edited_code
stringlengths
17
978k
original_code
stringlengths
17
978k
import getpass import hashlib import math import traceback import aiohttp from discord import (AsyncWebhookAdapter, Embed, File, RawReactionActionEvent, Webhook) from discord.ext import commands as c from module import item, status async def _webhook(all_error, url, ctx): for i in range(len(all_error)): while len("".join(all_error[i:i+2])) < 1800 and len("".join(all_error[i+1:])) != 0: all_error[i:i+2] = ["".join(all_error[i:i+2])] async with aiohttp.ClientSession() as session: w = Webhook.from_url(url, adapter=AsyncWebhookAdapter(session)) for i in range(0, len(all_error), 3): await w.send(file=File("variables.txt"), content=f"```py\n! ERROR:{ctx.author} ID:{ctx.author.id}\n! 鯖名:{ctx.guild} チャンネル名:{ctx.channel}\nBOTか否か:{ctx.author.bot}```", embeds=[Embed(title="TAO内部のError情報:", description=f"```py\n{y.replace("`", "")}```").set_footer(text=f"{i + x + 1}/{len(all_error)}") for x, y in enumerate(all_error[i:i + 3])]) class Cog(c.Cog): def __init__(self, bot): self.bot = bot @c.Cog.listener() async def on_command_error(self, ctx, error): if not __debug__: if any([isinstance(error, i) for i in [c.CommandInvokeError, c.CommandNotFound, c.BadArgument, c.UnexpectedQuoteError, c.ExpectedClosingQuoteError, c.InvalidEndOfQuotedStringError]]): traceback.print_exception(type(error), error, error.__traceback__) print(error.args) return elif isinstance(error, c.DisabledCommand): await ctx.send(embed=Embed(description="実行したコマンドは開発中か諸事情により開発者が無効化しています")) return l_error = traceback.format_exception( type(error), error, error.__traceback__) l_error = [x.replace(f"\\{getpass.getuser()}\\", "\\*\\") for x in l_error if "site-packages" not in x] webhook = await self.bot.fetch_webhook(712268338189041730) cnt = None hash_error = hashlib.sha512( bytes("".join(l_error), 'shift-jis')).hexdigest() async for message in webhook.channel.history(limit=None): if message.embeds: if message.embeds[0].footer.text == hash_error and message.embeds[0].author.name: if cnt is None: cnt = 1 + int(message.embeds[0].author.name[:-8]) await message.delete() cnt = cnt or 1 def is_limit(embeds, description=""): """FIELD LIMIT title 256 characters description 2048 characters fields Up to 25 field objects field.name 256 characters field.value 1024 characters footer.text 2048 characters author.name 256 characters Additionally, the characters in all title, description, field.name, field.value, footer.text, and author.name fields must not exceed 6000""" if len(embeds) == 0: embeds += [Embed(description=description)] return embeds, "" elif 9*sum([bool(e.description) for e in embeds])+sum(map(len, sum([[e.title, e.description, e.footer.text, e.author.name, *sum([[i.name, i.value] for i in e.fields], []), description] for e in embeds], []))) > 6000: return embeds, description elif len(embeds[-1].description)+len(description) <= 2048-9: if embeds[-1].description: embeds[-1].description += description else: embeds[-1].description = description return embeds, "" elif len(embeds) < 10: embeds += [Embed(description=description)] return embeds, "" else: return embeds, description top = Embed(title="{}: {}".format(type(error).__name__, error)[:256]).set_author( name=f"{cnt}回目のエラーです").set_footer(text=hash_error) l_embeds = [[top.copy()]] description = "" l_error += ["\n#END Traceback```\n**発生場所**\nGuild:{}(ID:{})\nchannel:{}(ID:{})\nuser:{}(ID:{})\nLink:[ここ]({})\n```escape".format( ctx.guild.name, ctx.guild.id, ctx.channel.name, ctx.channel.id, ctx.author.name, ctx.author.id, ctx.message.jump_url)] while l_error: if not description: description = l_error.pop(0) l_embeds[-1], description = is_limit(l_embeds[-1], description) if description: l_embeds += [[top.copy()]] for i in l_embeds: for j in i: j.description = "```py\n"+j.description+"```" for i, embeds in enumerate(l_embeds): await webhook.send(None if i else "<@&599220739815505941>修正よろしくね!", embeds=embeds, wait=True) if cnt == 1: item.obtain_an_item(ctx.author.id, -8) exp = math.ceil(status.get_player_level(ctx.author.id) / 7) first_err_msg = "\n\nあ、またバグが見つかったんだ。\nしかも今までにないエラーか\n<@{}>は{}の経験値と{}を得た。\n{}".format( ctx.author.id, exp, item.items.get("-8", {"name": "unknown"})["name"], status.experiment(ctx.author.id, exp)) else: first_err_msg = "" await ctx.send(embed=Embed(title="エラーが発生しました", description="発生したエラーは開発者が調査中です"+first_err_msg).set_footer(text="hash: "+hash_error)) def setup(bot): bot.add_cog(Cog(bot))
import getpass import hashlib import math import traceback import aiohttp from discord import (AsyncWebhookAdapter, Embed, File, RawReactionActionEvent, Webhook) from discord.ext import commands as c from module import item, status async def _webhook(all_error, url, ctx): for i in range(len(all_error)): while len("".join(all_error[i:i+2])) < 1800 and len("".join(all_error[i+1:])) != 0: all_error[i:i+2] = ["".join(all_error[i:i+2])] async with aiohttp.ClientSession() as session: w = Webhook.from_url(url, adapter=AsyncWebhookAdapter(session)) for i in range(0, len(all_error), 3): await w.send(file=File("variables.txt"), content=f"```py\n! ERROR:{ctx.author} ID:{ctx.author.id}\n! 鯖名:{ctx.guild} チャンネル名:{ctx.channel}\nBOTか否か:{ctx.author.bot}```", embeds=[Embed(title="TAO内部のError情報:", description=f"```py\n{y.replace('`', '')}```").set_footer(text=f"{i + x + 1}/{len(all_error)}") for x, y in enumerate(all_error[i:i + 3])]) class Cog(c.Cog): def __init__(self, bot): self.bot = bot @c.Cog.listener() async def on_command_error(self, ctx, error): if not __debug__: if any([isinstance(error, i) for i in [c.CommandInvokeError, c.CommandNotFound, c.BadArgument, c.UnexpectedQuoteError, c.ExpectedClosingQuoteError, c.InvalidEndOfQuotedStringError]]): traceback.print_exception(type(error), error, error.__traceback__) print(error.args) return elif isinstance(error, c.DisabledCommand): await ctx.send(embed=Embed(description="実行したコマンドは開発中か諸事情により開発者が無効化しています")) return l_error = traceback.format_exception( type(error), error, error.__traceback__) l_error = [x.replace(f"\\{getpass.getuser()}\\", "\\*\\") for x in l_error if "site-packages" not in x] webhook = await self.bot.fetch_webhook(712268338189041730) cnt = None hash_error = hashlib.sha512( bytes("".join(l_error), 'shift-jis')).hexdigest() async for message in webhook.channel.history(limit=None): if message.embeds: if message.embeds[0].footer.text == hash_error and message.embeds[0].author.name: if cnt is None: cnt = 1 + int(message.embeds[0].author.name[:-8]) await message.delete() cnt = cnt or 1 def is_limit(embeds, description=""): """FIELD LIMIT title 256 characters description 2048 characters fields Up to 25 field objects field.name 256 characters field.value 1024 characters footer.text 2048 characters author.name 256 characters Additionally, the characters in all title, description, field.name, field.value, footer.text, and author.name fields must not exceed 6000""" if len(embeds) == 0: embeds += [Embed(description=description)] return embeds, "" elif 9*sum([bool(e.description) for e in embeds])+sum(map(len, sum([[e.title, e.description, e.footer.text, e.author.name, *sum([[i.name, i.value] for i in e.fields], []), description] for e in embeds], []))) > 6000: return embeds, description elif len(embeds[-1].description)+len(description) <= 2048-9: if embeds[-1].description: embeds[-1].description += description else: embeds[-1].description = description return embeds, "" elif len(embeds) < 10: embeds += [Embed(description=description)] return embeds, "" else: return embeds, description top = Embed(title="{}: {}".format(type(error).__name__, error)[:256]).set_author( name=f"{cnt}回目のエラーです").set_footer(text=hash_error) l_embeds = [[top.copy()]] description = "" l_error += ["\n#END Traceback```\n**発生場所**\nGuild:{}(ID:{})\nchannel:{}(ID:{})\nuser:{}(ID:{})\nLink:[ここ]({})\n```escape".format( ctx.guild.name, ctx.guild.id, ctx.channel.name, ctx.channel.id, ctx.author.name, ctx.author.id, ctx.message.jump_url)] while l_error: if not description: description = l_error.pop(0) l_embeds[-1], description = is_limit(l_embeds[-1], description) if description: l_embeds += [[top.copy()]] for i in l_embeds: for j in i: j.description = "```py\n"+j.description+"```" for i, embeds in enumerate(l_embeds): await webhook.send(None if i else "<@&599220739815505941>修正よろしくね!", embeds=embeds, wait=True) if cnt == 1: item.obtain_an_item(ctx.author.id, -8) exp = math.ceil(status.get_player_level(ctx.author.id) / 7) first_err_msg = "\n\nあ、またバグが見つかったんだ。\nしかも今までにないエラーか\n<@{}>は{}の経験値と{}を得た。\n{}".format( ctx.author.id, exp, item.items.get("-8", {"name": "unknown"})["name"], status.experiment(ctx.author.id, exp)) else: first_err_msg = "" await ctx.send(embed=Embed(title="エラーが発生しました", description="発生したエラーは開発者が調査中です"+first_err_msg).set_footer(text="hash: "+hash_error)) def setup(bot): bot.add_cog(Cog(bot))
import sys import platform import warnings from pathlib import Path from functools import wraps import matplotlib as mpl import matplotlib.pyplot as plt import pkg_resources import pytest import astropy from astropy.wcs.wcs import FITSFixedWarning import sunpy.map __all__ = ['skip_windows', 'skip_glymur', 'skip_ana', 'skip_32bit', 'warnings_as_errors', 'asdf_entry_points'] # SunPy's JPEG2000 capabilities rely on the glymur library. # First we check to make sure that glymur imports correctly before proceeding. try: import glymur except ImportError: SKIP_GLYMUR = True else: # See if we have a C backend if glymur.lib.openjp2.OPENJP2: SKIP_GLYMUR = False else: SKIP_GLYMUR = True try: from sunpy.io import _pyana # NOQA except ImportError: SKIP_ANA = True else: SKIP_ANA = False if sys.maxsize > 2**32: SKIP_32 = False else: SKIP_32 = True skip_windows = pytest.mark.skipif(platform.system() == 'Windows', reason="Windows.") skip_glymur = pytest.mark.skipif(SKIP_GLYMUR, reason="Glymur can not be imported.") skip_ana = pytest.mark.skipif(SKIP_ANA, reason="ANA is not available.") skip_32bit = pytest.mark.skipif(SKIP_32, reason="Fails on a 32 bit system.") # Skip if the SunPy ASDF entry points are missing. asdf_entry_points = pytest.mark.skipif(not list(pkg_resources.iter_entry_points('asdf_extensions', 'sunpy')), reason="No SunPy ASDF entry points.") @pytest.fixture def warnings_as_errors(request): warnings.simplefilter('error') request.addfinalizer(lambda *args: warnings.resetwarnings()) new_hash_library = {} def get_hash_library_name(): """ Generate the hash library name for this env. """ import mpl_animators animators_version = "dev" if "+" in mpl_animators.__version__ else mpl_animators.__version__.replace('.', '') ft2_version = f"{mpl.ft2font.__freetype_version__.replace(".", "")}" mpl_version = "dev" if "+" in mpl.__version__ else mpl.__version__.replace('.', '') astropy_version = "dev" if "dev" in astropy.__version__ else astropy.__version__.replace('.', '') return f"figure_hashes_mpl_{mpl_version}_ft_{ft2_version}_astropy_{astropy_version}_animators_{animators_version}.json" def figure_test(test_function): """ A decorator for a test that verifies the hash of the current figure or the returned figure, with the name of the test function as the hash identifier in the library. A PNG is also created in the 'result_image' directory, which is created on the current path. All such decorated tests are marked with `pytest.mark.mpl_image` for convenient filtering. Examples -------- @figure_test def test_simple_plot(): plt.plot([0,1]) """ hash_library_name = get_hash_library_name() hash_library_file = Path(__file__).parent / hash_library_name @pytest.mark.remote_data @pytest.mark.mpl_image_compare(hash_library=hash_library_file, savefig_kwargs={'metadata': {'Software': None}}, style='default') @wraps(test_function) def test_wrapper(*args, **kwargs): ret = test_function(*args, **kwargs) if ret is None: ret = plt.gcf() return ret return test_wrapper def no_vso(f): """ Disable the VSO client from returning results via Fido during this test. """ from sunpy.net import Fido from sunpy.net.vso import VSOClient @wraps(f) def wrapper(*args, **kwargs): Fido.registry[VSOClient] = lambda *args: False res = f(*args, **kwargs) Fido.registry[VSOClient] = VSOClient._can_handle_query return res return wrapper def fix_map_wcs(smap): # Helper function to fix a WCS and silence the warnings with warnings.catch_warnings(): warnings.filterwarnings('ignore', category=FITSFixedWarning) wcs = smap.wcs wcs.fix() return sunpy.map.Map(smap.data, wcs)
import sys import platform import warnings from pathlib import Path from functools import wraps import matplotlib as mpl import matplotlib.pyplot as plt import pkg_resources import pytest import astropy from astropy.wcs.wcs import FITSFixedWarning import sunpy.map __all__ = ['skip_windows', 'skip_glymur', 'skip_ana', 'skip_32bit', 'warnings_as_errors', 'asdf_entry_points'] # SunPy's JPEG2000 capabilities rely on the glymur library. # First we check to make sure that glymur imports correctly before proceeding. try: import glymur except ImportError: SKIP_GLYMUR = True else: # See if we have a C backend if glymur.lib.openjp2.OPENJP2: SKIP_GLYMUR = False else: SKIP_GLYMUR = True try: from sunpy.io import _pyana # NOQA except ImportError: SKIP_ANA = True else: SKIP_ANA = False if sys.maxsize > 2**32: SKIP_32 = False else: SKIP_32 = True skip_windows = pytest.mark.skipif(platform.system() == 'Windows', reason="Windows.") skip_glymur = pytest.mark.skipif(SKIP_GLYMUR, reason="Glymur can not be imported.") skip_ana = pytest.mark.skipif(SKIP_ANA, reason="ANA is not available.") skip_32bit = pytest.mark.skipif(SKIP_32, reason="Fails on a 32 bit system.") # Skip if the SunPy ASDF entry points are missing. asdf_entry_points = pytest.mark.skipif(not list(pkg_resources.iter_entry_points('asdf_extensions', 'sunpy')), reason="No SunPy ASDF entry points.") @pytest.fixture def warnings_as_errors(request): warnings.simplefilter('error') request.addfinalizer(lambda *args: warnings.resetwarnings()) new_hash_library = {} def get_hash_library_name(): """ Generate the hash library name for this env. """ import mpl_animators animators_version = "dev" if "+" in mpl_animators.__version__ else mpl_animators.__version__.replace('.', '') ft2_version = f"{mpl.ft2font.__freetype_version__.replace('.', '')}" mpl_version = "dev" if "+" in mpl.__version__ else mpl.__version__.replace('.', '') astropy_version = "dev" if "dev" in astropy.__version__ else astropy.__version__.replace('.', '') return f"figure_hashes_mpl_{mpl_version}_ft_{ft2_version}_astropy_{astropy_version}_animators_{animators_version}.json" def figure_test(test_function): """ A decorator for a test that verifies the hash of the current figure or the returned figure, with the name of the test function as the hash identifier in the library. A PNG is also created in the 'result_image' directory, which is created on the current path. All such decorated tests are marked with `pytest.mark.mpl_image` for convenient filtering. Examples -------- @figure_test def test_simple_plot(): plt.plot([0,1]) """ hash_library_name = get_hash_library_name() hash_library_file = Path(__file__).parent / hash_library_name @pytest.mark.remote_data @pytest.mark.mpl_image_compare(hash_library=hash_library_file, savefig_kwargs={'metadata': {'Software': None}}, style='default') @wraps(test_function) def test_wrapper(*args, **kwargs): ret = test_function(*args, **kwargs) if ret is None: ret = plt.gcf() return ret return test_wrapper def no_vso(f): """ Disable the VSO client from returning results via Fido during this test. """ from sunpy.net import Fido from sunpy.net.vso import VSOClient @wraps(f) def wrapper(*args, **kwargs): Fido.registry[VSOClient] = lambda *args: False res = f(*args, **kwargs) Fido.registry[VSOClient] = VSOClient._can_handle_query return res return wrapper def fix_map_wcs(smap): # Helper function to fix a WCS and silence the warnings with warnings.catch_warnings(): warnings.filterwarnings('ignore', category=FITSFixedWarning) wcs = smap.wcs wcs.fix() return sunpy.map.Map(smap.data, wcs)
import os, re from mutagen.mp3 import EasyMP3 regex_old = re.compile(r"^(?P<title>.*) - (?P<name>.*)-(?P<mess>.{11}).mp3$") regex_new = re.compile(r"^(?P<name>.*) - (?P<title>.*)-(?P<mess>.{11}).mp3$") for filename in os.listdir("."): if '.mp3' in filename: print(f"Old name: {filename}") match_old = regex_old.match(filename) match_new = regex_new.match(filename) if filename.startswith("H3") and match_old: print(f"Mess: {match_old.group("mess")}") new_name = f"{match_old.group("title")} - {match_old.group("name")}.mp3" os.rename(filename, new_name) filename = new_name print(f"New name: {new_name}") elif match_new: print(f"Mess: {match_new.group("mess")}") new_name = f"{match_new.group("title")} - {match_new.group("name")}.mp3" os.rename(filename, new_name) filename = new_name print(f"New name: {new_name}") else: print(f"No change: {filename}") audio = EasyMP3(filename) audio["artist"] = "H3" audio["album"] = "H3 Podcast" audio.save()
import os, re from mutagen.mp3 import EasyMP3 regex_old = re.compile(r"^(?P<title>.*) - (?P<name>.*)-(?P<mess>.{11}).mp3$") regex_new = re.compile(r"^(?P<name>.*) - (?P<title>.*)-(?P<mess>.{11}).mp3$") for filename in os.listdir("."): if '.mp3' in filename: print(f"Old name: {filename}") match_old = regex_old.match(filename) match_new = regex_new.match(filename) if filename.startswith("H3") and match_old: print(f"Mess: {match_old.group('mess')}") new_name = f"{match_old.group('title')} - {match_old.group('name')}.mp3" os.rename(filename, new_name) filename = new_name print(f"New name: {new_name}") elif match_new: print(f"Mess: {match_new.group('mess')}") new_name = f"{match_new.group('title')} - {match_new.group('name')}.mp3" os.rename(filename, new_name) filename = new_name print(f"New name: {new_name}") else: print(f"No change: {filename}") audio = EasyMP3(filename) audio["artist"] = "H3" audio["album"] = "H3 Podcast" audio.save()
from __future__ import annotations import collections import math from typing import Any import networkx as nx import pandas as pd ACTOR_LABEL = 'actor' TRANSITION_ACTOR_LABEL = 'transition_actor' SPAWN_LABEL = 'spawn' NODE_TYPE_LABEL = 'node_type' SAVEW_EDGE_LABEL = 'save_warp' DEATHW_EDGE_LABEL = 'death_warp' SONGW_EDGE_LABEL = 'song_warp' BLUEW_EDGE_LABEL = 'blue_warp' EDGE_TYPE_LABEL = 'edge_type' CHILD_OW_SW = (52, 0) ADULT_OW_SW = (67, 7) # TODO: Handle requirements in SW _SW_SCENE_TO_TARGET_SCENES_AUX = { # Dungeons 0: [0], 1: [1], 2: [2], 3: [3], 4: [4], 5: [5], 6: [6], 7: [7], 8: [8], 9: [9], 10: [10], 11: [11], 12: [12], 13: [13], # Boss Rooms 17: [0], 18: [1], 19: [2], 20: [3], 21: [4], 22: [5], 23: [6], 24: [7], 25: [10], # Post Ganondorf 14: [10], 15: [10], 26: [10], 79: [10], # Link's House 52: [52], } SW_SCENE_TO_TARGET_SCENES = { i: [CHILD_OW_SW[0], ADULT_OW_SW[0]] for i in range(101) } SW_SCENE_TO_TARGET_SCENES.update(_SW_SCENE_TO_TARGET_SCENES_AUX) SCENE_TRANSITION_LIST = ( # Kok to Link's House ('s-459', 's-162'), # Link's House to Kok ('s-162', 's-459'), # Kok to Kok Shop ('s-460', 's-151'), # Kok Shop to Kok ('s-151', 's-460'), # Kok to Twins' ('s-464', 's-144'), # Twins' to Kok ('s-144', 's-464'), # Kak to Saria's ('s-466', 's-146'), # Saria's to Kak ('s-146', 's-466'), # Kok to Mido's ('s-465', 's-145'), # Mido's to Kok ('s-145', 's-465'), # Kok to Lost Woods (upper) ('s-462', 's-587'), # Lost Woods (upper) to Kok ('s-587', 's-462'), # Kok to Know-It-All's ('s-461', 's-143'), # Know-It-All's to Kok ('s-143', 's-461'), # Kok to Lost Woods (Bridge) ('s-458', 's-596'), # Lost Woods (Bridge) to Kok ('s-596', 's-458'), # Kok to Deku Tree ('s-457', 's-0'), # Deku Tree to Kok ('s-0', 's-457'), # Deku Tree to Gohma's Lair ('s-1', 's-61'), # Gohma's Lair to Deku Tree ('s-61', 's-1'), # Lost Woods to Hyrule Field ('s-595', 's-281'), # Hyrule Field to Lost Woods ('s-281', 's-595'), # Hyrule Field to Gerudo Valley ('s-283', 's-574'), # Gerudo Valley to Hyrule Field ('s-574', 's-283'), # Gerudo Valley to Gerudo's Fortress ('s-577', 's-627'), # Gerudo's Fortress to Gerudo Valley ('s-627', 's-577'), # Gerudo's Fortress to Haunted Wasteland ('s-642', 's-701'), # Haunted Wasteland to Gerudo's Fortress ('s-701', 's-642'), # Haunted Wasteland to Desert Colossus ('s-702', 's-608'), # Desert Colossus to Haunted Wasteland ('s-608', 's-702'), # Ice cavern to Zora's Fountain s2 ('s-21', 's-560'), # Zora's Fountain s2 to Ice Cavern ('s-560', 's-21'), # Windmill to Kak s0 ('s-260', 's-349'), # Kak s0 to Windmill ('s-349', 's-260'), # ## Transitions for single component with warps ## # GTG to GF s2 ('s-27', 's-659'), # GF s2 to GTG ('s-659', 's-27'), # Ganon's Castle to Ganon's Tower ('s-42', 's-24'), # Ganon's Tower to Ganon's Castle ('s-24', 's-42'), ) SAMPLE_TRANSITION_LIST = ( # Kok to Link's House ('s-459', 's-162'), # Link's House to Kok ('s-162', 's-459'), # Kok to Kok Shop ('s-460', 's-151'), # Kok Shop to Kok ('s-151', 's-460'), # Kok to Twins' ('s-464', 's-144'), # Twins' to Kok ('s-144', 's-464'), # Kak to Saria's ('s-466', 's-146'), # Saria's to Kak ('s-146', 's-466'), # Kok to Mido's ('s-465', 's-145'), # Mido's to Kok ('s-145', 's-465'), # Kok to Lost Woods (upper) ('s-462', 's-587'), # Lost Woods (upper) to Kok ('s-587', 's-462'), # Kok to Know-It-All's ('s-461', 's-143'), # Know-It-All's to Kok ('s-143', 's-461'), # Kok to Lost Woods (Bridge) ('s-458', 's-596'), # Lost Woods (Bridge) to Kok ('s-596', 's-458'), # Kok to Deku Tree ('s-457', 's-0'), # Deku Tree to Kok ('s-0', 's-457'), # Deku Tree to Gohma's Lair ('s-1', 's-61'), # Gohma's Lair to Deku Tree ('s-61', 's-1'), # Gohma's Blue Warp to Kok ('2633', 's-467'), ) BLUE_WARP_EDGE_LIST = ( # Queen Gohma to Kok ('2633', 's-467'), # King Dodongo to DMT ('2643', 's-713'), # Barinade to ZF ('2650', 's-545'), # Phantom Ganon to ('2657', 's-510'), # Volvagia to DMC ('2659', 's-735'), # Morpha to LH ('2660', 's-531'), # Twinrova to DC ('2731', 's-624'), # Bongo Bongo to Graveyard ('2741', 's-434'), ) # TODO: Add requirements SONG_WARP_DESTINATION_LIST = [ # Minuet 's-510', # Buleru 's-735', # Serenade 's-531', # Requiem 's-624', # Nocturne 's-434', # Prelude 's-230' ] NO_WARP_SONGS_SCENES = { 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 66, 68, 69, 70, 71, 73, 74, 75, 78, 79, } def build_room_actors_components(actors_df: pd.DataFrame, scene: int, setup: int, is_cutscene: bool, node_type: str) -> nx.MultiDiGraph: """ Build a graph with one component for every room in `actors_df` that has at least one actor. Each individual component will form a complete graph. Additional data in `actors_df` will be added to the nodes as attributes. Args: actors_df: `pandas.DataFrame` containing the actor data scene: scene to build setup: setup to pick from scene setups is_cutscene: whether to pick cutscene setups node_type: label to set the `NODE_TYPE_LABEL` attribute to. Must be in ('ACTOR_LABEL', SPAWN_LABEL) (see module constants). Returns: A new networkx.MultiDiGraph object resembling the given actors. """ if node_type not in (ACTOR_LABEL, SPAWN_LABEL): raise ValueError(f"{NODE_TYPE_LABEL} is {node_type}," f"expected one of: {(ACTOR_LABEL, SPAWN_LABEL)} (see vars of ogb)") scene_actors_df = actors_df.loc[(actors_df['scene'] == scene) & (actors_df['setup'] == setup) & (actors_df['is_cutscene'] == is_cutscene)] if len(scene_actors_df.index) == 0: return nx.MultiDiGraph() rooms = {x['room'] for _, x in scene_actors_df.iterrows()} room_actors_dfs = [scene_actors_df.loc[(scene_actors_df['room']) == r] for r in rooms] g_rooms = [nx.complete_graph(x.index, nx.MultiDiGraph) for x in room_actors_dfs] room_actors_dicts = [df.to_dict('index') for df in room_actors_dfs] for g_room, room_actor_dict in zip(g_rooms, room_actors_dicts): nx.set_node_attributes(g_room, room_actor_dict) nx.set_node_attributes(g_room, node_type, NODE_TYPE_LABEL) return nx.union_all(g_rooms) def build_transition_actors(transition_actors_df: pd.DataFrame, scene: int, setup: int, is_cutscene: bool) -> nx.MultiDiGraph: g_transit = nx.MultiDiGraph() scene_transit_df: pd.DataFrame = transition_actors_df.loc[(transition_actors_df['scene'] == scene) & (transition_actors_df['setup'] == setup) & (transition_actors_df['is_cutscene'] == is_cutscene)] if len(scene_transit_df.index) == 0: return g_transit scene_transit_dict = scene_transit_df.to_dict('index') g_transit.add_nodes_from([(k, v) for k, v in scene_transit_dict.items()]) nodes = g_transit.nodes(data=True) # Connect transition nodes with each other if they are adjacent to the same room for it, it_data in nodes: for other, other_data in nodes: if it != other: it_targets = {it_data['exiting_room'], it_data['entering_room']} other_targets = {other_data['exiting_room'], other_data['entering_room']} if not it_targets.isdisjoint(other_targets): g_transit.add_edge(it, other) nx.set_node_attributes(g_transit, TRANSITION_ACTOR_LABEL, NODE_TYPE_LABEL) return g_transit def build_scene_graph(spawns_df: pd.DataFrame, actors_df: pd.DataFrame, transit_actors_df: pd.DataFrame, scene: int, setup: int, is_cutscene: bool = False, rename: tuple[str, str, str] = ('s-', '', 't-')) -> nx.MultiDiGraph: """ Builds the entire scene as a `networkx.MultiDiGraph` . Includes room actors, spawns and transition actors. Spawns and room actors will be nodes of one complete graph per room, transition actors will be connected with all actors in adjacent rooms, including other transition actors. Other data in DataField objects will be added as node attributes. `NODE_TYPE_LABEL` labeled attribute will be given to all edges (see module constants); `ACTOR_LABEL` to room actors, `SPAWN_LABEL` to spawns and `TRANSITION_ACTOR_LABEL` to transition actors. Args: spawns_df: pandas.DataField with spawn data actors_df: pandas.DataField with room actor data transit_actors_df: pandas.DataField with transition actor data scene: scene to build setup: setup to pick from scene setups is_cutscene: whether to pick cutscene setups rename: renaming tuple (spawns_rename, actors_rename, transit_rename) (see networkx.union() ) Returns: A networkx.MultiDiGraph() with all room actors, transition actors and spawns as nodes. """ g_room_actors = build_room_actors_components(actors_df, scene, setup, is_cutscene, ACTOR_LABEL) g_spawns = build_room_actors_components(spawns_df, scene, setup, is_cutscene, SPAWN_LABEL) g_transit_actors = build_transition_actors(transit_actors_df, scene, setup, is_cutscene) g_spawns_and_actors = union_spawns_and_actors(g_spawns, g_room_actors, rename[:2]) g_scene = union_actors_and_transition_actors(g_spawns_and_actors, g_transit_actors, node_rename=('', rename[2])) return g_scene def union_spawns_and_actors(g_spawns: nx.MultiDiGraph, g_actors: nx.MultiDiGraph, rename: tuple[str, str] = ('s-', ''), set_node_type_label: bool = True) -> nx.MultiDiGraph: if not g_spawns and not g_actors: return nx.MultiDiGraph() if rename[0] == rename[1]: raise ValueError(f"{rename = }; elements must differ do distinguish them in union graph.") if set_node_type_label: nx.set_node_attributes(g_spawns, SPAWN_LABEL, NODE_TYPE_LABEL) nx.set_node_attributes(g_actors, ACTOR_LABEL, NODE_TYPE_LABEL) spawns = g_spawns.nodes(data='room') actors = g_actors.nodes(data='room') renamed_spawns = [(rename[0] + str(s), r) for s, r in spawns] renamed_actors = [(rename[1] + str(a), r) for a, r in actors] g: nx.MultiDiGraph = nx.union(g_spawns, g_actors, rename) for spawn, s_room in renamed_spawns: for actor, a_room in renamed_actors: if s_room == a_room: g.add_edge(spawn, actor) g.add_edge(actor, spawn) return g def union_actors_and_transition_actors(g_actors: nx.MultiDiGraph, g_transition_actors: nx.MultiDiGraph, disjoint: bool = False, graph_rename: str = None, node_rename: tuple[str, str] = None, connect_transition_actors: bool = True, set_node_type_label: bool = False) -> nx.MultiDiGraph: """ Union actors graph with transition actors graph and connecting actors with transitions. With `disjoint=True` : note the relabeling from `0` to `(len(g_actors) + len(g_transition_actors) -1)`. Also note that this function will assign an attribute `'node_type'` to the nodes of both input graphs in-place, `'actor'` or `'transition_actor'` respectively. Args: g_actors: networkx.MultiDiGraph containing the actors g_transition_actors: networkx.MultiDiGraph containing the transition actors disjoint: Whether or not to do a disjoint union (see networkx.union() and networkx.disjoint_union() ) graph_rename: Name of the resulting new graph when using non-disjoint union (see networkx.union() ) node_rename: Renaming tuple when using non-disjoint union (see networkx.union() ) connect_transition_actors: Whether or not to connect actors with transition actors in the new graph set_node_type_label: Whether or not to set NODE_TYPE_LABEL node attribute to ACTOR_LABEL and TRANSITION_ACTOR_LABEL (see module constants) Returns: New graph with connected actors and transition actors """ if not g_actors and not g_transition_actors: return nx.MultiDiGraph() if set_node_type_label: nx.set_node_attributes(g_actors, ACTOR_LABEL, NODE_TYPE_LABEL) nx.set_node_attributes(g_transition_actors, TRANSITION_ACTOR_LABEL, NODE_TYPE_LABEL) if disjoint: g: nx.MultiDiGraph = nx.disjoint_union(g_actors, g_transition_actors) else: g: nx.MultiDiGraph = nx.union(g_actors, g_transition_actors, rename=node_rename, name=graph_rename) if connect_transition_actors: transit_nodes = [] actor_nodes = [] for n, data in g.nodes(data=True): node_type = data[NODE_TYPE_LABEL] if node_type in (ACTOR_LABEL, SPAWN_LABEL): actor_nodes.append((n, data)) elif node_type == TRANSITION_ACTOR_LABEL: transit_nodes.append((n, data)) transit_edge_list = [] for t, t_data in transit_nodes: for a, a_data in actor_nodes: if a_data['room'] in (t_data['entering_room'], t_data['exiting_room']): transit_edge_list.append((a, t)) transit_edge_list.append((t, a)) g.add_edges_from(transit_edge_list) return g def get_telling_unique_node_label(node_dict: dict) -> str: node_type = str(node_dict[NODE_TYPE_LABEL]) if NODE_TYPE_LABEL in node_dict else '' scene = f"s{str(node_dict["scene"])}" room = f"r{str(node_dict["room"])}" if 'room' in node_dict else '' setup = f"setup{str(node_dict["setup"])}" is_cutscene = 'cutscene' if node_dict['is_cutscene'] else '' idx = f"idx{str(node_dict["idx"])}" return f"{node_type}{scene}{room}{setup}{is_cutscene}{idx}" def get_pos_dict(nodes_container: pd.DataFrame | nx.Graph, mirrored_over_x_axis=False) -> dict[Any, tuple[int, int]]: try: nodes = nodes_container.iterrows() except AttributeError: try: nodes = nodes_container.nodes(data=True) except AttributeError: raise TypeError("Container is neither a pandas.DataFrame nor a networkx.Graph.") return {k: (v['pos_x'], v['pos_z'] if not mirrored_over_x_axis else -v['pos_z']) for k, v in nodes} def get_normalized_pos_dict(nodes_container: pd.DataFrame | nx.Graph, mirrored_over_x_axis=False, preserve_ratio=True) -> dict[Any, tuple[int, int]]: res = get_pos_dict(nodes_container, mirrored_over_x_axis) # TODO: Maybe work with tuples here? pos = [(x, y) for _, (x, y) in res.items()] max_x = max(x for x, _ in pos) min_x = min(x for x, _ in pos) span_x = max_x - min_x max_y = max(y for _, y in pos) min_y = min(y for _, y in pos) span_y = max_y - min_y scale_x = (span_x / max(span_x, span_y)) if span_x and preserve_ratio else 1 scale_y = (span_y / max(span_x, span_y)) if span_y and preserve_ratio else 1 return {k: ((vx - min_x) / (span_x if span_x else 1) * scale_x, (vy - min_y) / (span_y if span_y else 1) * scale_y) for k, (vx, vy) in res.items()} def build_scenes( spawns_df: pd.DataFrame, actors_df: pd.DataFrame, transit_actors_df: pd.DataFrame, scenes: list[int], setups: list[int], cutscenes_included: list[bool], scene_transition_list: list[tuple] = None) -> tuple[nx.MultiDiGraph, dict]: g_scenes = [g_scene for sc in scenes for is_cutscene in cutscenes_included for se in setups if (g_scene := build_scene_graph(spawns_df, actors_df, transit_actors_df, sc, se, is_cutscene))] pos_dicts = [get_normalized_pos_dict(g_sc, True) for g_sc in g_scenes] # Define how many scene setups to put in each row and column rows = math.ceil(len(g_scenes) ** 0.5) # Compute coords for orderly lines for i, pos_dict in enumerate(pos_dicts): pos_dicts[i] = {k: ((x + ((i + rows) % rows) * 1.2), y + (((rows + i) // rows) - 1) * 1.2) for k, (x, y) in pos_dict.items()} g_union: nx.MultiDiGraph = nx.union_all(g_scenes) if scene_transition_list: g_union.add_edges_from(scene_transition_list) pos_res = {} for d in pos_dicts: pos_res |= d return g_union, pos_res def add_save_warps(g_scenes: nx.MultiDiGraph, sw_duration: float = None) -> nx.MultiDiGraph: if not g_scenes: return nx.MultiDiGraph() g: nx.MultiDiGraph = g_scenes.copy() # TODO: Handle partial game graphs; add requirements (age) nodes = g.nodes(data=True) d = {EDGE_TYPE_LABEL: SAVEW_EDGE_LABEL} targets = {item for sublist in SW_SCENE_TO_TARGET_SCENES.values() for item in sublist} sw_scene_to_spawn = {s: n for n, data in nodes if ((s := data['scene']) in targets and data[NODE_TYPE_LABEL] == SPAWN_LABEL and data['idx'] == (0 if s != ADULT_OW_SW[0] else ADULT_OW_SW[1]))} for n, data in nodes: if (s := data['scene']) in SW_SCENE_TO_TARGET_SCENES: for target in SW_SCENE_TO_TARGET_SCENES[s]: if sw_duration: g.add_edge(n, sw_scene_to_spawn[target], **d, weight=sw_duration) else: g.add_edge(n, sw_scene_to_spawn[target], **d) return g def add_death_warps(g_scenes: nx.MultiDiGraph, dw_duration: float = None) -> nx.MultiDiGraph: if not g_scenes: return nx.MultiDiGraph() g: nx.MultiDiGraph = g_scenes.copy() # TODO: Add requirements, Handle Boss rooms better nodes = g.nodes(data=True) d = {EDGE_TYPE_LABEL: DEATHW_EDGE_LABEL} spawn_dict = collections.defaultdict(list) node_dict = collections.defaultdict(list) # Add nodes to spawn and node pools by scene, cutscene and setup for n, data in nodes: key = (data['scene'], data['is_cutscene'], data['setup']) node_dict[key].append(n) if data[NODE_TYPE_LABEL] == SPAWN_LABEL: spawn_dict[key].append(n) # Connect nodes with spawns of equally keyed pool for k, nodes in node_dict.items(): for node in nodes: for spawn in spawn_dict[k]: if dw_duration: g.add_edge(node, spawn, **d, weight=dw_duration) else: g.add_edge(node, spawn, **d) return g def add_song_warps(g_scenes: nx.MultiDiGraph, sw_duration: float = None) -> nx.MultiDiGraph: if not g_scenes: return nx.MultiDiGraph() g: nx.MultiDiGraph = g_scenes.copy() # TODO: Handle partial graphs; add requirements nodes = g.nodes(data=True) d = {EDGE_TYPE_LABEL: SONGW_EDGE_LABEL} for n, data in nodes: if data['scene'] not in NO_WARP_SONGS_SCENES: for dest in SONG_WARP_DESTINATION_LIST: if sw_duration is not None: g.add_edge(n, dest, **d, weight=sw_duration) else: g.add_edge(n, dest, **d) return g
from __future__ import annotations import collections import math from typing import Any import networkx as nx import pandas as pd ACTOR_LABEL = 'actor' TRANSITION_ACTOR_LABEL = 'transition_actor' SPAWN_LABEL = 'spawn' NODE_TYPE_LABEL = 'node_type' SAVEW_EDGE_LABEL = 'save_warp' DEATHW_EDGE_LABEL = 'death_warp' SONGW_EDGE_LABEL = 'song_warp' BLUEW_EDGE_LABEL = 'blue_warp' EDGE_TYPE_LABEL = 'edge_type' CHILD_OW_SW = (52, 0) ADULT_OW_SW = (67, 7) # TODO: Handle requirements in SW _SW_SCENE_TO_TARGET_SCENES_AUX = { # Dungeons 0: [0], 1: [1], 2: [2], 3: [3], 4: [4], 5: [5], 6: [6], 7: [7], 8: [8], 9: [9], 10: [10], 11: [11], 12: [12], 13: [13], # Boss Rooms 17: [0], 18: [1], 19: [2], 20: [3], 21: [4], 22: [5], 23: [6], 24: [7], 25: [10], # Post Ganondorf 14: [10], 15: [10], 26: [10], 79: [10], # Link's House 52: [52], } SW_SCENE_TO_TARGET_SCENES = { i: [CHILD_OW_SW[0], ADULT_OW_SW[0]] for i in range(101) } SW_SCENE_TO_TARGET_SCENES.update(_SW_SCENE_TO_TARGET_SCENES_AUX) SCENE_TRANSITION_LIST = ( # Kok to Link's House ('s-459', 's-162'), # Link's House to Kok ('s-162', 's-459'), # Kok to Kok Shop ('s-460', 's-151'), # Kok Shop to Kok ('s-151', 's-460'), # Kok to Twins' ('s-464', 's-144'), # Twins' to Kok ('s-144', 's-464'), # Kak to Saria's ('s-466', 's-146'), # Saria's to Kak ('s-146', 's-466'), # Kok to Mido's ('s-465', 's-145'), # Mido's to Kok ('s-145', 's-465'), # Kok to Lost Woods (upper) ('s-462', 's-587'), # Lost Woods (upper) to Kok ('s-587', 's-462'), # Kok to Know-It-All's ('s-461', 's-143'), # Know-It-All's to Kok ('s-143', 's-461'), # Kok to Lost Woods (Bridge) ('s-458', 's-596'), # Lost Woods (Bridge) to Kok ('s-596', 's-458'), # Kok to Deku Tree ('s-457', 's-0'), # Deku Tree to Kok ('s-0', 's-457'), # Deku Tree to Gohma's Lair ('s-1', 's-61'), # Gohma's Lair to Deku Tree ('s-61', 's-1'), # Lost Woods to Hyrule Field ('s-595', 's-281'), # Hyrule Field to Lost Woods ('s-281', 's-595'), # Hyrule Field to Gerudo Valley ('s-283', 's-574'), # Gerudo Valley to Hyrule Field ('s-574', 's-283'), # Gerudo Valley to Gerudo's Fortress ('s-577', 's-627'), # Gerudo's Fortress to Gerudo Valley ('s-627', 's-577'), # Gerudo's Fortress to Haunted Wasteland ('s-642', 's-701'), # Haunted Wasteland to Gerudo's Fortress ('s-701', 's-642'), # Haunted Wasteland to Desert Colossus ('s-702', 's-608'), # Desert Colossus to Haunted Wasteland ('s-608', 's-702'), # Ice cavern to Zora's Fountain s2 ('s-21', 's-560'), # Zora's Fountain s2 to Ice Cavern ('s-560', 's-21'), # Windmill to Kak s0 ('s-260', 's-349'), # Kak s0 to Windmill ('s-349', 's-260'), # ## Transitions for single component with warps ## # GTG to GF s2 ('s-27', 's-659'), # GF s2 to GTG ('s-659', 's-27'), # Ganon's Castle to Ganon's Tower ('s-42', 's-24'), # Ganon's Tower to Ganon's Castle ('s-24', 's-42'), ) SAMPLE_TRANSITION_LIST = ( # Kok to Link's House ('s-459', 's-162'), # Link's House to Kok ('s-162', 's-459'), # Kok to Kok Shop ('s-460', 's-151'), # Kok Shop to Kok ('s-151', 's-460'), # Kok to Twins' ('s-464', 's-144'), # Twins' to Kok ('s-144', 's-464'), # Kak to Saria's ('s-466', 's-146'), # Saria's to Kak ('s-146', 's-466'), # Kok to Mido's ('s-465', 's-145'), # Mido's to Kok ('s-145', 's-465'), # Kok to Lost Woods (upper) ('s-462', 's-587'), # Lost Woods (upper) to Kok ('s-587', 's-462'), # Kok to Know-It-All's ('s-461', 's-143'), # Know-It-All's to Kok ('s-143', 's-461'), # Kok to Lost Woods (Bridge) ('s-458', 's-596'), # Lost Woods (Bridge) to Kok ('s-596', 's-458'), # Kok to Deku Tree ('s-457', 's-0'), # Deku Tree to Kok ('s-0', 's-457'), # Deku Tree to Gohma's Lair ('s-1', 's-61'), # Gohma's Lair to Deku Tree ('s-61', 's-1'), # Gohma's Blue Warp to Kok ('2633', 's-467'), ) BLUE_WARP_EDGE_LIST = ( # Queen Gohma to Kok ('2633', 's-467'), # King Dodongo to DMT ('2643', 's-713'), # Barinade to ZF ('2650', 's-545'), # Phantom Ganon to ('2657', 's-510'), # Volvagia to DMC ('2659', 's-735'), # Morpha to LH ('2660', 's-531'), # Twinrova to DC ('2731', 's-624'), # Bongo Bongo to Graveyard ('2741', 's-434'), ) # TODO: Add requirements SONG_WARP_DESTINATION_LIST = [ # Minuet 's-510', # Buleru 's-735', # Serenade 's-531', # Requiem 's-624', # Nocturne 's-434', # Prelude 's-230' ] NO_WARP_SONGS_SCENES = { 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 66, 68, 69, 70, 71, 73, 74, 75, 78, 79, } def build_room_actors_components(actors_df: pd.DataFrame, scene: int, setup: int, is_cutscene: bool, node_type: str) -> nx.MultiDiGraph: """ Build a graph with one component for every room in `actors_df` that has at least one actor. Each individual component will form a complete graph. Additional data in `actors_df` will be added to the nodes as attributes. Args: actors_df: `pandas.DataFrame` containing the actor data scene: scene to build setup: setup to pick from scene setups is_cutscene: whether to pick cutscene setups node_type: label to set the `NODE_TYPE_LABEL` attribute to. Must be in ('ACTOR_LABEL', SPAWN_LABEL) (see module constants). Returns: A new networkx.MultiDiGraph object resembling the given actors. """ if node_type not in (ACTOR_LABEL, SPAWN_LABEL): raise ValueError(f"{NODE_TYPE_LABEL} is {node_type}," f"expected one of: {(ACTOR_LABEL, SPAWN_LABEL)} (see vars of ogb)") scene_actors_df = actors_df.loc[(actors_df['scene'] == scene) & (actors_df['setup'] == setup) & (actors_df['is_cutscene'] == is_cutscene)] if len(scene_actors_df.index) == 0: return nx.MultiDiGraph() rooms = {x['room'] for _, x in scene_actors_df.iterrows()} room_actors_dfs = [scene_actors_df.loc[(scene_actors_df['room']) == r] for r in rooms] g_rooms = [nx.complete_graph(x.index, nx.MultiDiGraph) for x in room_actors_dfs] room_actors_dicts = [df.to_dict('index') for df in room_actors_dfs] for g_room, room_actor_dict in zip(g_rooms, room_actors_dicts): nx.set_node_attributes(g_room, room_actor_dict) nx.set_node_attributes(g_room, node_type, NODE_TYPE_LABEL) return nx.union_all(g_rooms) def build_transition_actors(transition_actors_df: pd.DataFrame, scene: int, setup: int, is_cutscene: bool) -> nx.MultiDiGraph: g_transit = nx.MultiDiGraph() scene_transit_df: pd.DataFrame = transition_actors_df.loc[(transition_actors_df['scene'] == scene) & (transition_actors_df['setup'] == setup) & (transition_actors_df['is_cutscene'] == is_cutscene)] if len(scene_transit_df.index) == 0: return g_transit scene_transit_dict = scene_transit_df.to_dict('index') g_transit.add_nodes_from([(k, v) for k, v in scene_transit_dict.items()]) nodes = g_transit.nodes(data=True) # Connect transition nodes with each other if they are adjacent to the same room for it, it_data in nodes: for other, other_data in nodes: if it != other: it_targets = {it_data['exiting_room'], it_data['entering_room']} other_targets = {other_data['exiting_room'], other_data['entering_room']} if not it_targets.isdisjoint(other_targets): g_transit.add_edge(it, other) nx.set_node_attributes(g_transit, TRANSITION_ACTOR_LABEL, NODE_TYPE_LABEL) return g_transit def build_scene_graph(spawns_df: pd.DataFrame, actors_df: pd.DataFrame, transit_actors_df: pd.DataFrame, scene: int, setup: int, is_cutscene: bool = False, rename: tuple[str, str, str] = ('s-', '', 't-')) -> nx.MultiDiGraph: """ Builds the entire scene as a `networkx.MultiDiGraph` . Includes room actors, spawns and transition actors. Spawns and room actors will be nodes of one complete graph per room, transition actors will be connected with all actors in adjacent rooms, including other transition actors. Other data in DataField objects will be added as node attributes. `NODE_TYPE_LABEL` labeled attribute will be given to all edges (see module constants); `ACTOR_LABEL` to room actors, `SPAWN_LABEL` to spawns and `TRANSITION_ACTOR_LABEL` to transition actors. Args: spawns_df: pandas.DataField with spawn data actors_df: pandas.DataField with room actor data transit_actors_df: pandas.DataField with transition actor data scene: scene to build setup: setup to pick from scene setups is_cutscene: whether to pick cutscene setups rename: renaming tuple (spawns_rename, actors_rename, transit_rename) (see networkx.union() ) Returns: A networkx.MultiDiGraph() with all room actors, transition actors and spawns as nodes. """ g_room_actors = build_room_actors_components(actors_df, scene, setup, is_cutscene, ACTOR_LABEL) g_spawns = build_room_actors_components(spawns_df, scene, setup, is_cutscene, SPAWN_LABEL) g_transit_actors = build_transition_actors(transit_actors_df, scene, setup, is_cutscene) g_spawns_and_actors = union_spawns_and_actors(g_spawns, g_room_actors, rename[:2]) g_scene = union_actors_and_transition_actors(g_spawns_and_actors, g_transit_actors, node_rename=('', rename[2])) return g_scene def union_spawns_and_actors(g_spawns: nx.MultiDiGraph, g_actors: nx.MultiDiGraph, rename: tuple[str, str] = ('s-', ''), set_node_type_label: bool = True) -> nx.MultiDiGraph: if not g_spawns and not g_actors: return nx.MultiDiGraph() if rename[0] == rename[1]: raise ValueError(f"{rename = }; elements must differ do distinguish them in union graph.") if set_node_type_label: nx.set_node_attributes(g_spawns, SPAWN_LABEL, NODE_TYPE_LABEL) nx.set_node_attributes(g_actors, ACTOR_LABEL, NODE_TYPE_LABEL) spawns = g_spawns.nodes(data='room') actors = g_actors.nodes(data='room') renamed_spawns = [(rename[0] + str(s), r) for s, r in spawns] renamed_actors = [(rename[1] + str(a), r) for a, r in actors] g: nx.MultiDiGraph = nx.union(g_spawns, g_actors, rename) for spawn, s_room in renamed_spawns: for actor, a_room in renamed_actors: if s_room == a_room: g.add_edge(spawn, actor) g.add_edge(actor, spawn) return g def union_actors_and_transition_actors(g_actors: nx.MultiDiGraph, g_transition_actors: nx.MultiDiGraph, disjoint: bool = False, graph_rename: str = None, node_rename: tuple[str, str] = None, connect_transition_actors: bool = True, set_node_type_label: bool = False) -> nx.MultiDiGraph: """ Union actors graph with transition actors graph and connecting actors with transitions. With `disjoint=True` : note the relabeling from `0` to `(len(g_actors) + len(g_transition_actors) -1)`. Also note that this function will assign an attribute `'node_type'` to the nodes of both input graphs in-place, `'actor'` or `'transition_actor'` respectively. Args: g_actors: networkx.MultiDiGraph containing the actors g_transition_actors: networkx.MultiDiGraph containing the transition actors disjoint: Whether or not to do a disjoint union (see networkx.union() and networkx.disjoint_union() ) graph_rename: Name of the resulting new graph when using non-disjoint union (see networkx.union() ) node_rename: Renaming tuple when using non-disjoint union (see networkx.union() ) connect_transition_actors: Whether or not to connect actors with transition actors in the new graph set_node_type_label: Whether or not to set NODE_TYPE_LABEL node attribute to ACTOR_LABEL and TRANSITION_ACTOR_LABEL (see module constants) Returns: New graph with connected actors and transition actors """ if not g_actors and not g_transition_actors: return nx.MultiDiGraph() if set_node_type_label: nx.set_node_attributes(g_actors, ACTOR_LABEL, NODE_TYPE_LABEL) nx.set_node_attributes(g_transition_actors, TRANSITION_ACTOR_LABEL, NODE_TYPE_LABEL) if disjoint: g: nx.MultiDiGraph = nx.disjoint_union(g_actors, g_transition_actors) else: g: nx.MultiDiGraph = nx.union(g_actors, g_transition_actors, rename=node_rename, name=graph_rename) if connect_transition_actors: transit_nodes = [] actor_nodes = [] for n, data in g.nodes(data=True): node_type = data[NODE_TYPE_LABEL] if node_type in (ACTOR_LABEL, SPAWN_LABEL): actor_nodes.append((n, data)) elif node_type == TRANSITION_ACTOR_LABEL: transit_nodes.append((n, data)) transit_edge_list = [] for t, t_data in transit_nodes: for a, a_data in actor_nodes: if a_data['room'] in (t_data['entering_room'], t_data['exiting_room']): transit_edge_list.append((a, t)) transit_edge_list.append((t, a)) g.add_edges_from(transit_edge_list) return g def get_telling_unique_node_label(node_dict: dict) -> str: node_type = str(node_dict[NODE_TYPE_LABEL]) if NODE_TYPE_LABEL in node_dict else '' scene = f"s{str(node_dict['scene'])}" room = f"r{str(node_dict['room'])}" if 'room' in node_dict else '' setup = f"setup{str(node_dict['setup'])}" is_cutscene = 'cutscene' if node_dict['is_cutscene'] else '' idx = f"idx{str(node_dict['idx'])}" return f"{node_type}{scene}{room}{setup}{is_cutscene}{idx}" def get_pos_dict(nodes_container: pd.DataFrame | nx.Graph, mirrored_over_x_axis=False) -> dict[Any, tuple[int, int]]: try: nodes = nodes_container.iterrows() except AttributeError: try: nodes = nodes_container.nodes(data=True) except AttributeError: raise TypeError("Container is neither a pandas.DataFrame nor a networkx.Graph.") return {k: (v['pos_x'], v['pos_z'] if not mirrored_over_x_axis else -v['pos_z']) for k, v in nodes} def get_normalized_pos_dict(nodes_container: pd.DataFrame | nx.Graph, mirrored_over_x_axis=False, preserve_ratio=True) -> dict[Any, tuple[int, int]]: res = get_pos_dict(nodes_container, mirrored_over_x_axis) # TODO: Maybe work with tuples here? pos = [(x, y) for _, (x, y) in res.items()] max_x = max(x for x, _ in pos) min_x = min(x for x, _ in pos) span_x = max_x - min_x max_y = max(y for _, y in pos) min_y = min(y for _, y in pos) span_y = max_y - min_y scale_x = (span_x / max(span_x, span_y)) if span_x and preserve_ratio else 1 scale_y = (span_y / max(span_x, span_y)) if span_y and preserve_ratio else 1 return {k: ((vx - min_x) / (span_x if span_x else 1) * scale_x, (vy - min_y) / (span_y if span_y else 1) * scale_y) for k, (vx, vy) in res.items()} def build_scenes( spawns_df: pd.DataFrame, actors_df: pd.DataFrame, transit_actors_df: pd.DataFrame, scenes: list[int], setups: list[int], cutscenes_included: list[bool], scene_transition_list: list[tuple] = None) -> tuple[nx.MultiDiGraph, dict]: g_scenes = [g_scene for sc in scenes for is_cutscene in cutscenes_included for se in setups if (g_scene := build_scene_graph(spawns_df, actors_df, transit_actors_df, sc, se, is_cutscene))] pos_dicts = [get_normalized_pos_dict(g_sc, True) for g_sc in g_scenes] # Define how many scene setups to put in each row and column rows = math.ceil(len(g_scenes) ** 0.5) # Compute coords for orderly lines for i, pos_dict in enumerate(pos_dicts): pos_dicts[i] = {k: ((x + ((i + rows) % rows) * 1.2), y + (((rows + i) // rows) - 1) * 1.2) for k, (x, y) in pos_dict.items()} g_union: nx.MultiDiGraph = nx.union_all(g_scenes) if scene_transition_list: g_union.add_edges_from(scene_transition_list) pos_res = {} for d in pos_dicts: pos_res |= d return g_union, pos_res def add_save_warps(g_scenes: nx.MultiDiGraph, sw_duration: float = None) -> nx.MultiDiGraph: if not g_scenes: return nx.MultiDiGraph() g: nx.MultiDiGraph = g_scenes.copy() # TODO: Handle partial game graphs; add requirements (age) nodes = g.nodes(data=True) d = {EDGE_TYPE_LABEL: SAVEW_EDGE_LABEL} targets = {item for sublist in SW_SCENE_TO_TARGET_SCENES.values() for item in sublist} sw_scene_to_spawn = {s: n for n, data in nodes if ((s := data['scene']) in targets and data[NODE_TYPE_LABEL] == SPAWN_LABEL and data['idx'] == (0 if s != ADULT_OW_SW[0] else ADULT_OW_SW[1]))} for n, data in nodes: if (s := data['scene']) in SW_SCENE_TO_TARGET_SCENES: for target in SW_SCENE_TO_TARGET_SCENES[s]: if sw_duration: g.add_edge(n, sw_scene_to_spawn[target], **d, weight=sw_duration) else: g.add_edge(n, sw_scene_to_spawn[target], **d) return g def add_death_warps(g_scenes: nx.MultiDiGraph, dw_duration: float = None) -> nx.MultiDiGraph: if not g_scenes: return nx.MultiDiGraph() g: nx.MultiDiGraph = g_scenes.copy() # TODO: Add requirements, Handle Boss rooms better nodes = g.nodes(data=True) d = {EDGE_TYPE_LABEL: DEATHW_EDGE_LABEL} spawn_dict = collections.defaultdict(list) node_dict = collections.defaultdict(list) # Add nodes to spawn and node pools by scene, cutscene and setup for n, data in nodes: key = (data['scene'], data['is_cutscene'], data['setup']) node_dict[key].append(n) if data[NODE_TYPE_LABEL] == SPAWN_LABEL: spawn_dict[key].append(n) # Connect nodes with spawns of equally keyed pool for k, nodes in node_dict.items(): for node in nodes: for spawn in spawn_dict[k]: if dw_duration: g.add_edge(node, spawn, **d, weight=dw_duration) else: g.add_edge(node, spawn, **d) return g def add_song_warps(g_scenes: nx.MultiDiGraph, sw_duration: float = None) -> nx.MultiDiGraph: if not g_scenes: return nx.MultiDiGraph() g: nx.MultiDiGraph = g_scenes.copy() # TODO: Handle partial graphs; add requirements nodes = g.nodes(data=True) d = {EDGE_TYPE_LABEL: SONGW_EDGE_LABEL} for n, data in nodes: if data['scene'] not in NO_WARP_SONGS_SCENES: for dest in SONG_WARP_DESTINATION_LIST: if sw_duration is not None: g.add_edge(n, dest, **d, weight=sw_duration) else: g.add_edge(n, dest, **d) return g
#!/usr/bin/env python3 import argparse import os import sys import datetime import time import requests # Initialize some variables: start_date = datetime.datetime(1970, 1, 1).isoformat() def generate_auth_header(token: str): return {'Authorization': 'Bearer ' + token} # Necessary to list all announcements # Work through Canvas' pagination model if the relevant links exist def get_paginated_list(result: requests.models.Response, token: str) -> list: """ Easily handle pagination with Canvas API requests """ print('\tRetrieving all entries...') auth = generate_auth_header(token) items_list = result.json() while True: try: result.headers['Link'] # Handle pagination links pagination_links = result.headers['Link'].split(',') pagination_urls = {} for link in pagination_links: url, label = link.split(';') label = label.split('=')[-1].replace('"', '') url = url.replace('<', '').replace('>', '') pagination_urls.update({label: url}) # Now try to get the next page print('\tGetting next page...') result = requests.get(pagination_urls['next'], headers=auth) items_list.extend(result.json()) except KeyError: print('\tReached end of paginated list') break return items_list def mark_all_discussions_read(domain: str, token: str, course_id: int) -> None: auth = generate_auth_header(token) url = domain + '/api/v1/courses/' + str(course_id) + '/discussion_topics' discussions_response = requests.get(url, headers=auth, params={"per_page": 10000}) if discussions_response.status_code != 200: print(f"Cannot access course {course_id} -- are you authorized to view this course?") return discussions_list = get_paginated_list(discussions_response, token) for topic in discussions_list: try: topic_id = topic['id'] if topic['read_state'] == 'unread': requests.put(domain + '/api/v1/courses/' + str(course_id) + '/discussion_topics/' + str(topic_id) + '/read_all.json', headers={**auth, **{"Content-Length": "0"}}, params={"per_page": 10000}) time.sleep(1) except TypeError: print(f"Couldn't get info for topic {topic}. Skipping.") def mark_old_todos_complete(domain: str, token: str) -> None: print("Marking old TODOs...") auth = generate_auth_header(token) end_date = datetime.datetime.now(datetime.timezone.utc).isoformat() activities_response = requests.get(domain + '/api/v1/planner/items', headers=auth, params={'start_date': start_date, 'end_date': end_date, 'per_page': 10000}) activities = get_paginated_list(activities_response, token) for item in activities: if item['planner_override'] == None: print("\tMarking item: " + item['plannable']['title'] + " (" + item['plannable_date'][:10] + ")") requests.post(domain + '/api/v1/planner/overrides', headers=auth, params={'plannable_type': item['plannable_type'], 'plannable_id': item['plannable_id'], 'marked_complete': True}) time.sleep(1) elif item['planner_override']['marked_complete'] == False: print("\tMarking item: " + item['plannable']['title'] + " (" + item['plannable_date'][:10] + ")") requests.put(domain + '/api/v1/planner/overrides/' + str(item['planner_override']['id']), headers=auth, params={'marked_complete': 'true'}) time.sleep(1) print("\tDone.") def main() -> int: parser = argparse.ArgumentParser() parser.add_argument('-D', '--domain', required=True, help='Your institution\'s domain for Canvas (e.g. https://utah.instructure.com)') parser.add_argument('-T', '--token', required=True, help='Your Canvas LMS Token') parser.add_argument('-a', '--announcements', action='store_true', help='Mark old announcements as read') parser.add_argument('-d', '--discussions', action='store_true', help='Mark old discussions as read') parser.add_argument('-t', '--todos', action='store_true', help='Mark old TODOs as complete') parser.add_argument('-u', '--unread', action='store_true', help='Mark old activities as read') parser.add_argument('-A', '--all', action='store_true', help='Enable all options') args = parser.parse_args() token = args.token domain = args.domain if args.all or args.todos: mark_old_todos_complete(domain, token) if args.all or args.discussions or args.announcements: print("Retrieving course list...") auth = generate_auth_header(token) courses_response = requests.get(domain + '/api/v1/courses', headers=auth, params={"per_page": 10000}) if courses_response.status_code != 200: print("Unable to access courses. Verify both the domain and token are correct.") return 1 courses_list = get_paginated_list(courses_response, token) for course in courses_list: try: course_id = course['id'] except TypeError: print(f"Couldn't get info for course {course}. Skipping.") continue try: print(f"Marking discussions for course {course_id} ({course["name"]})") except KeyError: print(f"Marking discussions for course {course_id}") mark_all_discussions_read(domain, token, course_id) return 0 if __name__ == '__main__': sys.exit(main())
#!/usr/bin/env python3 import argparse import os import sys import datetime import time import requests # Initialize some variables: start_date = datetime.datetime(1970, 1, 1).isoformat() def generate_auth_header(token: str): return {'Authorization': 'Bearer ' + token} # Necessary to list all announcements # Work through Canvas' pagination model if the relevant links exist def get_paginated_list(result: requests.models.Response, token: str) -> list: """ Easily handle pagination with Canvas API requests """ print('\tRetrieving all entries...') auth = generate_auth_header(token) items_list = result.json() while True: try: result.headers['Link'] # Handle pagination links pagination_links = result.headers['Link'].split(',') pagination_urls = {} for link in pagination_links: url, label = link.split(';') label = label.split('=')[-1].replace('"', '') url = url.replace('<', '').replace('>', '') pagination_urls.update({label: url}) # Now try to get the next page print('\tGetting next page...') result = requests.get(pagination_urls['next'], headers=auth) items_list.extend(result.json()) except KeyError: print('\tReached end of paginated list') break return items_list def mark_all_discussions_read(domain: str, token: str, course_id: int) -> None: auth = generate_auth_header(token) url = domain + '/api/v1/courses/' + str(course_id) + '/discussion_topics' discussions_response = requests.get(url, headers=auth, params={"per_page": 10000}) if discussions_response.status_code != 200: print(f"Cannot access course {course_id} -- are you authorized to view this course?") return discussions_list = get_paginated_list(discussions_response, token) for topic in discussions_list: try: topic_id = topic['id'] if topic['read_state'] == 'unread': requests.put(domain + '/api/v1/courses/' + str(course_id) + '/discussion_topics/' + str(topic_id) + '/read_all.json', headers={**auth, **{"Content-Length": "0"}}, params={"per_page": 10000}) time.sleep(1) except TypeError: print(f"Couldn't get info for topic {topic}. Skipping.") def mark_old_todos_complete(domain: str, token: str) -> None: print("Marking old TODOs...") auth = generate_auth_header(token) end_date = datetime.datetime.now(datetime.timezone.utc).isoformat() activities_response = requests.get(domain + '/api/v1/planner/items', headers=auth, params={'start_date': start_date, 'end_date': end_date, 'per_page': 10000}) activities = get_paginated_list(activities_response, token) for item in activities: if item['planner_override'] == None: print("\tMarking item: " + item['plannable']['title'] + " (" + item['plannable_date'][:10] + ")") requests.post(domain + '/api/v1/planner/overrides', headers=auth, params={'plannable_type': item['plannable_type'], 'plannable_id': item['plannable_id'], 'marked_complete': True}) time.sleep(1) elif item['planner_override']['marked_complete'] == False: print("\tMarking item: " + item['plannable']['title'] + " (" + item['plannable_date'][:10] + ")") requests.put(domain + '/api/v1/planner/overrides/' + str(item['planner_override']['id']), headers=auth, params={'marked_complete': 'true'}) time.sleep(1) print("\tDone.") def main() -> int: parser = argparse.ArgumentParser() parser.add_argument('-D', '--domain', required=True, help='Your institution\'s domain for Canvas (e.g. https://utah.instructure.com)') parser.add_argument('-T', '--token', required=True, help='Your Canvas LMS Token') parser.add_argument('-a', '--announcements', action='store_true', help='Mark old announcements as read') parser.add_argument('-d', '--discussions', action='store_true', help='Mark old discussions as read') parser.add_argument('-t', '--todos', action='store_true', help='Mark old TODOs as complete') parser.add_argument('-u', '--unread', action='store_true', help='Mark old activities as read') parser.add_argument('-A', '--all', action='store_true', help='Enable all options') args = parser.parse_args() token = args.token domain = args.domain if args.all or args.todos: mark_old_todos_complete(domain, token) if args.all or args.discussions or args.announcements: print("Retrieving course list...") auth = generate_auth_header(token) courses_response = requests.get(domain + '/api/v1/courses', headers=auth, params={"per_page": 10000}) if courses_response.status_code != 200: print("Unable to access courses. Verify both the domain and token are correct.") return 1 courses_list = get_paginated_list(courses_response, token) for course in courses_list: try: course_id = course['id'] except TypeError: print(f"Couldn't get info for course {course}. Skipping.") continue try: print(f"Marking discussions for course {course_id} ({course['name']})") except KeyError: print(f"Marking discussions for course {course_id}") mark_all_discussions_read(domain, token, course_id) return 0 if __name__ == '__main__': sys.exit(main())
#!/usr/bin/env python3 # # Copyright 2021 Graviti. Licensed under MIT License. # """The segment of remote dataset on TensorBay.""" import os import time from copy import deepcopy from itertools import zip_longest from typing import TYPE_CHECKING, Any, Dict, Generator, Iterable, Optional, Tuple, Union import filetype from requests_toolbelt import MultipartEncoder from ulid import ULID, from_timestamp from tensorbay.client.lazy import LazyPage, PagingList from tensorbay.client.status import Status from tensorbay.dataset import AuthData, Data, Frame, RemoteData from tensorbay.dataset.data import DataBase from tensorbay.exception import FrameError, InvalidParamsError, ResourceNotExistError, ResponseError from tensorbay.label import Label from tensorbay.sensor.sensor import Sensor, Sensors from tensorbay.utility import URL, FileMixin, chunked, config, locked if TYPE_CHECKING: from tensorbay.client.dataset import DatasetClient, FusionDatasetClient _STRATEGIES = {"abort", "override", "skip"} _MASK_KEYS = ("semantic_mask", "instance_mask", "panoptic_mask") class SegmentClientBase: """This class defines the basic concept of :class:`SegmentClient`. A :class:`SegmentClientBase` contains the information needed for determining a unique segment in a dataset on TensorBay. Arguments: name: Segment name. dataset_client: The dataset client. Attributes: name: Segment name. status: The status of the dataset client. """ _EXPIRED_IN_SECOND = 240 def __init__( self, name: str, dataset_client: "Union[DatasetClient, FusionDatasetClient]" ) -> None: self._name = name self._dataset_id = dataset_client.dataset_id self._dataset_client = dataset_client self._status = dataset_client.status self._client = dataset_client._client self._permission: Dict[str, Any] = {"expireAt": 0} if dataset_client.cache_enabled: self._cache_path: str = os.path.join( dataset_client._cache_path, dataset_client.status.commit_id, # type: ignore[arg-type] name, ) else: self._cache_path = "" def _get_url(self, remote_path: str) -> str: """Get URL of a specific remote path. Arguments: remote_path: The remote path of the file. Returns: The URL of the remote file. """ params: Dict[str, Any] = { "segmentName": self._name, "remotePath": remote_path, } params.update(self._status.get_status_info()) if config.is_internal: params["isInternal"] = True response = self._client.open_api_do("GET", "data/urls", self._dataset_id, params=params) return response.json()["urls"][0]["url"] # type: ignore[no-any-return] def _list_urls(self, offset: int = 0, limit: int = 128) -> Dict[str, Any]: params: Dict[str, Any] = { "segmentName": self._name, "offset": offset, "limit": limit, } params.update(self._status.get_status_info()) if config.is_internal: params["isInternal"] = True response = self._client.open_api_do("GET", "data/urls", self._dataset_id, params=params) return response.json() # type: ignore[no-any-return] def _get_data_details(self, remote_path: str) -> Dict[str, Any]: params: Dict[str, Any] = { "segmentName": self._name, "remotePath": remote_path, } params.update(self._status.get_status_info()) if config.is_internal: params["isInternal"] = True response = self._client.open_api_do("GET", "data/details", self._dataset_id, params=params) try: data_details = response.json()["dataDetails"][0] except IndexError as error: raise ResourceNotExistError(resource="data", identification=remote_path) from error return data_details # type: ignore[no-any-return] def _list_data_details(self, offset: int = 0, limit: int = 128) -> Dict[str, Any]: params: Dict[str, Any] = { "segmentName": self._name, "offset": offset, "limit": limit, } params.update(self._status.get_status_info()) if config.is_internal: params["isInternal"] = True response = self._client.open_api_do("GET", "data/details", self._dataset_id, params=params) return response.json() # type: ignore[no-any-return] def _get_mask_url(self, mask_type: str, remote_path: str) -> str: params: Dict[str, Any] = { "segmentName": self._name, "maskType": mask_type, "remotePath": remote_path, } params.update(self._status.get_status_info()) if config.is_internal: params["isInternal"] = True response = self._client.open_api_do("GET", "masks/urls", self._dataset_id, params=params) try: mask_url = response.json()["urls"][0]["url"] except IndexError as error: raise ResourceNotExistError( resource="{mask_type} of data", identification=remote_path ) from error return mask_url # type: ignore[no-any-return] def _list_mask_urls(self, mask_type: str, offset: int = 0, limit: int = 128) -> Dict[str, Any]: params: Dict[str, Any] = { "segmentName": self._name, "maskType": mask_type, "offset": offset, "limit": limit, } params.update(self._status.get_status_info()) if config.is_internal: params["isInternal"] = True response = self._client.open_api_do("GET", "masks/urls", self._dataset_id, params=params) return response.json() # type: ignore[no-any-return] def _list_labels(self, offset: int = 0, limit: int = 128) -> Dict[str, Any]: params: Dict[str, Any] = { "segmentName": self._name, "offset": offset, "limit": limit, } params.update(self._status.get_status_info()) response = self._client.open_api_do("GET", "labels", self._dataset_id, params=params) return response.json() # type: ignore[no-any-return] @locked def _request_upload_permission(self) -> None: params: Dict[str, Any] = {"expired": self._EXPIRED_IN_SECOND, "segmentName": self._name} params.update(self._status.get_status_info()) if config.is_internal: params["isInternal"] = True self._permission = self._client.open_api_do( "GET", "policies", self._dataset_id, params=params ).json() del self._permission["result"]["multipleUploadLimit"] def _get_upload_permission(self) -> Dict[str, Any]: if int(time.time()) >= self._permission["expireAt"]: self._request_upload_permission() return deepcopy(self._permission) def _upload_file(self, data: FileMixin) -> None: """Upload the file in the data to the draft. Arguments: data: The data instance needs to be uploaded. """ permission = self._get_upload_permission() post_data = permission["result"] local_path = data.path checksum = data.get_checksum() post_data["key"] = permission["extra"]["objectPrefix"] + checksum host = permission["extra"]["host"] backend_type = permission["extra"]["backendType"] if backend_type == "azure": url = ( f'{permission['extra']['host']}{permission['extra']['objectPrefix']}' f'{checksum}?{permission['result']['token']}' ) self._put_binary_file_to_azure(url, local_path, post_data) elif backend_type == "fps": self._post_multipart_formdata( host, local_path, post_data, checksum, ) else: self._post_multipart_formdata( host, local_path, post_data, ) def _upload_mask_files(self, label: Label) -> None: for key in _MASK_KEYS: mask = getattr(label, key, None) if mask: self._upload_file(mask) def _post_multipart_formdata( self, url: str, local_path: str, data: Dict[str, Any], filename: str = "", ) -> None: with open(local_path, "rb") as fp: file_type = filetype.guess_mime(local_path) if "x-amz-date" in data: data["Content-Type"] = file_type try: data["file"] = (filename, fp, file_type) self._post_formdata(url, data) except ResponseError as error: if b"MalformedPOSTRequest" in error.response.content: data["file"] = ("workaroundForMalformedPostRequest", fp, file_type) self._post_formdata(url, data) else: raise def _post_formdata(self, url: str, data: Dict[str, Any]) -> None: multipart = MultipartEncoder(data) self._client.do( "POST", url, data=multipart, headers={"Content-Type": multipart.content_type}, ) def _put_binary_file_to_azure( self, url: str, local_path: str, data: Dict[str, Any], ) -> None: with open(local_path, "rb") as fp: file_type = filetype.guess_mime(local_path) request_headers = { "x-ms-blob-content-type": file_type, "x-ms-blob-type": data["x-ms-blob-type"], } self._client.do("PUT", url, data=fp, headers=request_headers) def _synchronize_import_info(self, callback_bodies: Tuple[Dict[str, Any], ...]) -> None: put_data: Dict[str, Any] = { "segmentName": self.name, "objects": callback_bodies, "deleteSource": False, } put_data.update(self._status.get_status_info()) self._client.open_api_do("PUT", "multi/cloud-callback", self._dataset_id, json=put_data) def _synchronize_upload_info( self, callback_bodies: Tuple[Dict[str, Any], ...], ) -> None: put_data: Dict[str, Any] = { "segmentName": self.name, "objects": callback_bodies, } put_data.update(self._status.get_status_info()) self._client.open_api_do("PUT", "multi/callback", self._dataset_id, json=put_data) def _upload_label(self, data: Union[AuthData, Data]) -> None: label = data.label.dumps() if not label: return post_data: Dict[str, Any] = { "segmentName": self.name, "remotePath": data.target_remote_path, "label": label, } post_data.update(self._status.get_status_info()) self._client.open_api_do("PUT", "labels", self._dataset_id, json=post_data) def _upload_multi_label(self, data: Iterable[DataBase._Type]) -> None: post_data: Dict[str, Any] = {"segmentName": self.name} objects = [] for single_data in data: label = single_data.label.dumps() if not label: continue remote_path = ( single_data.path if isinstance(single_data, RemoteData) else single_data.target_remote_path ) objects.append({"remotePath": remote_path, "label": label}) post_data["objects"] = objects post_data.update(self._status.get_status_info()) self._client.open_api_do("PUT", "multi/data/labels", self._dataset_id, json=post_data) def upload_label(self, data: Union[DataBase._Type, Iterable[DataBase._Type]]) -> None: """Upload label with Data object to the draft. Arguments: data: The data object which represents the local file to upload. """ self._status.check_authority_for_draft() if not isinstance(data, Iterable): data = [data] for chunked_data in chunked(data, 128): for single_data in chunked_data: self._upload_mask_files(single_data.label) self._upload_multi_label(chunked_data) @property def name(self) -> str: """Return the segment name. Returns: The segment name. """ return self._name @property def status(self) -> Status: """Return the status of the dataset client. Returns: The status of the dataset client. """ return self._status class SegmentClient(SegmentClientBase): """This class defines :class:`SegmentClient`. :class:`SegmentClient` inherits from SegmentClientBase and provides methods within a segment scope, such as `upload_label()`, `upload_data()`, `list_data()` and so on. In contrast to FusionSegmentClient, :class:`SegmentClient` has only one sensor. """ _dataset_client: "DatasetClient" def __init__(self, name: str, data_client: "DatasetClient") -> None: super().__init__(name, data_client) def _generate_data_paths(self, offset: int = 0, limit: int = 128) -> Generator[str, None, int]: params: Dict[str, Any] = { "segmentName": self._name, "offset": offset, "limit": limit, } params.update(self._status.get_status_info()) response = self._client.open_api_do("GET", "data", self._dataset_id, params=params).json() for item in response["data"]: yield item["remotePath"] return response["totalCount"] # type: ignore[no-any-return] def _generate_data(self, offset: int = 0, limit: int = 128) -> Generator[RemoteData, None, int]: response = self._list_data_details(offset, limit) urls = LazyPage.from_items( offset, limit, self._generate_urls, (item["url"] for item in response["dataDetails"]), ) mask_urls = {} for key in _MASK_KEYS: mask_urls[key] = LazyPage.from_items( offset, limit, lambda offset, limit, k=key.upper(): ( # type: ignore[misc] self._generate_mask_urls(k, offset, limit) ), (item["label"].get(key.upper(), {}).get("url") for item in response["dataDetails"]), ) for i, item in enumerate(response["dataDetails"]): data = RemoteData.from_response_body( item, url=URL.from_getter(urls.items[i].get, urls.pull), cache_path=self._cache_path, ) label = data.label for key in _MASK_KEYS: mask = getattr(label, key, None) if mask: mask.url = URL.from_getter(mask_urls[key].items[i].get, mask_urls[key].pull) mask.cache_path = os.path.join(self._cache_path, key, mask.path) yield data return response["totalCount"] # type: ignore[no-any-return] def _generate_urls(self, offset: int = 0, limit: int = 128) -> Generator[str, None, int]: response = self._list_urls(offset, limit) for item in response["urls"]: yield item["url"] return response["totalCount"] # type: ignore[no-any-return] def _generate_mask_urls( self, mask_type: str, offset: int = 0, limit: int = 128 ) -> Generator[Optional[str], None, int]: response = self._list_mask_urls(mask_type, offset, limit) for item in response["urls"]: yield item["url"] if item else None return response["totalCount"] # type: ignore[no-any-return] def _upload_or_import_data(self, data: Union[Data, AuthData]) -> Optional[Dict[str, Any]]: if isinstance(data, Data): self._upload_file(data) self._upload_mask_files(data.label) return data.get_callback_body() self._synchronize_import_info((data.get_callback_body(),)) return None def upload_file(self, local_path: str, target_remote_path: str = "") -> None: """Upload data with local path to the draft. Arguments: local_path: The local path of the data to upload. target_remote_path: The path to save the data in segment client. """ self._status.check_authority_for_draft() data = Data(local_path, target_remote_path=target_remote_path) self._upload_file(data) self._synchronize_upload_info((data.get_callback_body(),)) def upload_data(self, data: Data) -> None: """Upload Data object to the draft. Arguments: data: The :class:`~tensorbay.dataset.data.Data`. """ self._status.check_authority_for_draft() self._upload_file(data) self._upload_mask_files(data.label) self._synchronize_upload_info((data.get_callback_body(),)) def import_auth_data(self, data: AuthData) -> None: """Import AuthData object to the draft. Arguments: data: The :class:`~tensorbay.dataset.data.Data`. """ self._status.check_authority_for_draft() self._synchronize_import_info((data.get_callback_body(),)) def copy_data( self, source_remote_paths: Union[str, Iterable[str]], target_remote_paths: Union[None, str, Iterable[str]] = None, *, source_client: Optional["SegmentClient"] = None, strategy: str = "abort", ) -> None: """Copy data to this segment. Arguments: source_remote_paths: The source remote paths of the copied data. target_remote_paths: The target remote paths of the copied data. This argument is used to specify new remote paths of the copied data. If None, the remote path of the copied data will not be changed after copy. source_client: The source segment client of the copied data. This argument is used to specifies where the copied data comes from when the copied data is from another commit, draft, segment or even another dataset. If None, the copied data comes from this segment. strategy: The strategy of handling the name conflict. There are three options: 1. "abort": stop copying and raise exception; 2. "override": the source data will override the origin data; 3. "skip": keep the origin data. Raises: InvalidParamsError: When strategy is invalid. ValueError: When the type of target_remote_paths is not equal with source_remote_paths. """ self._status.check_authority_for_draft() if strategy not in _STRATEGIES: raise InvalidParamsError(param_name="strategy", param_value=strategy) if not target_remote_paths: all_target_remote_paths = [] all_source_remote_paths = ( [source_remote_paths] if isinstance(source_remote_paths, str) else list(source_remote_paths) ) elif isinstance(source_remote_paths, str) and isinstance(target_remote_paths, str): all_target_remote_paths = [target_remote_paths] all_source_remote_paths = [source_remote_paths] elif not isinstance(source_remote_paths, str) and not isinstance(target_remote_paths, str): all_target_remote_paths = list(target_remote_paths) all_source_remote_paths = list(source_remote_paths) if len(all_target_remote_paths) != len(all_source_remote_paths): raise ValueError( "To copy the data, the length of target_remote_paths " "must be equal with source_remote_paths" ) else: raise ValueError( "To copy the data, the type of target_remote_paths " "must be equal with source_remote_paths" ) source = {} if source_client: source["segmentName"] = source_client.name source["id"] = source_client._dataset_id # pylint: disable=protected-access source.update(source_client.status.get_status_info()) else: source["segmentName"] = self.name post_data: Dict[str, Any] = { "strategy": strategy, "source": source, "segmentName": self.name, } post_data.update(self._status.get_status_info()) for targets, sources in zip_longest( chunked(all_target_remote_paths, 128), chunked(all_source_remote_paths, 128) ): if targets: post_data["remotePaths"] = targets post_data["source"]["remotePaths"] = sources self._client.open_api_do("POST", "data?multipleCopy", self._dataset_id, json=post_data) def move_data( self, source_remote_paths: Union[str, Iterable[str]], target_remote_paths: Union[None, str, Iterable[str]] = None, *, source_client: Optional["SegmentClient"] = None, strategy: str = "abort", ) -> None: """Move data to this segment, also used to rename data. Arguments: source_remote_paths: The source remote paths of the moved data. target_remote_paths: The target remote paths of the moved data. This argument is used to specify new remote paths of the moved data. If None, the remote path of the moved data will not be changed after copy. source_client: The source segment client of the moved data. This argument is used to specifies where the moved data comes from when the moved data is from another segment. If None, the moved data comes from this segment. strategy: The strategy of handling the name conflict. There are three options: 1. "abort": stop copying and raise exception; 2. "override": the source data will override the origin data; 3. "skip": keep the origin data. Raises: InvalidParamsError: When strategy is invalid. ValueError: When the type or the length of target_remote_paths is not equal with source_remote_paths. Or when the dataset_id and drafter_number of source_client is not equal with the current segment client. """ self._status.check_authority_for_draft() if strategy not in _STRATEGIES: raise InvalidParamsError(param_name="strategy", param_value=strategy) if not target_remote_paths: all_target_remote_paths = [] all_source_remote_paths = ( [source_remote_paths] if isinstance(source_remote_paths, str) else list(source_remote_paths) ) elif isinstance(source_remote_paths, str) and isinstance(target_remote_paths, str): all_target_remote_paths = [target_remote_paths] all_source_remote_paths = [source_remote_paths] elif not isinstance(source_remote_paths, str) and not isinstance(target_remote_paths, str): all_target_remote_paths = list(target_remote_paths) all_source_remote_paths = list(source_remote_paths) if len(all_target_remote_paths) != len(all_source_remote_paths): raise ValueError( "To move the data, the length of target_remote_paths " "must be equal with source_remote_paths" ) else: raise ValueError( "To move the data, the type of target_remote_paths " "must be equal with source_remote_paths" ) source = {} if source_client: if ( source_client.status.draft_number == self.status.draft_number and source_client._dataset_id # pylint: disable=protected-access == self._dataset_id ): source["segmentName"] = source_client.name else: raise ValueError( "To move the data, the dataset_id and drafter_number of source_client " "must be equal with the current segment client" ) else: source["segmentName"] = self.name post_data: Dict[str, Any] = { "strategy": strategy, "source": source, "segmentName": self.name, } post_data.update(self._status.get_status_info()) for targets, sources in zip_longest( chunked(all_target_remote_paths, 128), chunked(all_source_remote_paths, 128) ): if targets: post_data["remotePaths"] = targets post_data["source"]["remotePaths"] = sources self._client.open_api_do("POST", "data?multipleMove", self._dataset_id, json=post_data) def list_data_paths(self) -> PagingList[str]: """List required data path in a segment in a certain commit. Returns: The PagingList of data paths. """ return PagingList(self._generate_data_paths, 128) def get_data(self, remote_path: str) -> RemoteData: """Get required Data object from a dataset segment. Arguments: remote_path: The remote paths of the required data. Returns: :class:`~tensorbay.dataset.data.RemoteData`. Raises: ResourceNotExistError: When the required data does not exist. """ if not remote_path: raise ResourceNotExistError(resource="data", identification=remote_path) data_details = self._get_data_details(remote_path) data = RemoteData.from_response_body( data_details, url=URL(data_details["url"], lambda: self._get_url(remote_path)), cache_path=self._cache_path, ) label = data.label for key in _MASK_KEYS: mask = getattr(label, key, None) if mask: mask.url = URL( data_details["label"][key.upper()]["url"], lambda k=key.upper(), r=remote_path: ( # type: ignore[misc, arg-type] self._get_mask_url(k, r) ), ) mask.cache_path = os.path.join(self._cache_path, key, mask.path) return data def list_data(self) -> PagingList[RemoteData]: """List required Data object in a dataset segment. Returns: The PagingList of :class:`~tensorbay.dataset.data.RemoteData`. """ return PagingList(self._generate_data, 128) def delete_data(self, remote_path: str) -> None: """Delete data of a segment in a certain commit with the given remote paths. Arguments: remote_path: The remote path of data in a segment. """ self._status.check_authority_for_draft() delete_data: Dict[str, Any] = { "segmentName": self.name, "remotePath": remote_path, } delete_data.update(self._status.get_status_info()) self._client.open_api_do("DELETE", "data", self._dataset_id, json=delete_data) def list_urls(self) -> PagingList[str]: """List the data urls in this segment. Returns: The PagingList of urls. """ return PagingList(self._generate_urls, 128) def list_mask_urls(self, mask_type: str) -> PagingList[Optional[str]]: """List the mask urls in this segment. Arguments: mask_type: The required mask type, the supported types are ``SEMANTIC_MASK``, ``INSTANCE_MASK`` and ``PANOPTIC_MASK`` Returns: The PagingList of mask urls. """ return PagingList( lambda offset, limit: self._generate_mask_urls(mask_type, offset, limit), 128 ) class FusionSegmentClient(SegmentClientBase): """This class defines :class:`FusionSegmentClient`. :class:`FusionSegmentClient` inherits from :class:`SegmentClientBase` and provides methods within a fusion segment scope, such as :meth:`FusionSegmentClient.upload_sensor`, :meth:`FusionSegmentClient.upload_frame` and :meth:`FusionSegmentClient.list_frames`. In contrast to :class:`SegmentClient`, :class:`FusionSegmentClient` has multiple sensors. """ _dataset_client: "FusionDatasetClient" def __init__(self, name: str, data_client: "FusionDatasetClient") -> None: super().__init__(name, data_client) def _generate_frames(self, offset: int = 0, limit: int = 128) -> Generator[Frame, None, int]: response = self._list_data_details(offset, limit) url_page = LazyPage.from_items( offset, limit, self._generate_urls, ( {frame["sensorName"]: frame["url"] for frame in item["frame"]} for item in response["dataDetails"] ), ) for index, item in enumerate(response["dataDetails"]): yield Frame.from_response_body(item, index, url_page, cache_path=self._cache_path) return response["totalCount"] # type: ignore[no-any-return] def _generate_urls( self, offset: int = 0, limit: int = 128 ) -> Generator[Dict[str, str], None, int]: response = self._list_urls(offset, limit) for frame in response["urls"]: yield {item["sensorName"]: item["url"] for item in frame["urls"]} return response["totalCount"] # type: ignore[no-any-return] def _upload_or_import_data( self, data: Union[Data, AuthData], sensor_name: str, frame_id: str, ) -> Optional[Dict[str, Any]]: callback_body = data.get_callback_body() callback_body["frameId"] = frame_id callback_body["sensorName"] = sensor_name if isinstance(data, Data): self._upload_file(data) self._upload_mask_files(data.label) return callback_body self._synchronize_import_info((callback_body,)) return None def get_sensors(self) -> Sensors: """Return the sensors in a fusion segment client. Returns: The :class:`sensors<~tensorbay.sensor.sensor.Sensors>` in the fusion segment client. """ params: Dict[str, Any] = {"segmentName": self._name} params.update(self._status.get_status_info()) response = self._client.open_api_do( "GET", "sensors", self._dataset_id, params=params ).json() return Sensors.loads(response["sensors"]) def upload_sensor(self, sensor: Sensor) -> None: """Upload sensor to the draft. Arguments: sensor: The sensor to upload. """ self._status.check_authority_for_draft() post_data = sensor.dumps() post_data.update(self._status.get_status_info()) post_data["segmentName"] = self._name self._client.open_api_do("POST", "sensors", self._dataset_id, json=post_data) def delete_sensor(self, sensor_name: str) -> None: """Delete a TensorBay sensor of the draft with the given sensor name. Arguments: sensor_name: The TensorBay sensor to delete. """ self._status.check_authority_for_draft() delete_data: Dict[str, Any] = {"segmentName": self._name, "sensorName": sensor_name} delete_data.update(self._status.get_status_info()) self._client.open_api_do("DELETE", "sensors", self._dataset_id, json=delete_data) def upload_frame(self, frame: Frame, timestamp: Optional[float] = None) -> None: """Upload frame to the draft. Arguments: frame: The :class:`~tensorbay.dataset.frame.Frame` to upload. timestamp: The mark to sort frames, supporting timestamp and float. Raises: FrameError: When lacking frame id or frame id conflicts. """ self._status.check_authority_for_draft() if timestamp is None: try: frame_id = frame.frame_id except AttributeError as error: raise FrameError( "Lack frame id, please add frame id in frame or " "give timestamp to the function!" ) from error elif not hasattr(frame, "frame_id"): frame_id = from_timestamp(timestamp) else: raise FrameError("Frame id conflicts, please do not give timestamp to the function!.") callback_bodies = [] for sensor_name, data in frame.items(): try: callback_body = data.get_callback_body() # type:ignore[union-attr] except AttributeError: continue callback_body["frameId"] = frame_id.str callback_body["sensorName"] = sensor_name if isinstance(data, Data): self._upload_file(data) self._upload_mask_files(data.label) callback_bodies.append(callback_body) elif isinstance(data, AuthData): self._synchronize_import_info((callback_body,)) for chunked_callback_bodies in chunked(callback_bodies, 50): self._synchronize_upload_info(chunked_callback_bodies) def list_frames(self) -> PagingList[Frame]: """List required frames in the segment in a certain commit. Returns: The PagingList of :class:`~tensorbay.dataset.frame.Frame`. """ return PagingList(self._generate_frames, 128) def delete_frame(self, frame_id: Union[str, ULID]) -> None: """Delete a frame of a segment in a certain commit with the given frame id. Arguments: frame_id: The id of a frame in a segment. """ self._status.check_authority_for_draft() delete_data: Dict[str, Any] = { "segmentName": self.name, "frameId": str(frame_id), } delete_data.update(self._status.get_status_info()) self._client.open_api_do("DELETE", "frames", self._dataset_id, json=delete_data) def list_urls(self) -> PagingList[Dict[str, str]]: """List the data urls in this segment. Returns: The PagingList of url dict, which key is the sensor name, value is the url. """ urls = PagingList(self._generate_urls, 128) urls._repr_maxlevel = 2 # pylint: disable=protected-access return urls
#!/usr/bin/env python3 # # Copyright 2021 Graviti. Licensed under MIT License. # """The segment of remote dataset on TensorBay.""" import os import time from copy import deepcopy from itertools import zip_longest from typing import TYPE_CHECKING, Any, Dict, Generator, Iterable, Optional, Tuple, Union import filetype from requests_toolbelt import MultipartEncoder from ulid import ULID, from_timestamp from tensorbay.client.lazy import LazyPage, PagingList from tensorbay.client.status import Status from tensorbay.dataset import AuthData, Data, Frame, RemoteData from tensorbay.dataset.data import DataBase from tensorbay.exception import FrameError, InvalidParamsError, ResourceNotExistError, ResponseError from tensorbay.label import Label from tensorbay.sensor.sensor import Sensor, Sensors from tensorbay.utility import URL, FileMixin, chunked, config, locked if TYPE_CHECKING: from tensorbay.client.dataset import DatasetClient, FusionDatasetClient _STRATEGIES = {"abort", "override", "skip"} _MASK_KEYS = ("semantic_mask", "instance_mask", "panoptic_mask") class SegmentClientBase: """This class defines the basic concept of :class:`SegmentClient`. A :class:`SegmentClientBase` contains the information needed for determining a unique segment in a dataset on TensorBay. Arguments: name: Segment name. dataset_client: The dataset client. Attributes: name: Segment name. status: The status of the dataset client. """ _EXPIRED_IN_SECOND = 240 def __init__( self, name: str, dataset_client: "Union[DatasetClient, FusionDatasetClient]" ) -> None: self._name = name self._dataset_id = dataset_client.dataset_id self._dataset_client = dataset_client self._status = dataset_client.status self._client = dataset_client._client self._permission: Dict[str, Any] = {"expireAt": 0} if dataset_client.cache_enabled: self._cache_path: str = os.path.join( dataset_client._cache_path, dataset_client.status.commit_id, # type: ignore[arg-type] name, ) else: self._cache_path = "" def _get_url(self, remote_path: str) -> str: """Get URL of a specific remote path. Arguments: remote_path: The remote path of the file. Returns: The URL of the remote file. """ params: Dict[str, Any] = { "segmentName": self._name, "remotePath": remote_path, } params.update(self._status.get_status_info()) if config.is_internal: params["isInternal"] = True response = self._client.open_api_do("GET", "data/urls", self._dataset_id, params=params) return response.json()["urls"][0]["url"] # type: ignore[no-any-return] def _list_urls(self, offset: int = 0, limit: int = 128) -> Dict[str, Any]: params: Dict[str, Any] = { "segmentName": self._name, "offset": offset, "limit": limit, } params.update(self._status.get_status_info()) if config.is_internal: params["isInternal"] = True response = self._client.open_api_do("GET", "data/urls", self._dataset_id, params=params) return response.json() # type: ignore[no-any-return] def _get_data_details(self, remote_path: str) -> Dict[str, Any]: params: Dict[str, Any] = { "segmentName": self._name, "remotePath": remote_path, } params.update(self._status.get_status_info()) if config.is_internal: params["isInternal"] = True response = self._client.open_api_do("GET", "data/details", self._dataset_id, params=params) try: data_details = response.json()["dataDetails"][0] except IndexError as error: raise ResourceNotExistError(resource="data", identification=remote_path) from error return data_details # type: ignore[no-any-return] def _list_data_details(self, offset: int = 0, limit: int = 128) -> Dict[str, Any]: params: Dict[str, Any] = { "segmentName": self._name, "offset": offset, "limit": limit, } params.update(self._status.get_status_info()) if config.is_internal: params["isInternal"] = True response = self._client.open_api_do("GET", "data/details", self._dataset_id, params=params) return response.json() # type: ignore[no-any-return] def _get_mask_url(self, mask_type: str, remote_path: str) -> str: params: Dict[str, Any] = { "segmentName": self._name, "maskType": mask_type, "remotePath": remote_path, } params.update(self._status.get_status_info()) if config.is_internal: params["isInternal"] = True response = self._client.open_api_do("GET", "masks/urls", self._dataset_id, params=params) try: mask_url = response.json()["urls"][0]["url"] except IndexError as error: raise ResourceNotExistError( resource="{mask_type} of data", identification=remote_path ) from error return mask_url # type: ignore[no-any-return] def _list_mask_urls(self, mask_type: str, offset: int = 0, limit: int = 128) -> Dict[str, Any]: params: Dict[str, Any] = { "segmentName": self._name, "maskType": mask_type, "offset": offset, "limit": limit, } params.update(self._status.get_status_info()) if config.is_internal: params["isInternal"] = True response = self._client.open_api_do("GET", "masks/urls", self._dataset_id, params=params) return response.json() # type: ignore[no-any-return] def _list_labels(self, offset: int = 0, limit: int = 128) -> Dict[str, Any]: params: Dict[str, Any] = { "segmentName": self._name, "offset": offset, "limit": limit, } params.update(self._status.get_status_info()) response = self._client.open_api_do("GET", "labels", self._dataset_id, params=params) return response.json() # type: ignore[no-any-return] @locked def _request_upload_permission(self) -> None: params: Dict[str, Any] = {"expired": self._EXPIRED_IN_SECOND, "segmentName": self._name} params.update(self._status.get_status_info()) if config.is_internal: params["isInternal"] = True self._permission = self._client.open_api_do( "GET", "policies", self._dataset_id, params=params ).json() del self._permission["result"]["multipleUploadLimit"] def _get_upload_permission(self) -> Dict[str, Any]: if int(time.time()) >= self._permission["expireAt"]: self._request_upload_permission() return deepcopy(self._permission) def _upload_file(self, data: FileMixin) -> None: """Upload the file in the data to the draft. Arguments: data: The data instance needs to be uploaded. """ permission = self._get_upload_permission() post_data = permission["result"] local_path = data.path checksum = data.get_checksum() post_data["key"] = permission["extra"]["objectPrefix"] + checksum host = permission["extra"]["host"] backend_type = permission["extra"]["backendType"] if backend_type == "azure": url = ( f'{permission["extra"]["host"]}{permission["extra"]["objectPrefix"]}' f'{checksum}?{permission["result"]["token"]}' ) self._put_binary_file_to_azure(url, local_path, post_data) elif backend_type == "fps": self._post_multipart_formdata( host, local_path, post_data, checksum, ) else: self._post_multipart_formdata( host, local_path, post_data, ) def _upload_mask_files(self, label: Label) -> None: for key in _MASK_KEYS: mask = getattr(label, key, None) if mask: self._upload_file(mask) def _post_multipart_formdata( self, url: str, local_path: str, data: Dict[str, Any], filename: str = "", ) -> None: with open(local_path, "rb") as fp: file_type = filetype.guess_mime(local_path) if "x-amz-date" in data: data["Content-Type"] = file_type try: data["file"] = (filename, fp, file_type) self._post_formdata(url, data) except ResponseError as error: if b"MalformedPOSTRequest" in error.response.content: data["file"] = ("workaroundForMalformedPostRequest", fp, file_type) self._post_formdata(url, data) else: raise def _post_formdata(self, url: str, data: Dict[str, Any]) -> None: multipart = MultipartEncoder(data) self._client.do( "POST", url, data=multipart, headers={"Content-Type": multipart.content_type}, ) def _put_binary_file_to_azure( self, url: str, local_path: str, data: Dict[str, Any], ) -> None: with open(local_path, "rb") as fp: file_type = filetype.guess_mime(local_path) request_headers = { "x-ms-blob-content-type": file_type, "x-ms-blob-type": data["x-ms-blob-type"], } self._client.do("PUT", url, data=fp, headers=request_headers) def _synchronize_import_info(self, callback_bodies: Tuple[Dict[str, Any], ...]) -> None: put_data: Dict[str, Any] = { "segmentName": self.name, "objects": callback_bodies, "deleteSource": False, } put_data.update(self._status.get_status_info()) self._client.open_api_do("PUT", "multi/cloud-callback", self._dataset_id, json=put_data) def _synchronize_upload_info( self, callback_bodies: Tuple[Dict[str, Any], ...], ) -> None: put_data: Dict[str, Any] = { "segmentName": self.name, "objects": callback_bodies, } put_data.update(self._status.get_status_info()) self._client.open_api_do("PUT", "multi/callback", self._dataset_id, json=put_data) def _upload_label(self, data: Union[AuthData, Data]) -> None: label = data.label.dumps() if not label: return post_data: Dict[str, Any] = { "segmentName": self.name, "remotePath": data.target_remote_path, "label": label, } post_data.update(self._status.get_status_info()) self._client.open_api_do("PUT", "labels", self._dataset_id, json=post_data) def _upload_multi_label(self, data: Iterable[DataBase._Type]) -> None: post_data: Dict[str, Any] = {"segmentName": self.name} objects = [] for single_data in data: label = single_data.label.dumps() if not label: continue remote_path = ( single_data.path if isinstance(single_data, RemoteData) else single_data.target_remote_path ) objects.append({"remotePath": remote_path, "label": label}) post_data["objects"] = objects post_data.update(self._status.get_status_info()) self._client.open_api_do("PUT", "multi/data/labels", self._dataset_id, json=post_data) def upload_label(self, data: Union[DataBase._Type, Iterable[DataBase._Type]]) -> None: """Upload label with Data object to the draft. Arguments: data: The data object which represents the local file to upload. """ self._status.check_authority_for_draft() if not isinstance(data, Iterable): data = [data] for chunked_data in chunked(data, 128): for single_data in chunked_data: self._upload_mask_files(single_data.label) self._upload_multi_label(chunked_data) @property def name(self) -> str: """Return the segment name. Returns: The segment name. """ return self._name @property def status(self) -> Status: """Return the status of the dataset client. Returns: The status of the dataset client. """ return self._status class SegmentClient(SegmentClientBase): """This class defines :class:`SegmentClient`. :class:`SegmentClient` inherits from SegmentClientBase and provides methods within a segment scope, such as `upload_label()`, `upload_data()`, `list_data()` and so on. In contrast to FusionSegmentClient, :class:`SegmentClient` has only one sensor. """ _dataset_client: "DatasetClient" def __init__(self, name: str, data_client: "DatasetClient") -> None: super().__init__(name, data_client) def _generate_data_paths(self, offset: int = 0, limit: int = 128) -> Generator[str, None, int]: params: Dict[str, Any] = { "segmentName": self._name, "offset": offset, "limit": limit, } params.update(self._status.get_status_info()) response = self._client.open_api_do("GET", "data", self._dataset_id, params=params).json() for item in response["data"]: yield item["remotePath"] return response["totalCount"] # type: ignore[no-any-return] def _generate_data(self, offset: int = 0, limit: int = 128) -> Generator[RemoteData, None, int]: response = self._list_data_details(offset, limit) urls = LazyPage.from_items( offset, limit, self._generate_urls, (item["url"] for item in response["dataDetails"]), ) mask_urls = {} for key in _MASK_KEYS: mask_urls[key] = LazyPage.from_items( offset, limit, lambda offset, limit, k=key.upper(): ( # type: ignore[misc] self._generate_mask_urls(k, offset, limit) ), (item["label"].get(key.upper(), {}).get("url") for item in response["dataDetails"]), ) for i, item in enumerate(response["dataDetails"]): data = RemoteData.from_response_body( item, url=URL.from_getter(urls.items[i].get, urls.pull), cache_path=self._cache_path, ) label = data.label for key in _MASK_KEYS: mask = getattr(label, key, None) if mask: mask.url = URL.from_getter(mask_urls[key].items[i].get, mask_urls[key].pull) mask.cache_path = os.path.join(self._cache_path, key, mask.path) yield data return response["totalCount"] # type: ignore[no-any-return] def _generate_urls(self, offset: int = 0, limit: int = 128) -> Generator[str, None, int]: response = self._list_urls(offset, limit) for item in response["urls"]: yield item["url"] return response["totalCount"] # type: ignore[no-any-return] def _generate_mask_urls( self, mask_type: str, offset: int = 0, limit: int = 128 ) -> Generator[Optional[str], None, int]: response = self._list_mask_urls(mask_type, offset, limit) for item in response["urls"]: yield item["url"] if item else None return response["totalCount"] # type: ignore[no-any-return] def _upload_or_import_data(self, data: Union[Data, AuthData]) -> Optional[Dict[str, Any]]: if isinstance(data, Data): self._upload_file(data) self._upload_mask_files(data.label) return data.get_callback_body() self._synchronize_import_info((data.get_callback_body(),)) return None def upload_file(self, local_path: str, target_remote_path: str = "") -> None: """Upload data with local path to the draft. Arguments: local_path: The local path of the data to upload. target_remote_path: The path to save the data in segment client. """ self._status.check_authority_for_draft() data = Data(local_path, target_remote_path=target_remote_path) self._upload_file(data) self._synchronize_upload_info((data.get_callback_body(),)) def upload_data(self, data: Data) -> None: """Upload Data object to the draft. Arguments: data: The :class:`~tensorbay.dataset.data.Data`. """ self._status.check_authority_for_draft() self._upload_file(data) self._upload_mask_files(data.label) self._synchronize_upload_info((data.get_callback_body(),)) def import_auth_data(self, data: AuthData) -> None: """Import AuthData object to the draft. Arguments: data: The :class:`~tensorbay.dataset.data.Data`. """ self._status.check_authority_for_draft() self._synchronize_import_info((data.get_callback_body(),)) def copy_data( self, source_remote_paths: Union[str, Iterable[str]], target_remote_paths: Union[None, str, Iterable[str]] = None, *, source_client: Optional["SegmentClient"] = None, strategy: str = "abort", ) -> None: """Copy data to this segment. Arguments: source_remote_paths: The source remote paths of the copied data. target_remote_paths: The target remote paths of the copied data. This argument is used to specify new remote paths of the copied data. If None, the remote path of the copied data will not be changed after copy. source_client: The source segment client of the copied data. This argument is used to specifies where the copied data comes from when the copied data is from another commit, draft, segment or even another dataset. If None, the copied data comes from this segment. strategy: The strategy of handling the name conflict. There are three options: 1. "abort": stop copying and raise exception; 2. "override": the source data will override the origin data; 3. "skip": keep the origin data. Raises: InvalidParamsError: When strategy is invalid. ValueError: When the type of target_remote_paths is not equal with source_remote_paths. """ self._status.check_authority_for_draft() if strategy not in _STRATEGIES: raise InvalidParamsError(param_name="strategy", param_value=strategy) if not target_remote_paths: all_target_remote_paths = [] all_source_remote_paths = ( [source_remote_paths] if isinstance(source_remote_paths, str) else list(source_remote_paths) ) elif isinstance(source_remote_paths, str) and isinstance(target_remote_paths, str): all_target_remote_paths = [target_remote_paths] all_source_remote_paths = [source_remote_paths] elif not isinstance(source_remote_paths, str) and not isinstance(target_remote_paths, str): all_target_remote_paths = list(target_remote_paths) all_source_remote_paths = list(source_remote_paths) if len(all_target_remote_paths) != len(all_source_remote_paths): raise ValueError( "To copy the data, the length of target_remote_paths " "must be equal with source_remote_paths" ) else: raise ValueError( "To copy the data, the type of target_remote_paths " "must be equal with source_remote_paths" ) source = {} if source_client: source["segmentName"] = source_client.name source["id"] = source_client._dataset_id # pylint: disable=protected-access source.update(source_client.status.get_status_info()) else: source["segmentName"] = self.name post_data: Dict[str, Any] = { "strategy": strategy, "source": source, "segmentName": self.name, } post_data.update(self._status.get_status_info()) for targets, sources in zip_longest( chunked(all_target_remote_paths, 128), chunked(all_source_remote_paths, 128) ): if targets: post_data["remotePaths"] = targets post_data["source"]["remotePaths"] = sources self._client.open_api_do("POST", "data?multipleCopy", self._dataset_id, json=post_data) def move_data( self, source_remote_paths: Union[str, Iterable[str]], target_remote_paths: Union[None, str, Iterable[str]] = None, *, source_client: Optional["SegmentClient"] = None, strategy: str = "abort", ) -> None: """Move data to this segment, also used to rename data. Arguments: source_remote_paths: The source remote paths of the moved data. target_remote_paths: The target remote paths of the moved data. This argument is used to specify new remote paths of the moved data. If None, the remote path of the moved data will not be changed after copy. source_client: The source segment client of the moved data. This argument is used to specifies where the moved data comes from when the moved data is from another segment. If None, the moved data comes from this segment. strategy: The strategy of handling the name conflict. There are three options: 1. "abort": stop copying and raise exception; 2. "override": the source data will override the origin data; 3. "skip": keep the origin data. Raises: InvalidParamsError: When strategy is invalid. ValueError: When the type or the length of target_remote_paths is not equal with source_remote_paths. Or when the dataset_id and drafter_number of source_client is not equal with the current segment client. """ self._status.check_authority_for_draft() if strategy not in _STRATEGIES: raise InvalidParamsError(param_name="strategy", param_value=strategy) if not target_remote_paths: all_target_remote_paths = [] all_source_remote_paths = ( [source_remote_paths] if isinstance(source_remote_paths, str) else list(source_remote_paths) ) elif isinstance(source_remote_paths, str) and isinstance(target_remote_paths, str): all_target_remote_paths = [target_remote_paths] all_source_remote_paths = [source_remote_paths] elif not isinstance(source_remote_paths, str) and not isinstance(target_remote_paths, str): all_target_remote_paths = list(target_remote_paths) all_source_remote_paths = list(source_remote_paths) if len(all_target_remote_paths) != len(all_source_remote_paths): raise ValueError( "To move the data, the length of target_remote_paths " "must be equal with source_remote_paths" ) else: raise ValueError( "To move the data, the type of target_remote_paths " "must be equal with source_remote_paths" ) source = {} if source_client: if ( source_client.status.draft_number == self.status.draft_number and source_client._dataset_id # pylint: disable=protected-access == self._dataset_id ): source["segmentName"] = source_client.name else: raise ValueError( "To move the data, the dataset_id and drafter_number of source_client " "must be equal with the current segment client" ) else: source["segmentName"] = self.name post_data: Dict[str, Any] = { "strategy": strategy, "source": source, "segmentName": self.name, } post_data.update(self._status.get_status_info()) for targets, sources in zip_longest( chunked(all_target_remote_paths, 128), chunked(all_source_remote_paths, 128) ): if targets: post_data["remotePaths"] = targets post_data["source"]["remotePaths"] = sources self._client.open_api_do("POST", "data?multipleMove", self._dataset_id, json=post_data) def list_data_paths(self) -> PagingList[str]: """List required data path in a segment in a certain commit. Returns: The PagingList of data paths. """ return PagingList(self._generate_data_paths, 128) def get_data(self, remote_path: str) -> RemoteData: """Get required Data object from a dataset segment. Arguments: remote_path: The remote paths of the required data. Returns: :class:`~tensorbay.dataset.data.RemoteData`. Raises: ResourceNotExistError: When the required data does not exist. """ if not remote_path: raise ResourceNotExistError(resource="data", identification=remote_path) data_details = self._get_data_details(remote_path) data = RemoteData.from_response_body( data_details, url=URL(data_details["url"], lambda: self._get_url(remote_path)), cache_path=self._cache_path, ) label = data.label for key in _MASK_KEYS: mask = getattr(label, key, None) if mask: mask.url = URL( data_details["label"][key.upper()]["url"], lambda k=key.upper(), r=remote_path: ( # type: ignore[misc, arg-type] self._get_mask_url(k, r) ), ) mask.cache_path = os.path.join(self._cache_path, key, mask.path) return data def list_data(self) -> PagingList[RemoteData]: """List required Data object in a dataset segment. Returns: The PagingList of :class:`~tensorbay.dataset.data.RemoteData`. """ return PagingList(self._generate_data, 128) def delete_data(self, remote_path: str) -> None: """Delete data of a segment in a certain commit with the given remote paths. Arguments: remote_path: The remote path of data in a segment. """ self._status.check_authority_for_draft() delete_data: Dict[str, Any] = { "segmentName": self.name, "remotePath": remote_path, } delete_data.update(self._status.get_status_info()) self._client.open_api_do("DELETE", "data", self._dataset_id, json=delete_data) def list_urls(self) -> PagingList[str]: """List the data urls in this segment. Returns: The PagingList of urls. """ return PagingList(self._generate_urls, 128) def list_mask_urls(self, mask_type: str) -> PagingList[Optional[str]]: """List the mask urls in this segment. Arguments: mask_type: The required mask type, the supported types are ``SEMANTIC_MASK``, ``INSTANCE_MASK`` and ``PANOPTIC_MASK`` Returns: The PagingList of mask urls. """ return PagingList( lambda offset, limit: self._generate_mask_urls(mask_type, offset, limit), 128 ) class FusionSegmentClient(SegmentClientBase): """This class defines :class:`FusionSegmentClient`. :class:`FusionSegmentClient` inherits from :class:`SegmentClientBase` and provides methods within a fusion segment scope, such as :meth:`FusionSegmentClient.upload_sensor`, :meth:`FusionSegmentClient.upload_frame` and :meth:`FusionSegmentClient.list_frames`. In contrast to :class:`SegmentClient`, :class:`FusionSegmentClient` has multiple sensors. """ _dataset_client: "FusionDatasetClient" def __init__(self, name: str, data_client: "FusionDatasetClient") -> None: super().__init__(name, data_client) def _generate_frames(self, offset: int = 0, limit: int = 128) -> Generator[Frame, None, int]: response = self._list_data_details(offset, limit) url_page = LazyPage.from_items( offset, limit, self._generate_urls, ( {frame["sensorName"]: frame["url"] for frame in item["frame"]} for item in response["dataDetails"] ), ) for index, item in enumerate(response["dataDetails"]): yield Frame.from_response_body(item, index, url_page, cache_path=self._cache_path) return response["totalCount"] # type: ignore[no-any-return] def _generate_urls( self, offset: int = 0, limit: int = 128 ) -> Generator[Dict[str, str], None, int]: response = self._list_urls(offset, limit) for frame in response["urls"]: yield {item["sensorName"]: item["url"] for item in frame["urls"]} return response["totalCount"] # type: ignore[no-any-return] def _upload_or_import_data( self, data: Union[Data, AuthData], sensor_name: str, frame_id: str, ) -> Optional[Dict[str, Any]]: callback_body = data.get_callback_body() callback_body["frameId"] = frame_id callback_body["sensorName"] = sensor_name if isinstance(data, Data): self._upload_file(data) self._upload_mask_files(data.label) return callback_body self._synchronize_import_info((callback_body,)) return None def get_sensors(self) -> Sensors: """Return the sensors in a fusion segment client. Returns: The :class:`sensors<~tensorbay.sensor.sensor.Sensors>` in the fusion segment client. """ params: Dict[str, Any] = {"segmentName": self._name} params.update(self._status.get_status_info()) response = self._client.open_api_do( "GET", "sensors", self._dataset_id, params=params ).json() return Sensors.loads(response["sensors"]) def upload_sensor(self, sensor: Sensor) -> None: """Upload sensor to the draft. Arguments: sensor: The sensor to upload. """ self._status.check_authority_for_draft() post_data = sensor.dumps() post_data.update(self._status.get_status_info()) post_data["segmentName"] = self._name self._client.open_api_do("POST", "sensors", self._dataset_id, json=post_data) def delete_sensor(self, sensor_name: str) -> None: """Delete a TensorBay sensor of the draft with the given sensor name. Arguments: sensor_name: The TensorBay sensor to delete. """ self._status.check_authority_for_draft() delete_data: Dict[str, Any] = {"segmentName": self._name, "sensorName": sensor_name} delete_data.update(self._status.get_status_info()) self._client.open_api_do("DELETE", "sensors", self._dataset_id, json=delete_data) def upload_frame(self, frame: Frame, timestamp: Optional[float] = None) -> None: """Upload frame to the draft. Arguments: frame: The :class:`~tensorbay.dataset.frame.Frame` to upload. timestamp: The mark to sort frames, supporting timestamp and float. Raises: FrameError: When lacking frame id or frame id conflicts. """ self._status.check_authority_for_draft() if timestamp is None: try: frame_id = frame.frame_id except AttributeError as error: raise FrameError( "Lack frame id, please add frame id in frame or " "give timestamp to the function!" ) from error elif not hasattr(frame, "frame_id"): frame_id = from_timestamp(timestamp) else: raise FrameError("Frame id conflicts, please do not give timestamp to the function!.") callback_bodies = [] for sensor_name, data in frame.items(): try: callback_body = data.get_callback_body() # type:ignore[union-attr] except AttributeError: continue callback_body["frameId"] = frame_id.str callback_body["sensorName"] = sensor_name if isinstance(data, Data): self._upload_file(data) self._upload_mask_files(data.label) callback_bodies.append(callback_body) elif isinstance(data, AuthData): self._synchronize_import_info((callback_body,)) for chunked_callback_bodies in chunked(callback_bodies, 50): self._synchronize_upload_info(chunked_callback_bodies) def list_frames(self) -> PagingList[Frame]: """List required frames in the segment in a certain commit. Returns: The PagingList of :class:`~tensorbay.dataset.frame.Frame`. """ return PagingList(self._generate_frames, 128) def delete_frame(self, frame_id: Union[str, ULID]) -> None: """Delete a frame of a segment in a certain commit with the given frame id. Arguments: frame_id: The id of a frame in a segment. """ self._status.check_authority_for_draft() delete_data: Dict[str, Any] = { "segmentName": self.name, "frameId": str(frame_id), } delete_data.update(self._status.get_status_info()) self._client.open_api_do("DELETE", "frames", self._dataset_id, json=delete_data) def list_urls(self) -> PagingList[Dict[str, str]]: """List the data urls in this segment. Returns: The PagingList of url dict, which key is the sensor name, value is the url. """ urls = PagingList(self._generate_urls, 128) urls._repr_maxlevel = 2 # pylint: disable=protected-access return urls
# Copyright 2021 F5 Networks All rights reserved. # # Version 3.14.0 """Creates BIG-IP""" COMPUTE_URL_BASE = 'https://www.googleapis.com/compute/v1/' def Storage(context,storageName): # Build storage container storage = { 'name': storageName, 'type': 'storage.v1.bucket', 'properties': { 'project': context.env['project'], 'name': storageName, } } return storage def Instance(context,storageName,deployment): # Build instance template instance = { 'name': 'bigip-' + deployment, 'type': 'compute.v1.instanceTemplate', 'properties': { 'properties': { 'canIpForward': True, 'tags': { 'items': ['mgmtfw-' + context.env['deployment'],'appfw-' + context.env['deployment'],'syncfw-' + context.env['deployment'],] }, 'labels': { 'f5_deployment': context.env['deployment'] }, 'machineType': context.properties['instanceType'], 'serviceAccounts': [{ 'email': context.properties['serviceAccount'], 'scopes': ['https://www.googleapis.com/auth/compute','https://www.googleapis.com/auth/devstorage.read_write','https://www.googleapis.com/auth/pubsub'] }], 'disks': [{ 'deviceName': 'boot', 'type': 'PERSISTENT', 'boot': True, 'autoDelete': True, 'initializeParams': { 'sourceImage': ''.join([COMPUTE_URL_BASE, 'projects/f5-7626-networks-public', '/global/images/', context.properties['imageName'], ]) } }], 'networkInterfaces': [{ 'network': ''.join([COMPUTE_URL_BASE, 'projects/', context.env['project'], '/global/networks/', context.properties['mgmtNetwork']]), 'subnetwork': ''.join([COMPUTE_URL_BASE, 'projects/', context.env['project'], '/regions/', context.properties['region'], '/subnetworks/', context.properties['mgmtSubnet']]), 'accessConfigs': [{ 'name': 'Management NAT', 'type': 'ONE_TO_ONE_NAT' }], }], 'metadata': Metadata(context,storageName,deployment) } } } return instance def Igm(context,deployment): # Build instance group manager igm = { 'name': deployment + '-igm', 'type': 'compute.v1.instanceGroupManager', 'properties': { 'baseInstanceName': deployment + '-bigip', 'instanceTemplate': ''.join(['$(ref.', 'bigip-' + deployment, '.selfLink)']), 'targetSize': int(context.properties['targetSize']), 'targetPools': ['$(ref.' + deployment + '-tp.selfLink)'], 'zone': context.properties['availabilityZone1'], } } return igm def Autoscaler(context,deployment): # Build autoscaler autoscaler = { 'name': deployment + 'big-ip-as', 'type': 'compute.v1.autoscalers', 'properties': { 'zone': context.properties['availabilityZone1'], 'target': '$(ref.' + deployment + '-igm.selfLink)', 'autoscalingPolicy': { "minNumReplicas": int(context.properties['minReplicas']), 'maxNumReplicas': int(context.properties['maxReplicas']), 'cpuUtilization': { 'utilizationTarget': float(context.properties['cpuUtilization']) }, 'coolDownPeriodSec': int(context.properties['coolDownPeriod']) } }, } return autoscaler def HealthCheck(context,deployment): # Build health autoscaler health check healthCheck = { 'name': deployment, 'type': 'compute.v1.httpHealthCheck', 'properties': { 'port': int(context.properties['applicationPort']), 'host': str(context.properties['applicationDnsName']), } } return healthCheck def TargetPool(context,deployment): # Build lb target pool targetPool = { 'name': deployment + '-tp', 'type': 'compute.v1.targetPool', 'properties': { 'region': context.properties['region'], 'healthChecks': ['$(ref.' + deployment + '.selfLink)'], 'sessionAffinity': 'CLIENT_IP', } } return targetPool def ForwardingRule(context,deployment): # Build forwarding rule forwardingRule = { 'name': deployment + '-fr', 'type': 'compute.v1.forwardingRule', 'properties': { 'region': context.properties['region'], 'IPProtocol': 'TCP', 'target': '$(ref.' + deployment + '-tp.selfLink)', 'loadBalancingScheme': 'EXTERNAL', } } return forwardingRule def FirewallRuleSync(context): # Build Sync traffic firewall rule firewallRuleSync = { 'name': 'syncfw-' + context.env['deployment'], 'type': 'compute.v1.firewall', 'properties': { 'network': ''.join([COMPUTE_URL_BASE, 'projects/', context.env['project'], '/global/networks/', context.properties['mgmtNetwork']]), 'targetTags': ['syncfw-'+ context.env['deployment']], 'sourceTags': ['syncfw-'+ context.env['deployment']], 'allowed': [{ 'IPProtocol': 'TCP', 'ports': ['4353'] },{ 'IPProtocol': 'UDP', 'ports': ['1026'], },{ "IPProtocol": "TCP", "ports": ['6123-6128'], }, ] } } return firewallRuleSync def FirewallRuleApp(context): # Build Application firewall rule firewallRuleApp = { 'name': 'appfw-' + context.env['deployment'], 'type': 'compute.v1.firewall', 'properties': { 'network': ''.join([COMPUTE_URL_BASE, 'projects/', context.env['project'], '/global/networks/', context.properties['mgmtNetwork']]), 'sourceRanges': ['0.0.0.0/0'], 'targetTags': ['appfw-'+ context.env['deployment']], 'allowed': [{ "IPProtocol": "TCP", "ports": [str(context.properties['applicationPort'])], }, ] } } return firewallRuleApp def FirewallRuleMgmt(context): # Build Management firewall rule firewallRuleMgmt = { 'name': 'mgmtfw-' + context.env['deployment'], 'type': 'compute.v1.firewall', 'properties': { 'network': ''.join([COMPUTE_URL_BASE, 'projects/', context.env['project'], '/global/networks/', context.properties['mgmtNetwork']]), 'sourceRanges': ['0.0.0.0/0'], 'targetTags': ['mgmtfw-'+ context.env['deployment']], 'allowed': [{ "IPProtocol": "TCP", "ports": ['8443','22'], }, ] } } return firewallRuleMgmt def Metadata(context,storageName,deployment): # Build metadata ALLOWUSAGEANALYTICS = str(context.properties['allowUsageAnalytics']) if ALLOWUSAGEANALYTICS == "yes": CUSTHASH = 'CUSTOMERID=`curl -s "http://metadata.google.internal/computeMetadata/v1/project/numeric-project-id" -H "Metadata-Flavor: Google" |sha512sum|cut -d " " -f 1`;\nDEPLOYMENTID=`curl -s "http://metadata.google.internal/computeMetadata/v1/instance/id" -H "Metadata-Flavor: Google"|sha512sum|cut -d " " -f 1`;' SENDANALYTICS = ' --metrics "cloudName:google,region:' + context.properties['region'] + ',bigipVersion:' + context.properties['imageName'] + ',customerId:${CUSTOMERID},deploymentId:${DEPLOYMENTID},templateName:f5-payg-autoscale-bigip-waf.py,templateVersion:3.14.0,licenseType:payg"' else: CUSTHASH = 'echo "No analytics."' SENDANALYTICS = '' # Provisioning modules PROVISIONING_MODULES = ','.join(context.properties['bigIpModules'].split('-')) ## generate metadata metadata = { 'items': [{ 'key': 'startup-script', 'value': ('\n'.join(['#!/bin/bash', 'if [ -f /config/startupFinished ]; then', ' exit', 'fi', 'mkdir -p /config/cloud/gce', 'cat <<\'EOF\' > /config/installCloudLibs.sh', '#!/bin/bash', 'echo about to execute', 'checks=0', 'while [ $checks -lt 120 ]; do echo checking mcpd', ' tmsh -a show sys mcp-state field-fmt | grep -q running', ' if [ $? == 0 ]; then', ' echo mcpd ready', ' break', ' fi', ' echo mcpd not ready yet', ' let checks=checks+1', ' sleep 10', 'done', 'echo loading verifyHash script', 'if ! tmsh load sys config merge file /config/verifyHash; then', ' echo cannot validate signature of /config/verifyHash', ' exit', 'fi', 'echo loaded verifyHash', 'declare -a filesToVerify=(\"/config/cloud/f5-cloud-libs.tar.gz\" \"/config/cloud/f5-cloud-libs-gce.tar.gz\" \"/var/config/rest/downloads/f5-appsvcs-3.31.0-6.noarch.rpm\")', 'for fileToVerify in \"${filesToVerify[@]}\"', 'do', ' echo verifying \"$fileToVerify\"', ' if ! tmsh run cli script verifyHash \"$fileToVerify\"; then', ' echo \"$fileToVerify\" is not valid', ' exit 1', ' fi', ' echo verified \"$fileToVerify\"', 'done', 'mkdir -p /config/cloud/gce/node_modules/@f5devcentral', 'echo expanding f5-cloud-libs.tar.gz', 'tar xvfz /config/cloud/f5-cloud-libs.tar.gz -C /config/cloud/gce/node_modules/@f5devcentral', 'echo expanding f5-cloud-libs-gce.tar.gz', 'tar xvfz /config/cloud/f5-cloud-libs-gce.tar.gz -C /config/cloud/gce/node_modules/@f5devcentral', 'echo "expanding waf policies"', 'tar xvfz /config/cloud/asm-policy-linux.tar.gz -C /config/cloud', 'echo cloud libs install complete', 'touch /config/cloud/cloudLibsReady', 'EOF', 'echo \'Y2xpIHNjcmlwdCAvQ29tbW9uL3ZlcmlmeUhhc2ggewpwcm9jIHNjcmlwdDo6cnVuIHt9IHsKICAgICAgICBpZiB7W2NhdGNoIHsKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS1jbG91ZC1saWJzLnRhci5neikgZThkOTYyZTI5NWE2MDY4NzMxMGI1MGNiZjEwODVjM2JjNjljNzZjMjk0MzljYmNlNjE0MWE1Njc3ZDg5ZmZhZGRlOWFhMWU3MzA4YTg1NDQ4NmFhYmE3OThjZTk4ZTM1YmQyNWZlYjlmY2M2ZDk0MDJhOWI3MmVjODc4NTYzNjEKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS1jbG91ZC1saWJzLWF3cy50YXIuZ3opIDA5MWVhN2IxOGFjYTdmMThhMGVjMzc3YTY4ODZkNWQ2NjZjYzgxMzQ5ZWFmYTU3MjVhYjA3NThkZGNjMTdjMTBlMDM3MzcxOTUzODRlYWZkNjNjMTE3ZDI1OTEzYzE1YTExMjg0ZDJjYzNiMjIxZDdiYTNjMzE0MjIxNzIxNDJiCiAgICAgICAgICAgIHNldCBoYXNoZXMoZjUtY2xvdWQtbGlicy1henVyZS50YXIuZ3opIGU3OTczYTFmZTg1YjVhODMyYzVlY2QxY2ZjZTY2YjQzYjg0ZTQyY2YyYTA2YjI3NTE3MzRmNzk4MTJkZTE4N2VlMWFkODczMGExMjljYjA4MTk4YTQ1MjE1N2M0NjZiYjg3MTgwYzE3ZGZkMmUwOWI0OWJlNmVmZTllOWE1N2ZlCiAgICAgICAgICAgIHNldCBoYXNoZXMoZjUtY2xvdWQtbGlicy1nY2UudGFyLmd6KSBjZDk1YTVjYzM2YzM5ZjgwZjk1NDc2YWQwMDBmN2RjYzIxYTlmZWY0MTRjOGVkYWM4MmJlMmU0OTFjMGZhOWViYTUxYjE0NWY3NWJhMGYzYzBkYWU0OGUxYzczMTQzMjIxN2IzYmI3MDBmNzFmZTE5MTIxNTJkYmU0MzllODk2NwogICAgICAgICAgICBzZXQgaGFzaGVzKGY1LWNsb3VkLWxpYnMtb3BlbnN0YWNrLnRhci5neikgNWM4M2ZlNmE5M2E2ZmNlYjVhMmU4NDM3YjVlZDhjYzlmYWY0YzE2MjFiZmM5ZTZhMDc3OWY2YzIxMzdiNDVlYWI4YWUwZTdlZDc0NWM4Y2Y4MjFiOTM3MTI0NWNhMjk3NDljYTBiN2U1NjYzOTQ5ZDc3NDk2Yjg3MjhmNGIwZjkKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS1jbG91ZC1saWJzLWNvbnN1bC50YXIuZ3opIGEzMmFhYjM5NzA3M2RmOTJjYmJiYTUwNjdlNTgyM2U5YjVmYWZjYTg2MmEyNThiNjBiNmI0MGFhMDk3NWMzOTg5ZDFlMTEwZjcwNjE3N2IyZmZiZTRkZGU2NTMwNWEyNjBhNTg1NjU5NGNlN2FkNGVmMGM0N2I2OTRhZTRhNTEzCiAgICAgICAgICAgIHNldCBoYXNoZXMoYXNtLXBvbGljeS1saW51eC50YXIuZ3opIDYzYjVjMmE1MWNhMDljNDNiZDg5YWYzNzczYmJhYjg3YzcxYTZlN2Y2YWQ5NDEwYjIyOWI0ZTBhMWM0ODNkNDZmMWE5ZmZmMzlkOTk0NDA0MWIwMmVlOTI2MDcyNDAyNzQxNGRlNTkyZTk5ZjRjMjQ3NTQxNTMyM2UxOGE3MmUwCiAgICAgICAgICAgIHNldCBoYXNoZXMoZjUuaHR0cC52MS4yLjByYzQudG1wbCkgNDdjMTlhODNlYmZjN2JkMWU5ZTljMzVmMzQyNDk0NWVmODY5NGFhNDM3ZWVkZDE3YjZhMzg3Nzg4ZDRkYjEzOTZmZWZlNDQ1MTk5YjQ5NzA2NGQ3Njk2N2IwZDUwMjM4MTU0MTkwY2EwYmQ3Mzk0MTI5OGZjMjU3ZGY0ZGMwMzQKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS5odHRwLnYxLjIuMHJjNi50bXBsKSA4MTFiMTRiZmZhYWI1ZWQwMzY1ZjAxMDZiYjVjZTVlNGVjMjIzODU2NTVlYTNhYzA0ZGUyYTM5YmQ5OTQ0ZjUxZTM3MTQ2MTlkYWU3Y2E0MzY2MmM5NTZiNTIxMjIyODg1OGYwNTkyNjcyYTI1NzlkNGE4Nzc2OTE4NmUyY2JmZQogICAgICAgICAgICBzZXQgaGFzaGVzKGY1Lmh0dHAudjEuMi4wcmM3LnRtcGwpIDIxZjQxMzM0MmU5YTdhMjgxYTBmMGUxMzAxZTc0NWFhODZhZjIxYTY5N2QyZTZmZGMyMWRkMjc5NzM0OTM2NjMxZTkyZjM0YmYxYzJkMjUwNGMyMDFmNTZjY2Q3NWM1YzEzYmFhMmZlNzY1MzIxMzY4OWVjM2M5ZTI3ZGZmNzdkCiAgICAgICAgICAgIHNldCBoYXNoZXMoZjUuYXdzX2FkdmFuY2VkX2hhLnYxLjMuMHJjMS50bXBsKSA5ZTU1MTQ5YzAxMGMxZDM5NWFiZGFlM2MzZDJjYjgzZWMxM2QzMWVkMzk0MjQ2OTVlODg2ODBjZjNlZDVhMDEzZDYyNmIzMjY3MTFkM2Q0MGVmMmRmNDZiNzJkNDE0YjRjYjhlNGY0NDVlYTA3MzhkY2JkMjVjNGM4NDNhYzM5ZAogICAgICAgICAgICBzZXQgaGFzaGVzKGY1LmF3c19hZHZhbmNlZF9oYS52MS40LjByYzEudG1wbCkgZGUwNjg0NTUyNTc0MTJhOTQ5ZjFlYWRjY2FlZTg1MDYzNDdlMDRmZDY5YmZiNjQ1MDAxYjc2ZjIwMDEyNzY2OGU0YTA2YmUyYmJiOTRlMTBmZWZjMjE1Y2ZjMzY2NWIwNzk0NWU2ZDczM2NiZTFhNGZhMWI4OGU4ODE1OTAzOTYKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS5hd3NfYWR2YW5jZWRfaGEudjEuNC4wcmMyLnRtcGwpIDZhYjBiZmZjNDI2ZGY3ZDMxOTEzZjlhNDc0YjFhMDc4NjA0MzVlMzY2YjA3ZDc3YjMyMDY0YWNmYjI5NTJjMWYyMDdiZWFlZDc3MDEzYTE1ZTQ0ZDgwZDc0ZjMyNTNlN2NmOWZiYmUxMmE5MGVjNzEyOGRlNmZhY2QwOTdkNjhmCiAgICAgICAgICAgIHNldCBoYXNoZXMoZjUuYXdzX2FkdmFuY2VkX2hhLnYxLjQuMHJjMy50bXBsKSAyZjIzMzliNGJjM2EyM2M5Y2ZkNDJhYWUyYTZkZTM5YmEwNjU4MzY2ZjI1OTg1ZGUyZWE1MzQxMGE3NDVmMGYxOGVlZGM0OTFiMjBmNGE4ZGJhOGRiNDg5NzAwOTZlMmVmZGNhN2I4ZWZmZmExYTgzYTc4ZTVhYWRmMjE4YjEzNAogICAgICAgICAgICBzZXQgaGFzaGVzKGY1LmF3c19hZHZhbmNlZF9oYS52MS40LjByYzQudG1wbCkgMjQxOGFjOGIxZjE4ODRjNWMwOTZjYmFjNmE5NGQ0MDU5YWFhZjA1OTI3YTZhNDUwOGZkMWYyNWI4Y2M2MDc3NDk4ODM5ZmJkZGE4MTc2ZDJjZjJkMjc0YTI3ZTZhMWRhZTJhMWUzYTBhOTk5MWJjNjVmYzc0ZmMwZDAyY2U5NjMKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS5hd3NfYWR2YW5jZWRfaGEudjEuNC4wcmM1LnRtcGwpIDVlNTgyMTg3YWUxYTYzMjNlMDk1ZDQxZWRkZDQxMTUxZDZiZDM4ZWI4M2M2MzQ0MTBkNDUyN2EzZDBlMjQ2YThmYzYyNjg1YWIwODQ5ZGUyYWRlNjJiMDI3NWY1MTI2NGQyZGVhY2NiYzE2Yjc3MzQxN2Y4NDdhNGExZWE5YmM0CiAgICAgICAgICAgIHNldCBoYXNoZXMoYXNtLXBvbGljeS50YXIuZ3opIDJkMzllYzYwZDAwNmQwNWQ4YTE1NjdhMWQ4YWFlNzIyNDE5ZThiMDYyYWQ3N2Q2ZDlhMzE2NTI5NzFlNWU2N2JjNDA0M2Q4MTY3MWJhMmE4YjEyZGQyMjllYTQ2ZDIwNTE0NGY3NTM3NGVkNGNhZTU4Y2VmYThmOWFiNjUzM2U2CiAgICAgICAgICAgIHNldCBoYXNoZXMoZGVwbG95X3dhZi5zaCkgMWEzYTNjNjI3NGFiMDhhN2RjMmNiNzNhZWRjOGQyYjJhMjNjZDllMGViMDZhMmUxNTM0YjM2MzJmMjUwZjFkODk3MDU2ZjIxOWQ1YjM1ZDNlZWQxMjA3MDI2ZTg5OTg5Zjc1NDg0MGZkOTI5NjljNTE1YWU0ZDgyOTIxNGZiNzQKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS5wb2xpY3lfY3JlYXRvci50bXBsKSAwNjUzOWUwOGQxMTVlZmFmZTU1YWE1MDdlY2I0ZTQ0M2U4M2JkYjFmNTgyNWE5NTE0OTU0ZWY2Y2E1NmQyNDBlZDAwYzdiNWQ2N2JkOGY2N2I4MTVlZTlkZDQ2NDUxOTg0NzAxZDA1OGM4OWRhZTI0MzRjODk3MTVkMzc1YTYyMAogICAgICAgICAgICBzZXQgaGFzaGVzKGY1LnNlcnZpY2VfZGlzY292ZXJ5LnRtcGwpIDQ4MTFhOTUzNzJkMWRiZGJiNGY2MmY4YmNjNDhkNGJjOTE5ZmE0OTJjZGEwMTJjODFlM2EyZmU2M2Q3OTY2Y2MzNmJhODY3N2VkMDQ5YTgxNGE5MzA0NzMyMzRmMzAwZDNmOGJjZWQyYjBkYjYzMTc2ZDUyYWM5OTY0MGNlODFiCiAgICAgICAgICAgIHNldCBoYXNoZXMoZjUuY2xvdWRfbG9nZ2VyLnYxLjAuMC50bXBsKSA2NGEwZWQzYjVlMzJhMDM3YmE0ZTcxZDQ2MDM4NWZlOGI1ZTFhZWNjMjdkYzBlODUxNGI1MTE4NjM5NTJlNDE5YTg5ZjRhMmE0MzMyNmFiYjU0M2JiYTliYzM0Mzc2YWZhMTE0Y2VkYTk1MGQyYzNiZDA4ZGFiNzM1ZmY1YWQyMAogICAgICAgICAgICBzZXQgaGFzaGVzKGY1LWFwcHN2Y3MtMy41LjEtNS5ub2FyY2gucnBtKSBiYTcxYzZlMWM1MmQwYzcwNzdjZGIyNWE1ODcwOWI4ZmI3YzM3YjM0NDE4YTgzMzhiYmY2NzY2ODMzOTY3NmQyMDhjMWE0ZmVmNGU1NDcwYzE1MmFhYzg0MDIwYjRjY2I4MDc0Y2UzODdkZTI0YmUzMzk3MTEyNTZjMGZhNzhjOAogICAgICAgICAgICBzZXQgaGFzaGVzKGY1LWFwcHN2Y3MtMy4xOC4wLTQubm9hcmNoLnJwbSkgZTcyZWU4MDA1YTI3MDcwYWMzOTlhYjA5N2U4YWE1MDdhNzJhYWU0NzIxZDc0OTE1ODljZmViODIxZGIzZWY4NmNiYzk3OWU3OTZhYjMxOWVjNzI3YmI1MTQwMGNjZGE4MTNjNGI5ZWI0YTZiM2QxMjIwYTM5NmI1ODJmOGY0MDAKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS1hcHBzdmNzLTMuMjAuMC0zLm5vYXJjaC5ycG0pIGQ0YmJhODg5MmEyMDY4YmI1M2Y4OGM2MDkwZGM2NWYxNzcwN2FiY2EzNWE3ZWQyZmZmMzk5ODAwNTdmZTdmN2EyZWJmNzEwYWIyMjg0YTFkODNkNzBiNzc0NmJlYWJhZDlkZjYwMzAxN2MwZmQ4NzI4Zjc0NTc2NjFjOTVhYzhkCiAgICAgICAgICAgIHNldCBoYXNoZXMoZjUtYXBwc3Zjcy0zLjI1LjAtMy5ub2FyY2gucnBtKSAyNmYxOWJkYWFhODFjYmUwNDIxYjNlMDhjMDk5ODdmOWRkMGM1NGIwNWE2MjZkNmEyMWE4MzZiMzQyNDhkMmQ5ZDgzMDk1ZjBkYWFkOGU3YTRhMDY4ZTllZjk5Yjg5ZmJjZDI0NmFlOGI2MTdhYzJiMjQ1NjU5OTE1N2QwZThiMwogICAgICAgICAgICBzZXQgaGFzaGVzKGY1LWFwcHN2Y3MtMy4yNi4xLTEubm9hcmNoLnJwbSkgYjQ2MGUxMTY3OWQzOGE5NjU0OWI1MDQxZGVmMjdiNDE5ZjFhNDFjOGY3ODhmOWY4YzdhMDM0YWE1Y2I1YThjOWZkMTUxYzdjNDM5YmViZDA5M2ZjZDg1Y2Q4NjU3ZjFjMDY0NTUxZDkzMzc1NjZmOWZjN2U5NTA2YzU1ZGMwMmMKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS1hcHBzdmNzLTMuMzEuMC02Lm5vYXJjaC5ycG0pIDY1MDZmZGU1ZDFjMmUwNjc2NjJiNTEzMzg3ZGNjZGEwMjgxZDNiYmM2MDRmYzZkY2Y4ZTU3NDBhZTU2Mzc0ODg5OWY3ZjMzNWUzNDkwMDZmZTNmMGU3NTFjZDcwZDRlZjhiZTM3MDFhZTQ1ZGNhMzA1ZGU2NDlmMjU5ZjA5MGE5CiAgICAgICAgICAgIHNldCBoYXNoZXMoZjUtY2xvdWQtZmFpbG92ZXItMS4xLjAtMC5ub2FyY2gucnBtKSAxNWE0NDBjMjk5ZjllNGFmODZhM2QwZjViMGQ3NWIwMDU0Mzg1Yjk1ZTQ3YzNlZjExNmQyZTBiZmIwMDQxYTI2ZGNiZjU0OTAyOGUyYTI2ZDJjNzE4ZWM2MTQ0NmJkNjU3YmUzOGZiYmNkOWRiNzgxZWZlNTQxNGMxNzRhYzY4YwogICAgICAgICAgICBzZXQgaGFzaGVzKGY1LWNsb3VkLWZhaWxvdmVyLTEuMy4wLTAubm9hcmNoLnJwbSkgMTk2ODFlYjMzZDlmOTEwYzkxM2Y4MTgwMTk5NDg1ZWI2NTNiNGI1ZWJlYWFlMGI5MGE2Y2U4MzQxZDdhMjJmZWQ4ZDIxODE1YjViYTE0OGM0Njg4NTJkMjBjYzI2ZmFkNGM0MjQyZTUwZWNjMTg0ZjFmODc3MGRhY2NlZDZmNmEKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS1jbG91ZC1mYWlsb3Zlci0xLjQuMC0wLm5vYXJjaC5ycG0pIDQ5ZTkxMDhhMDcwZTBjODcxM2FlYjdiMzMwNjYyMzU4NTQyZTYxYjdjNTNhOWQ0NTEwOGQzN2E5YmY1MjQ2ZjllNGFhYWUxMGNjNjEwNjQ4MDFkY2NjZDIwYmZkNTEwODM0N2IwZjY5NDUxMGU3ZWNlMDdmOTZjNDViYTY4M2IwCiAgICAgICAgICAgIHNldCBoYXNoZXMoZjUtY2xvdWQtZmFpbG92ZXItMS41LjAtMC5ub2FyY2gucnBtKSAzM2E3ZTJkMDQ3MTA2YmNjZTY4MTc1N2E2NTI0MGJmYWNlZGQ0OGUxMzU2N2UwNWZkYjIzYTRiMjY5ZDI2NmFhNTAwMWY4MTE1OGMzOTY0ZGMyOTdmMDQyOGRiMzFjOWRmNDI4MDAyODk4ZDE5MDI4NWIzNDljNTk0MjJhNTczYgogICAgICAgICAgICBzZXQgaGFzaGVzKGY1LWNsb3VkLWZhaWxvdmVyLTEuNi4xLTEubm9hcmNoLnJwbSkgYzFiODQyZGEyMWI4ZDFiYTIxYjZlYjYzYzg1OThhOWVhOTk4NmQ1ZGFkZGMyMWU0ZDI4MGUxZDZiMDlkM2RiMWRlOGFjN2RlNWM4NGVkZjA3YjQzZTRhZjAzZGFmOGZlNzQ3YTQwNDhmNjU3M2Q5NTUyMDYzNTJjZGUyY2VjNjUKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS1jbG91ZC1mYWlsb3Zlci0xLjcuMS0xLm5vYXJjaC5ycG0pIDE0ZmYwY2QyYmI0OTc4MGNjMGFlMzAyMWM0ZmM4ZmNjMDk2ZTNmY2UyMjU4MDk2YTRhYTAyNmQ2ZDM3ZGU3MjhjYTczNDViZmUzYTc5MDMxZTMzNmU3NGQyNWEyYjQwZmYyODMyNGMyYzc1MmJmMGVlNzFiN2ZjODliNmZjOGZlCiAgICAgICAgICAgIHNldCBoYXNoZXMoZjUtY2xvdWQtZmFpbG92ZXItMS44LjAtMC5ub2FyY2gucnBtKSAyMzA4NmQxY2JmM2NiMjRlYWM3ZWJhMjMwNTE1NmM2MDBmYTIxZjFiODk2MzIxYTJmYTUyMjVkMzMxZDdlNDE0NzFlZGIzZjUzNjgxNDRkODY4NDhhNDUyMGIxZTAwNWMwMTQ0ODVmZjQ1MWU3ZGE2NDI5MDUzZjU4YmZlOGNlNAogICAgICAgICAgICBzZXQgaGFzaGVzKGY1LWNsb3VkLWZhaWxvdmVyLTEuOS4wLTAubm9hcmNoLnJwbSkgMDljMTUzNzczODlhYzE4MzEzMzcwNjM1ZmI5OWY5YWZmMDU5NzA4MDdjYzYwYmZmMDc0ZjgwZjY2NDAyM2NmYzBkOWY1YjdmMmVkN2E4Zjg3OWRlYjJkYTg0YTAzNGJiOWZhOWY0ZTk1Zjk4MDZkNjQ0YWY1MThkYjMyZjE0MjUKCiAgICAgICAgICAgIHNldCBmaWxlX3BhdGggW2xpbmRleCAkdG1zaDo6YXJndiAxXQogICAgICAgICAgICBzZXQgZmlsZV9uYW1lIFtmaWxlIHRhaWwgJGZpbGVfcGF0aF0KCiAgICAgICAgICAgIGlmIHshW2luZm8gZXhpc3RzIGhhc2hlcygkZmlsZV9uYW1lKV19IHsKICAgICAgICAgICAgICAgIHRtc2g6OmxvZyBlcnIgIk5vIGhhc2ggZm91bmQgZm9yICRmaWxlX25hbWUiCiAgICAgICAgICAgICAgICBleGl0IDEKICAgICAgICAgICAgfQoKICAgICAgICAgICAgc2V0IGV4cGVjdGVkX2hhc2ggJGhhc2hlcygkZmlsZV9uYW1lKQogICAgICAgICAgICBzZXQgY29tcHV0ZWRfaGFzaCBbbGluZGV4IFtleGVjIC91c3IvYmluL29wZW5zc2wgZGdzdCAtciAtc2hhNTEyICRmaWxlX3BhdGhdIDBdCiAgICAgICAgICAgIGlmIHsgJGV4cGVjdGVkX2hhc2ggZXEgJGNvbXB1dGVkX2hhc2ggfSB7CiAgICAgICAgICAgICAgICBleGl0IDAKICAgICAgICAgICAgfQogICAgICAgICAgICB0bXNoOjpsb2cgZXJyICJIYXNoIGRvZXMgbm90IG1hdGNoIGZvciAkZmlsZV9wYXRoIgogICAgICAgICAgICBleGl0IDEKICAgICAgICB9XX0gewogICAgICAgICAgICB0bXNoOjpsb2cgZXJyIHtVbmV4cGVjdGVkIGVycm9yIGluIHZlcmlmeUhhc2h9CiAgICAgICAgICAgIGV4aXQgMQogICAgICAgIH0KICAgIH0KICAgIHNjcmlwdC1zaWduYXR1cmUgaWpMY1dkbHdpNG5mdklINC9qUEZKMVk5WGtvZEtWZHVxN0VGV2plV2sweHdmTjVyVkxrQnNodVJPRkpOdG9uV2w1dXYyS1pHMFNUVDhHY0UvRGk5NnVoNlVWakRKQzBnSHdIcUVGa2pkTzNVRXFQd28wOVJRM2xsaVdyb0YzeGFrazlWUTlSdFNBSCtYUXJGNTlNbUFVRGtTT3llVC9DdUY3QXBKNFdFcmNiWnJzeGlhM1RpUkdCZFVXbXowL1hDZlc0L2ZhRUJHVEFUNkFOdzBhTFZxd2tjZ2pxWS9Ld01xWFlITE5VdmtRYm9KQmZtWVVOQXVnM1ozMjlqN1FTZENCbG9wQk9kcG1aM1JxNURPQm15OXpRd2Ewd205MTF6WDEySUpsaUdGUUwwYW1UTSt3ZTFoSENXRFd0ZDVpQ05rd2lldGtzQlhSNkozMWVpZ0M1U2dBPT0KICAgIHNpZ25pbmcta2V5IC9Db21tb24vZjUtaXJ1bGUKfQ==\' | base64 -d > /config/verifyHash', 'cat <<\'EOF\' > /config/waitThenRun.sh', '#!/bin/bash', 'while true; do echo \"waiting for cloud libs install to complete\"', ' if [ -f /config/cloud/cloudLibsReady ]; then', ' break', ' else', ' sleep 10', ' fi', 'done', '\"$@\"', 'EOF', 'cat <<\'EOF\' > /config/cloud/gce/run_autoscale_update.sh', '#!/bin/bash', 'f5-rest-node /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/autoscale.js --cloud gce --provider-options \'storageBucket:' + storageName + ',mgmtPort:' + str(context.properties['manGuiPort']) + ',serviceAccount:' + context.properties['serviceAccount'] + ',instanceGroup:' + deployment + '-igm\' --host localhost --port 8443 --user cluster_admin --password-url file:///config/cloud/gce/.adminPassword --password-encrypted --device-group autoscale-group --cluster-action update --log-level silly --output /var/log/cloud/google/autoscale.log', 'EOF', 'cat <<\'EOF\' > /config/cloud/gce/run_autoscale_backup.sh', '#!/bin/bash', 'f5-rest-node /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/autoscale.js --cloud gce --provider-options \'storageBucket:' + storageName + ',mgmtPort:' + str(context.properties['manGuiPort']) + ',serviceAccount:' + context.properties['serviceAccount'] + ',instanceGroup:' + deployment + '-igm\' --host localhost --port 8443 --user cluster_admin --password-url file:///config/cloud/gce/.adminPassword --password-encrypted --device-group autoscale-group --cluster-action backup-ucs --log-level silly --output /var/log/cloud/google/autoscale.log', 'EOF', 'cat <<\'EOF\' > /config/cloud/gce/custom-config.sh', '#!/bin/bash', 'function wait_for_ready {', ' checks=0', ' ready_response=""', ' while [ $checks -lt 120 ] ; do', ' ready_response=$(curl -sku admin:$passwd -w "%{http_code}" -X GET https://localhost:${mgmtGuiPort}/mgmt/shared/appsvcs/info -o /dev/null)', ' if [[ $ready_response == *200 ]]; then', ' echo "AS3 is ready"', ' break', ' else', ' echo "AS3" is not ready: $checks, response: $ready_response', ' let checks=checks+1', ' sleep 5', ' fi', ' done', ' if [[ $ready_response != *200 ]]; then', ' error_exit "$LINENO: AS3 was not installed correctly. Exit."', ' fi', '}', 'date', 'echo "starting custom-config.sh"', 'tmsh save /sys config', 'echo "Attempting to Join or Initiate Autoscale Cluster"', '(crontab -l 2>/dev/null; echo \'*/1 * * * * /config/cloud/gce/run_autoscale_update.sh\') | crontab -', '(crontab -l 2>/dev/null; echo \'59 23 * * * /config/cloud/gce/run_autoscale_backup.sh\') | crontab -', 'f5-rest-node /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/autoscale.js --cloud gce --provider-options \'storageBucket:' + storageName + ',mgmtPort:' + str(context.properties['manGuiPort']) + ',serviceAccount:' + context.properties['serviceAccount'] + ',instanceGroup:' + deployment + '-igm\' --host localhost --port 8443 --user cluster_admin --password-url file:///config/cloud/gce/.adminPassword --password-encrypted --device-group autoscale-group --block-sync -c join --log-level silly -o /var/log/cloud/google/autoscale.log', 'if [ -f /config/cloud/master ];then', ' if $(jq \'.ucsLoaded\' < /config/cloud/master);then', ' echo "UCS backup loaded from backup folder in storage: ' + storageName + '."', ' else', ' echo "SELF-SELECTED as Primary ... Initiated Autoscale Cluster ... Loading default config"', ' tmsh modify cm device-group autoscale-group asm-sync enabled', ' source /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/waitForBigip.sh;wait-for-bigip', ' ', ' ### START CUSTOM CONFIGURATION: Policy Name/Policy URL, etc. ', ' applicationDnsName="' + str(context.properties['applicationDnsName']) + '"', ' applicationPort="' + str(context.properties['applicationPort']) + '"', ' asm_policy="/config/cloud/asm-policy-linux-' + context.properties['policyLevel'] + '.xml"', ' manGuiPort="' + str(context.properties['manGuiPort']) + '"', ' passwd=$(f5-rest-node /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/decryptDataFromFile.js --data-file /config/cloud/gce/.adminPassword)', ' deployed="no"', ' file_loc="/config/cloud/custom_config"', ' url_regex="(http:\/\/|https:\/\/)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$"', ' if [[ ' + str(context.properties['declarationUrl']) + ' =~ $url_regex ]]; then', ' response_code=$(/usr/bin/curl -sk -w "%{http_code}" ' + str(context.properties['declarationUrl']) + ' -o $file_loc)', ' if [[ $response_code == 200 ]]; then', ' echo "Custom config download complete; checking for valid JSON."', ' cat $file_loc | jq .class', ' if [[ $? == 0 ]]; then', ' wait_for_ready', ' response_code=$(/usr/bin/curl -skvvu cluster_admin:$passwd -w "%{http_code}" -X POST -H "Content-Type: application/json" -H "Expect:" https://localhost:${manGuiPort}/mgmt/shared/appsvcs/declare -d @$file_loc -o /dev/null)', ' if [[ $response_code == *200 || $response_code == *502 ]]; then', ' echo "Deployment of custom application succeeded."', ' deployed="yes"', ' else', ' echo "Failed to deploy custom application; continuing..."', ' fi', ' else', ' echo "Custom config was not valid JSON, continuing..."', ' fi', ' else', ' echo "Failed to download custom config; continuing..."', ' fi', ' else', ' echo "Custom config was not a URL, continuing..."', ' fi', ' if [[ $deployed == "no" && ' + str(context.properties['declarationUrl']) + ' == "default" ]]; then', ' payload=\'{"class":"ADC","schemaVersion":"3.0.0","label":"autoscale_waf","id":"AUTOSCALE_WAF","remark":"Autoscale WAF","waf":{"class":"Tenant","Shared":{"class":"Application","template":"shared","serviceAddress":{"class":"Service_Address","virtualAddress":"0.0.0.0"},"policyWAF":{"class":"WAF_Policy","file":"/tmp/as30-linux-medium.xml"}},"http":{"class":"Application","template":"http","serviceMain":{"class":"Service_HTTP","virtualAddresses":[{"use":"/waf/Shared/serviceAddress"}],"snat":"auto","securityLogProfiles":[{"bigip":"/Common/Log illegal requests"}],"pool":"pool","policyWAF":{"use":"/waf/Shared/policyWAF"}},"pool":{"class":"Pool","monitors":["http"],"members":[{"autoPopulate":true,"hostname":"demo.example.com","servicePort":80,"addressDiscovery":"gce","updateInterval":15,"tagKey":"applicationPoolTagKey","tagValue":"applicationPoolTagValue","addressRealm":"private","region":""}]}}}}\'', ' payload=$(echo $payload | jq -c --arg asm_policy $asm_policy --arg pool_http_port $applicationPort --arg vs_http_port $applicationPort \'.waf.Shared.policyWAF.file = $asm_policy | .waf.http.pool.members[0].servicePort = ($pool_http_port | tonumber) | .waf.http.serviceMain.virtualPort = ($vs_http_port | tonumber)\')', ' payload=$(echo $payload | jq -c \'del(.waf.http.pool.members[0].updateInterval) | del(.waf.http.pool.members[0].tagKey) | del(.waf.http.pool.members[0].tagValue) | del(.waf.http.pool.members[0].addressRealm) | del(.waf.http.pool.members[0].region)\')', ' payload=$(echo $payload | jq -c --arg pool_member $applicationDnsName \'.waf.http.pool.members[0].hostname = $pool_member | .waf.http.pool.members[0].addressDiscovery = "fqdn"\')', ' response_code=$(/usr/bin/curl -skvvu cluster_admin:$passwd -w "%{http_code}" -X POST -H "Content-Type: application/json" -H "Expect:" https://localhost:${manGuiPort}/mgmt/shared/appsvcs/declare -d "$payload" -o /dev/null)', ' if [[ $response_code == 200 || $response_code == 502 ]]; then', ' echo "Deployment of application succeeded."', ' else', ' echo "Failed to deploy application"', ' exit 1', ' fi', ' fi', ' ### END CUSTOM CONFIGURATION', ' tmsh save /sys config', ' bigstart restart restnoded', ' f5-rest-node /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/autoscale.js --cloud gce --provider-options \'storageBucket:' + storageName + ',mgmtPort:' + str(context.properties['manGuiPort']) + ',serviceAccount:' + context.properties['serviceAccount'] + ',instanceGroup:' + deployment + '-igm\' --host localhost --port 8443 --user cluster_admin --password-url file:///config/cloud/gce/.adminPassword --password-encrypted -c unblock-sync --log-level silly --output /var/log/cloud/google/autoscale.log', ' fi', 'fi', 'tmsh save /sys config', 'date', 'echo "custom-config.sh complete"', 'EOF', 'cat <<\'EOF\' > /config/cloud/gce/rm-password.sh', '#!/bin/bash', 'date', 'echo \'starting rm-password.sh\'', 'rm /config/cloud/gce/.adminPassword', 'date', 'EOF', 'checks=0', 'while [ $checks -lt 12 ]; do echo checking downloads directory', ' if [ -d "/var/config/rest/downloads" ]; then', ' echo downloads directory ready', ' break', ' fi', ' echo downloads directory not ready yet', ' let checks=checks+1', ' sleep 10', 'done', 'if [ ! -d "/var/config/rest/downloads" ]; then', ' mkdir -p /var/config/rest/downloads', 'fi', 'curl -s -f --retry 20 -o /config/cloud/f5-cloud-libs.tar.gz https://cdn.f5.com/product/cloudsolutions/f5-cloud-libs/v4.26.5/f5-cloud-libs.tar.gz', 'curl -s -f --retry 20 -o /config/cloud/f5-cloud-libs-gce.tar.gz https://cdn.f5.com/product/cloudsolutions/f5-cloud-libs-gce/v2.9.1/f5-cloud-libs-gce.tar.gz', 'curl -s -f --retry 20 -o /var/config/rest/downloads/f5-appsvcs-3.31.0-6.noarch.rpm https://cdn.f5.com/product/cloudsolutions/f5-appsvcs-extension/v3.31.0/f5-appsvcs-3.31.0-6.noarch.rpm', 'curl -s -f --retry 20 -o /config/cloud/asm-policy-linux.tar.gz http://cdn.f5.com/product/cloudsolutions/solution-scripts/asm-policy-linux.tar.gz', 'chmod 755 /config/verifyHash', 'chmod 755 /config/installCloudLibs.sh', 'chmod 755 /config/waitThenRun.sh', 'chmod 755 /config/cloud/gce/custom-config.sh', 'chmod 755 /config/cloud/gce/rm-password.sh', 'chmod 755 /config/cloud/gce/run_autoscale_update.sh', 'chmod 755 /config/cloud/gce/run_autoscale_backup.sh', 'mkdir -p /var/log/cloud/google', 'nohup /config/installCloudLibs.sh &>> /var/log/cloud/google/install.log < /dev/null &', 'nohup /config/waitThenRun.sh f5-rest-node /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/runScript.js --signal PASSWORD_CREATED --file f5-rest-node --cl-args \'/config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/generatePassword --file /config/cloud/gce/.adminPassword --encrypt\' --log-level silly -o /var/log/cloud/google/generatePassword.log &>> /var/log/cloud/google/install.log < /dev/null &', 'nohup /config/waitThenRun.sh f5-rest-node /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/runScript.js --wait-for PASSWORD_CREATED --signal ADMIN_CREATED --file /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/createUser.sh --cl-args \'--user cluster_admin --password-file /config/cloud/gce/.adminPassword --password-encrypted\' --log-level silly -o /var/log/cloud/google/createUser.log &>> /var/log/cloud/google/install.log < /dev/null &', CUSTHASH, 'nohup /config/waitThenRun.sh f5-rest-node /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/onboard.js --port 8443 --ssl-port ' + str(context.properties['manGuiPort']) + ' --wait-for ADMIN_CREATED -o /var/log/cloud/google/onboard.log --log-level silly --no-reboot --install-ilx-package file:///var/config/rest/downloads/f5-appsvcs-3.31.0-6.noarch.rpm --host localhost --user cluster_admin --password-url file:///config/cloud/gce/.adminPassword --password-encrypted --hostname $(curl http://metadata.google.internal/computeMetadata/v1/instance/hostname -H "Metadata-Flavor: Google") --ntp 0.us.pool.ntp.org --ntp 1.us.pool.ntp.org --tz UTC ' + '--modules ' + PROVISIONING_MODULES + ' --db provision.1nicautoconfig:disable' + SENDANALYTICS + ' &>> /var/log/cloud/google/install.log < /dev/null &', 'nohup /config/waitThenRun.sh f5-rest-node /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/runScript.js --file /config/cloud/gce/custom-config.sh --cwd /config/cloud/gce -o /var/log/cloud/google/custom-config.log --log-level silly --wait-for ONBOARD_DONE --signal CUSTOM_CONFIG_DONE &>> /var/log/cloud/google/install.log < /dev/null &', 'touch /config/startupFinished', ]) ) }] } return metadata def GenerateConfig(context): # set variables import random ## set variables storageNumber = str(random.randint(10000, 99999)) storageName = 'f5-bigip-' + context.env['deployment'] + '-' + storageNumber deployment = context.env['deployment'] # build resources resources = [ Storage(context,storageName), Instance(context,storageName,deployment), Igm(context,deployment), Autoscaler(context,deployment), HealthCheck(context,deployment), TargetPool(context,deployment), ForwardingRule(context,deployment), FirewallRuleSync(context), FirewallRuleApp(context), FirewallRuleMgmt(context), ] return {'resources': resources}
# Copyright 2021 F5 Networks All rights reserved. # # Version 3.14.0 """Creates BIG-IP""" COMPUTE_URL_BASE = 'https://www.googleapis.com/compute/v1/' def Storage(context,storageName): # Build storage container storage = { 'name': storageName, 'type': 'storage.v1.bucket', 'properties': { 'project': context.env['project'], 'name': storageName, } } return storage def Instance(context,storageName,deployment): # Build instance template instance = { 'name': 'bigip-' + deployment, 'type': 'compute.v1.instanceTemplate', 'properties': { 'properties': { 'canIpForward': True, 'tags': { 'items': ['mgmtfw-' + context.env['deployment'],'appfw-' + context.env['deployment'],'syncfw-' + context.env['deployment'],] }, 'labels': { 'f5_deployment': context.env['deployment'] }, 'machineType': context.properties['instanceType'], 'serviceAccounts': [{ 'email': context.properties['serviceAccount'], 'scopes': ['https://www.googleapis.com/auth/compute','https://www.googleapis.com/auth/devstorage.read_write','https://www.googleapis.com/auth/pubsub'] }], 'disks': [{ 'deviceName': 'boot', 'type': 'PERSISTENT', 'boot': True, 'autoDelete': True, 'initializeParams': { 'sourceImage': ''.join([COMPUTE_URL_BASE, 'projects/f5-7626-networks-public', '/global/images/', context.properties['imageName'], ]) } }], 'networkInterfaces': [{ 'network': ''.join([COMPUTE_URL_BASE, 'projects/', context.env['project'], '/global/networks/', context.properties['mgmtNetwork']]), 'subnetwork': ''.join([COMPUTE_URL_BASE, 'projects/', context.env['project'], '/regions/', context.properties['region'], '/subnetworks/', context.properties['mgmtSubnet']]), 'accessConfigs': [{ 'name': 'Management NAT', 'type': 'ONE_TO_ONE_NAT' }], }], 'metadata': Metadata(context,storageName,deployment) } } } return instance def Igm(context,deployment): # Build instance group manager igm = { 'name': deployment + '-igm', 'type': 'compute.v1.instanceGroupManager', 'properties': { 'baseInstanceName': deployment + '-bigip', 'instanceTemplate': ''.join(['$(ref.', 'bigip-' + deployment, '.selfLink)']), 'targetSize': int(context.properties['targetSize']), 'targetPools': ['$(ref.' + deployment + '-tp.selfLink)'], 'zone': context.properties['availabilityZone1'], } } return igm def Autoscaler(context,deployment): # Build autoscaler autoscaler = { 'name': deployment + 'big-ip-as', 'type': 'compute.v1.autoscalers', 'properties': { 'zone': context.properties['availabilityZone1'], 'target': '$(ref.' + deployment + '-igm.selfLink)', 'autoscalingPolicy': { "minNumReplicas": int(context.properties['minReplicas']), 'maxNumReplicas': int(context.properties['maxReplicas']), 'cpuUtilization': { 'utilizationTarget': float(context.properties['cpuUtilization']) }, 'coolDownPeriodSec': int(context.properties['coolDownPeriod']) } }, } return autoscaler def HealthCheck(context,deployment): # Build health autoscaler health check healthCheck = { 'name': deployment, 'type': 'compute.v1.httpHealthCheck', 'properties': { 'port': int(context.properties['applicationPort']), 'host': str(context.properties['applicationDnsName']), } } return healthCheck def TargetPool(context,deployment): # Build lb target pool targetPool = { 'name': deployment + '-tp', 'type': 'compute.v1.targetPool', 'properties': { 'region': context.properties['region'], 'healthChecks': ['$(ref.' + deployment + '.selfLink)'], 'sessionAffinity': 'CLIENT_IP', } } return targetPool def ForwardingRule(context,deployment): # Build forwarding rule forwardingRule = { 'name': deployment + '-fr', 'type': 'compute.v1.forwardingRule', 'properties': { 'region': context.properties['region'], 'IPProtocol': 'TCP', 'target': '$(ref.' + deployment + '-tp.selfLink)', 'loadBalancingScheme': 'EXTERNAL', } } return forwardingRule def FirewallRuleSync(context): # Build Sync traffic firewall rule firewallRuleSync = { 'name': 'syncfw-' + context.env['deployment'], 'type': 'compute.v1.firewall', 'properties': { 'network': ''.join([COMPUTE_URL_BASE, 'projects/', context.env['project'], '/global/networks/', context.properties['mgmtNetwork']]), 'targetTags': ['syncfw-'+ context.env['deployment']], 'sourceTags': ['syncfw-'+ context.env['deployment']], 'allowed': [{ 'IPProtocol': 'TCP', 'ports': ['4353'] },{ 'IPProtocol': 'UDP', 'ports': ['1026'], },{ "IPProtocol": "TCP", "ports": ['6123-6128'], }, ] } } return firewallRuleSync def FirewallRuleApp(context): # Build Application firewall rule firewallRuleApp = { 'name': 'appfw-' + context.env['deployment'], 'type': 'compute.v1.firewall', 'properties': { 'network': ''.join([COMPUTE_URL_BASE, 'projects/', context.env['project'], '/global/networks/', context.properties['mgmtNetwork']]), 'sourceRanges': ['0.0.0.0/0'], 'targetTags': ['appfw-'+ context.env['deployment']], 'allowed': [{ "IPProtocol": "TCP", "ports": [str(context.properties['applicationPort'])], }, ] } } return firewallRuleApp def FirewallRuleMgmt(context): # Build Management firewall rule firewallRuleMgmt = { 'name': 'mgmtfw-' + context.env['deployment'], 'type': 'compute.v1.firewall', 'properties': { 'network': ''.join([COMPUTE_URL_BASE, 'projects/', context.env['project'], '/global/networks/', context.properties['mgmtNetwork']]), 'sourceRanges': ['0.0.0.0/0'], 'targetTags': ['mgmtfw-'+ context.env['deployment']], 'allowed': [{ "IPProtocol": "TCP", "ports": ['8443','22'], }, ] } } return firewallRuleMgmt def Metadata(context,storageName,deployment): # Build metadata ALLOWUSAGEANALYTICS = str(context.properties['allowUsageAnalytics']) if ALLOWUSAGEANALYTICS == "yes": CUSTHASH = 'CUSTOMERID=`curl -s "http://metadata.google.internal/computeMetadata/v1/project/numeric-project-id" -H "Metadata-Flavor: Google" |sha512sum|cut -d " " -f 1`;\nDEPLOYMENTID=`curl -s "http://metadata.google.internal/computeMetadata/v1/instance/id" -H "Metadata-Flavor: Google"|sha512sum|cut -d " " -f 1`;' SENDANALYTICS = ' --metrics "cloudName:google,region:' + context.properties['region'] + ',bigipVersion:' + context.properties['imageName'] + ',customerId:${CUSTOMERID},deploymentId:${DEPLOYMENTID},templateName:f5-payg-autoscale-bigip-waf.py,templateVersion:3.14.0,licenseType:payg"' else: CUSTHASH = 'echo "No analytics."' SENDANALYTICS = '' # Provisioning modules PROVISIONING_MODULES = ','.join(context.properties['bigIpModules'].split('-')) ## generate metadata metadata = { 'items': [{ 'key': 'startup-script', 'value': ('\n'.join(['#!/bin/bash', 'if [ -f /config/startupFinished ]; then', ' exit', 'fi', 'mkdir -p /config/cloud/gce', 'cat <<\'EOF\' > /config/installCloudLibs.sh', '#!/bin/bash', 'echo about to execute', 'checks=0', 'while [ $checks -lt 120 ]; do echo checking mcpd', ' tmsh -a show sys mcp-state field-fmt | grep -q running', ' if [ $? == 0 ]; then', ' echo mcpd ready', ' break', ' fi', ' echo mcpd not ready yet', ' let checks=checks+1', ' sleep 10', 'done', 'echo loading verifyHash script', 'if ! tmsh load sys config merge file /config/verifyHash; then', ' echo cannot validate signature of /config/verifyHash', ' exit', 'fi', 'echo loaded verifyHash', 'declare -a filesToVerify=(\"/config/cloud/f5-cloud-libs.tar.gz\" \"/config/cloud/f5-cloud-libs-gce.tar.gz\" \"/var/config/rest/downloads/f5-appsvcs-3.31.0-6.noarch.rpm\")', 'for fileToVerify in \"${filesToVerify[@]}\"', 'do', ' echo verifying \"$fileToVerify\"', ' if ! tmsh run cli script verifyHash \"$fileToVerify\"; then', ' echo \"$fileToVerify\" is not valid', ' exit 1', ' fi', ' echo verified \"$fileToVerify\"', 'done', 'mkdir -p /config/cloud/gce/node_modules/@f5devcentral', 'echo expanding f5-cloud-libs.tar.gz', 'tar xvfz /config/cloud/f5-cloud-libs.tar.gz -C /config/cloud/gce/node_modules/@f5devcentral', 'echo expanding f5-cloud-libs-gce.tar.gz', 'tar xvfz /config/cloud/f5-cloud-libs-gce.tar.gz -C /config/cloud/gce/node_modules/@f5devcentral', 'echo "expanding waf policies"', 'tar xvfz /config/cloud/asm-policy-linux.tar.gz -C /config/cloud', 'echo cloud libs install complete', 'touch /config/cloud/cloudLibsReady', 'EOF', 'echo \'Y2xpIHNjcmlwdCAvQ29tbW9uL3ZlcmlmeUhhc2ggewpwcm9jIHNjcmlwdDo6cnVuIHt9IHsKICAgICAgICBpZiB7W2NhdGNoIHsKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS1jbG91ZC1saWJzLnRhci5neikgZThkOTYyZTI5NWE2MDY4NzMxMGI1MGNiZjEwODVjM2JjNjljNzZjMjk0MzljYmNlNjE0MWE1Njc3ZDg5ZmZhZGRlOWFhMWU3MzA4YTg1NDQ4NmFhYmE3OThjZTk4ZTM1YmQyNWZlYjlmY2M2ZDk0MDJhOWI3MmVjODc4NTYzNjEKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS1jbG91ZC1saWJzLWF3cy50YXIuZ3opIDA5MWVhN2IxOGFjYTdmMThhMGVjMzc3YTY4ODZkNWQ2NjZjYzgxMzQ5ZWFmYTU3MjVhYjA3NThkZGNjMTdjMTBlMDM3MzcxOTUzODRlYWZkNjNjMTE3ZDI1OTEzYzE1YTExMjg0ZDJjYzNiMjIxZDdiYTNjMzE0MjIxNzIxNDJiCiAgICAgICAgICAgIHNldCBoYXNoZXMoZjUtY2xvdWQtbGlicy1henVyZS50YXIuZ3opIGU3OTczYTFmZTg1YjVhODMyYzVlY2QxY2ZjZTY2YjQzYjg0ZTQyY2YyYTA2YjI3NTE3MzRmNzk4MTJkZTE4N2VlMWFkODczMGExMjljYjA4MTk4YTQ1MjE1N2M0NjZiYjg3MTgwYzE3ZGZkMmUwOWI0OWJlNmVmZTllOWE1N2ZlCiAgICAgICAgICAgIHNldCBoYXNoZXMoZjUtY2xvdWQtbGlicy1nY2UudGFyLmd6KSBjZDk1YTVjYzM2YzM5ZjgwZjk1NDc2YWQwMDBmN2RjYzIxYTlmZWY0MTRjOGVkYWM4MmJlMmU0OTFjMGZhOWViYTUxYjE0NWY3NWJhMGYzYzBkYWU0OGUxYzczMTQzMjIxN2IzYmI3MDBmNzFmZTE5MTIxNTJkYmU0MzllODk2NwogICAgICAgICAgICBzZXQgaGFzaGVzKGY1LWNsb3VkLWxpYnMtb3BlbnN0YWNrLnRhci5neikgNWM4M2ZlNmE5M2E2ZmNlYjVhMmU4NDM3YjVlZDhjYzlmYWY0YzE2MjFiZmM5ZTZhMDc3OWY2YzIxMzdiNDVlYWI4YWUwZTdlZDc0NWM4Y2Y4MjFiOTM3MTI0NWNhMjk3NDljYTBiN2U1NjYzOTQ5ZDc3NDk2Yjg3MjhmNGIwZjkKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS1jbG91ZC1saWJzLWNvbnN1bC50YXIuZ3opIGEzMmFhYjM5NzA3M2RmOTJjYmJiYTUwNjdlNTgyM2U5YjVmYWZjYTg2MmEyNThiNjBiNmI0MGFhMDk3NWMzOTg5ZDFlMTEwZjcwNjE3N2IyZmZiZTRkZGU2NTMwNWEyNjBhNTg1NjU5NGNlN2FkNGVmMGM0N2I2OTRhZTRhNTEzCiAgICAgICAgICAgIHNldCBoYXNoZXMoYXNtLXBvbGljeS1saW51eC50YXIuZ3opIDYzYjVjMmE1MWNhMDljNDNiZDg5YWYzNzczYmJhYjg3YzcxYTZlN2Y2YWQ5NDEwYjIyOWI0ZTBhMWM0ODNkNDZmMWE5ZmZmMzlkOTk0NDA0MWIwMmVlOTI2MDcyNDAyNzQxNGRlNTkyZTk5ZjRjMjQ3NTQxNTMyM2UxOGE3MmUwCiAgICAgICAgICAgIHNldCBoYXNoZXMoZjUuaHR0cC52MS4yLjByYzQudG1wbCkgNDdjMTlhODNlYmZjN2JkMWU5ZTljMzVmMzQyNDk0NWVmODY5NGFhNDM3ZWVkZDE3YjZhMzg3Nzg4ZDRkYjEzOTZmZWZlNDQ1MTk5YjQ5NzA2NGQ3Njk2N2IwZDUwMjM4MTU0MTkwY2EwYmQ3Mzk0MTI5OGZjMjU3ZGY0ZGMwMzQKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS5odHRwLnYxLjIuMHJjNi50bXBsKSA4MTFiMTRiZmZhYWI1ZWQwMzY1ZjAxMDZiYjVjZTVlNGVjMjIzODU2NTVlYTNhYzA0ZGUyYTM5YmQ5OTQ0ZjUxZTM3MTQ2MTlkYWU3Y2E0MzY2MmM5NTZiNTIxMjIyODg1OGYwNTkyNjcyYTI1NzlkNGE4Nzc2OTE4NmUyY2JmZQogICAgICAgICAgICBzZXQgaGFzaGVzKGY1Lmh0dHAudjEuMi4wcmM3LnRtcGwpIDIxZjQxMzM0MmU5YTdhMjgxYTBmMGUxMzAxZTc0NWFhODZhZjIxYTY5N2QyZTZmZGMyMWRkMjc5NzM0OTM2NjMxZTkyZjM0YmYxYzJkMjUwNGMyMDFmNTZjY2Q3NWM1YzEzYmFhMmZlNzY1MzIxMzY4OWVjM2M5ZTI3ZGZmNzdkCiAgICAgICAgICAgIHNldCBoYXNoZXMoZjUuYXdzX2FkdmFuY2VkX2hhLnYxLjMuMHJjMS50bXBsKSA5ZTU1MTQ5YzAxMGMxZDM5NWFiZGFlM2MzZDJjYjgzZWMxM2QzMWVkMzk0MjQ2OTVlODg2ODBjZjNlZDVhMDEzZDYyNmIzMjY3MTFkM2Q0MGVmMmRmNDZiNzJkNDE0YjRjYjhlNGY0NDVlYTA3MzhkY2JkMjVjNGM4NDNhYzM5ZAogICAgICAgICAgICBzZXQgaGFzaGVzKGY1LmF3c19hZHZhbmNlZF9oYS52MS40LjByYzEudG1wbCkgZGUwNjg0NTUyNTc0MTJhOTQ5ZjFlYWRjY2FlZTg1MDYzNDdlMDRmZDY5YmZiNjQ1MDAxYjc2ZjIwMDEyNzY2OGU0YTA2YmUyYmJiOTRlMTBmZWZjMjE1Y2ZjMzY2NWIwNzk0NWU2ZDczM2NiZTFhNGZhMWI4OGU4ODE1OTAzOTYKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS5hd3NfYWR2YW5jZWRfaGEudjEuNC4wcmMyLnRtcGwpIDZhYjBiZmZjNDI2ZGY3ZDMxOTEzZjlhNDc0YjFhMDc4NjA0MzVlMzY2YjA3ZDc3YjMyMDY0YWNmYjI5NTJjMWYyMDdiZWFlZDc3MDEzYTE1ZTQ0ZDgwZDc0ZjMyNTNlN2NmOWZiYmUxMmE5MGVjNzEyOGRlNmZhY2QwOTdkNjhmCiAgICAgICAgICAgIHNldCBoYXNoZXMoZjUuYXdzX2FkdmFuY2VkX2hhLnYxLjQuMHJjMy50bXBsKSAyZjIzMzliNGJjM2EyM2M5Y2ZkNDJhYWUyYTZkZTM5YmEwNjU4MzY2ZjI1OTg1ZGUyZWE1MzQxMGE3NDVmMGYxOGVlZGM0OTFiMjBmNGE4ZGJhOGRiNDg5NzAwOTZlMmVmZGNhN2I4ZWZmZmExYTgzYTc4ZTVhYWRmMjE4YjEzNAogICAgICAgICAgICBzZXQgaGFzaGVzKGY1LmF3c19hZHZhbmNlZF9oYS52MS40LjByYzQudG1wbCkgMjQxOGFjOGIxZjE4ODRjNWMwOTZjYmFjNmE5NGQ0MDU5YWFhZjA1OTI3YTZhNDUwOGZkMWYyNWI4Y2M2MDc3NDk4ODM5ZmJkZGE4MTc2ZDJjZjJkMjc0YTI3ZTZhMWRhZTJhMWUzYTBhOTk5MWJjNjVmYzc0ZmMwZDAyY2U5NjMKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS5hd3NfYWR2YW5jZWRfaGEudjEuNC4wcmM1LnRtcGwpIDVlNTgyMTg3YWUxYTYzMjNlMDk1ZDQxZWRkZDQxMTUxZDZiZDM4ZWI4M2M2MzQ0MTBkNDUyN2EzZDBlMjQ2YThmYzYyNjg1YWIwODQ5ZGUyYWRlNjJiMDI3NWY1MTI2NGQyZGVhY2NiYzE2Yjc3MzQxN2Y4NDdhNGExZWE5YmM0CiAgICAgICAgICAgIHNldCBoYXNoZXMoYXNtLXBvbGljeS50YXIuZ3opIDJkMzllYzYwZDAwNmQwNWQ4YTE1NjdhMWQ4YWFlNzIyNDE5ZThiMDYyYWQ3N2Q2ZDlhMzE2NTI5NzFlNWU2N2JjNDA0M2Q4MTY3MWJhMmE4YjEyZGQyMjllYTQ2ZDIwNTE0NGY3NTM3NGVkNGNhZTU4Y2VmYThmOWFiNjUzM2U2CiAgICAgICAgICAgIHNldCBoYXNoZXMoZGVwbG95X3dhZi5zaCkgMWEzYTNjNjI3NGFiMDhhN2RjMmNiNzNhZWRjOGQyYjJhMjNjZDllMGViMDZhMmUxNTM0YjM2MzJmMjUwZjFkODk3MDU2ZjIxOWQ1YjM1ZDNlZWQxMjA3MDI2ZTg5OTg5Zjc1NDg0MGZkOTI5NjljNTE1YWU0ZDgyOTIxNGZiNzQKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS5wb2xpY3lfY3JlYXRvci50bXBsKSAwNjUzOWUwOGQxMTVlZmFmZTU1YWE1MDdlY2I0ZTQ0M2U4M2JkYjFmNTgyNWE5NTE0OTU0ZWY2Y2E1NmQyNDBlZDAwYzdiNWQ2N2JkOGY2N2I4MTVlZTlkZDQ2NDUxOTg0NzAxZDA1OGM4OWRhZTI0MzRjODk3MTVkMzc1YTYyMAogICAgICAgICAgICBzZXQgaGFzaGVzKGY1LnNlcnZpY2VfZGlzY292ZXJ5LnRtcGwpIDQ4MTFhOTUzNzJkMWRiZGJiNGY2MmY4YmNjNDhkNGJjOTE5ZmE0OTJjZGEwMTJjODFlM2EyZmU2M2Q3OTY2Y2MzNmJhODY3N2VkMDQ5YTgxNGE5MzA0NzMyMzRmMzAwZDNmOGJjZWQyYjBkYjYzMTc2ZDUyYWM5OTY0MGNlODFiCiAgICAgICAgICAgIHNldCBoYXNoZXMoZjUuY2xvdWRfbG9nZ2VyLnYxLjAuMC50bXBsKSA2NGEwZWQzYjVlMzJhMDM3YmE0ZTcxZDQ2MDM4NWZlOGI1ZTFhZWNjMjdkYzBlODUxNGI1MTE4NjM5NTJlNDE5YTg5ZjRhMmE0MzMyNmFiYjU0M2JiYTliYzM0Mzc2YWZhMTE0Y2VkYTk1MGQyYzNiZDA4ZGFiNzM1ZmY1YWQyMAogICAgICAgICAgICBzZXQgaGFzaGVzKGY1LWFwcHN2Y3MtMy41LjEtNS5ub2FyY2gucnBtKSBiYTcxYzZlMWM1MmQwYzcwNzdjZGIyNWE1ODcwOWI4ZmI3YzM3YjM0NDE4YTgzMzhiYmY2NzY2ODMzOTY3NmQyMDhjMWE0ZmVmNGU1NDcwYzE1MmFhYzg0MDIwYjRjY2I4MDc0Y2UzODdkZTI0YmUzMzk3MTEyNTZjMGZhNzhjOAogICAgICAgICAgICBzZXQgaGFzaGVzKGY1LWFwcHN2Y3MtMy4xOC4wLTQubm9hcmNoLnJwbSkgZTcyZWU4MDA1YTI3MDcwYWMzOTlhYjA5N2U4YWE1MDdhNzJhYWU0NzIxZDc0OTE1ODljZmViODIxZGIzZWY4NmNiYzk3OWU3OTZhYjMxOWVjNzI3YmI1MTQwMGNjZGE4MTNjNGI5ZWI0YTZiM2QxMjIwYTM5NmI1ODJmOGY0MDAKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS1hcHBzdmNzLTMuMjAuMC0zLm5vYXJjaC5ycG0pIGQ0YmJhODg5MmEyMDY4YmI1M2Y4OGM2MDkwZGM2NWYxNzcwN2FiY2EzNWE3ZWQyZmZmMzk5ODAwNTdmZTdmN2EyZWJmNzEwYWIyMjg0YTFkODNkNzBiNzc0NmJlYWJhZDlkZjYwMzAxN2MwZmQ4NzI4Zjc0NTc2NjFjOTVhYzhkCiAgICAgICAgICAgIHNldCBoYXNoZXMoZjUtYXBwc3Zjcy0zLjI1LjAtMy5ub2FyY2gucnBtKSAyNmYxOWJkYWFhODFjYmUwNDIxYjNlMDhjMDk5ODdmOWRkMGM1NGIwNWE2MjZkNmEyMWE4MzZiMzQyNDhkMmQ5ZDgzMDk1ZjBkYWFkOGU3YTRhMDY4ZTllZjk5Yjg5ZmJjZDI0NmFlOGI2MTdhYzJiMjQ1NjU5OTE1N2QwZThiMwogICAgICAgICAgICBzZXQgaGFzaGVzKGY1LWFwcHN2Y3MtMy4yNi4xLTEubm9hcmNoLnJwbSkgYjQ2MGUxMTY3OWQzOGE5NjU0OWI1MDQxZGVmMjdiNDE5ZjFhNDFjOGY3ODhmOWY4YzdhMDM0YWE1Y2I1YThjOWZkMTUxYzdjNDM5YmViZDA5M2ZjZDg1Y2Q4NjU3ZjFjMDY0NTUxZDkzMzc1NjZmOWZjN2U5NTA2YzU1ZGMwMmMKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS1hcHBzdmNzLTMuMzEuMC02Lm5vYXJjaC5ycG0pIDY1MDZmZGU1ZDFjMmUwNjc2NjJiNTEzMzg3ZGNjZGEwMjgxZDNiYmM2MDRmYzZkY2Y4ZTU3NDBhZTU2Mzc0ODg5OWY3ZjMzNWUzNDkwMDZmZTNmMGU3NTFjZDcwZDRlZjhiZTM3MDFhZTQ1ZGNhMzA1ZGU2NDlmMjU5ZjA5MGE5CiAgICAgICAgICAgIHNldCBoYXNoZXMoZjUtY2xvdWQtZmFpbG92ZXItMS4xLjAtMC5ub2FyY2gucnBtKSAxNWE0NDBjMjk5ZjllNGFmODZhM2QwZjViMGQ3NWIwMDU0Mzg1Yjk1ZTQ3YzNlZjExNmQyZTBiZmIwMDQxYTI2ZGNiZjU0OTAyOGUyYTI2ZDJjNzE4ZWM2MTQ0NmJkNjU3YmUzOGZiYmNkOWRiNzgxZWZlNTQxNGMxNzRhYzY4YwogICAgICAgICAgICBzZXQgaGFzaGVzKGY1LWNsb3VkLWZhaWxvdmVyLTEuMy4wLTAubm9hcmNoLnJwbSkgMTk2ODFlYjMzZDlmOTEwYzkxM2Y4MTgwMTk5NDg1ZWI2NTNiNGI1ZWJlYWFlMGI5MGE2Y2U4MzQxZDdhMjJmZWQ4ZDIxODE1YjViYTE0OGM0Njg4NTJkMjBjYzI2ZmFkNGM0MjQyZTUwZWNjMTg0ZjFmODc3MGRhY2NlZDZmNmEKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS1jbG91ZC1mYWlsb3Zlci0xLjQuMC0wLm5vYXJjaC5ycG0pIDQ5ZTkxMDhhMDcwZTBjODcxM2FlYjdiMzMwNjYyMzU4NTQyZTYxYjdjNTNhOWQ0NTEwOGQzN2E5YmY1MjQ2ZjllNGFhYWUxMGNjNjEwNjQ4MDFkY2NjZDIwYmZkNTEwODM0N2IwZjY5NDUxMGU3ZWNlMDdmOTZjNDViYTY4M2IwCiAgICAgICAgICAgIHNldCBoYXNoZXMoZjUtY2xvdWQtZmFpbG92ZXItMS41LjAtMC5ub2FyY2gucnBtKSAzM2E3ZTJkMDQ3MTA2YmNjZTY4MTc1N2E2NTI0MGJmYWNlZGQ0OGUxMzU2N2UwNWZkYjIzYTRiMjY5ZDI2NmFhNTAwMWY4MTE1OGMzOTY0ZGMyOTdmMDQyOGRiMzFjOWRmNDI4MDAyODk4ZDE5MDI4NWIzNDljNTk0MjJhNTczYgogICAgICAgICAgICBzZXQgaGFzaGVzKGY1LWNsb3VkLWZhaWxvdmVyLTEuNi4xLTEubm9hcmNoLnJwbSkgYzFiODQyZGEyMWI4ZDFiYTIxYjZlYjYzYzg1OThhOWVhOTk4NmQ1ZGFkZGMyMWU0ZDI4MGUxZDZiMDlkM2RiMWRlOGFjN2RlNWM4NGVkZjA3YjQzZTRhZjAzZGFmOGZlNzQ3YTQwNDhmNjU3M2Q5NTUyMDYzNTJjZGUyY2VjNjUKICAgICAgICAgICAgc2V0IGhhc2hlcyhmNS1jbG91ZC1mYWlsb3Zlci0xLjcuMS0xLm5vYXJjaC5ycG0pIDE0ZmYwY2QyYmI0OTc4MGNjMGFlMzAyMWM0ZmM4ZmNjMDk2ZTNmY2UyMjU4MDk2YTRhYTAyNmQ2ZDM3ZGU3MjhjYTczNDViZmUzYTc5MDMxZTMzNmU3NGQyNWEyYjQwZmYyODMyNGMyYzc1MmJmMGVlNzFiN2ZjODliNmZjOGZlCiAgICAgICAgICAgIHNldCBoYXNoZXMoZjUtY2xvdWQtZmFpbG92ZXItMS44LjAtMC5ub2FyY2gucnBtKSAyMzA4NmQxY2JmM2NiMjRlYWM3ZWJhMjMwNTE1NmM2MDBmYTIxZjFiODk2MzIxYTJmYTUyMjVkMzMxZDdlNDE0NzFlZGIzZjUzNjgxNDRkODY4NDhhNDUyMGIxZTAwNWMwMTQ0ODVmZjQ1MWU3ZGE2NDI5MDUzZjU4YmZlOGNlNAogICAgICAgICAgICBzZXQgaGFzaGVzKGY1LWNsb3VkLWZhaWxvdmVyLTEuOS4wLTAubm9hcmNoLnJwbSkgMDljMTUzNzczODlhYzE4MzEzMzcwNjM1ZmI5OWY5YWZmMDU5NzA4MDdjYzYwYmZmMDc0ZjgwZjY2NDAyM2NmYzBkOWY1YjdmMmVkN2E4Zjg3OWRlYjJkYTg0YTAzNGJiOWZhOWY0ZTk1Zjk4MDZkNjQ0YWY1MThkYjMyZjE0MjUKCiAgICAgICAgICAgIHNldCBmaWxlX3BhdGggW2xpbmRleCAkdG1zaDo6YXJndiAxXQogICAgICAgICAgICBzZXQgZmlsZV9uYW1lIFtmaWxlIHRhaWwgJGZpbGVfcGF0aF0KCiAgICAgICAgICAgIGlmIHshW2luZm8gZXhpc3RzIGhhc2hlcygkZmlsZV9uYW1lKV19IHsKICAgICAgICAgICAgICAgIHRtc2g6OmxvZyBlcnIgIk5vIGhhc2ggZm91bmQgZm9yICRmaWxlX25hbWUiCiAgICAgICAgICAgICAgICBleGl0IDEKICAgICAgICAgICAgfQoKICAgICAgICAgICAgc2V0IGV4cGVjdGVkX2hhc2ggJGhhc2hlcygkZmlsZV9uYW1lKQogICAgICAgICAgICBzZXQgY29tcHV0ZWRfaGFzaCBbbGluZGV4IFtleGVjIC91c3IvYmluL29wZW5zc2wgZGdzdCAtciAtc2hhNTEyICRmaWxlX3BhdGhdIDBdCiAgICAgICAgICAgIGlmIHsgJGV4cGVjdGVkX2hhc2ggZXEgJGNvbXB1dGVkX2hhc2ggfSB7CiAgICAgICAgICAgICAgICBleGl0IDAKICAgICAgICAgICAgfQogICAgICAgICAgICB0bXNoOjpsb2cgZXJyICJIYXNoIGRvZXMgbm90IG1hdGNoIGZvciAkZmlsZV9wYXRoIgogICAgICAgICAgICBleGl0IDEKICAgICAgICB9XX0gewogICAgICAgICAgICB0bXNoOjpsb2cgZXJyIHtVbmV4cGVjdGVkIGVycm9yIGluIHZlcmlmeUhhc2h9CiAgICAgICAgICAgIGV4aXQgMQogICAgICAgIH0KICAgIH0KICAgIHNjcmlwdC1zaWduYXR1cmUgaWpMY1dkbHdpNG5mdklINC9qUEZKMVk5WGtvZEtWZHVxN0VGV2plV2sweHdmTjVyVkxrQnNodVJPRkpOdG9uV2w1dXYyS1pHMFNUVDhHY0UvRGk5NnVoNlVWakRKQzBnSHdIcUVGa2pkTzNVRXFQd28wOVJRM2xsaVdyb0YzeGFrazlWUTlSdFNBSCtYUXJGNTlNbUFVRGtTT3llVC9DdUY3QXBKNFdFcmNiWnJzeGlhM1RpUkdCZFVXbXowL1hDZlc0L2ZhRUJHVEFUNkFOdzBhTFZxd2tjZ2pxWS9Ld01xWFlITE5VdmtRYm9KQmZtWVVOQXVnM1ozMjlqN1FTZENCbG9wQk9kcG1aM1JxNURPQm15OXpRd2Ewd205MTF6WDEySUpsaUdGUUwwYW1UTSt3ZTFoSENXRFd0ZDVpQ05rd2lldGtzQlhSNkozMWVpZ0M1U2dBPT0KICAgIHNpZ25pbmcta2V5IC9Db21tb24vZjUtaXJ1bGUKfQ==\' | base64 -d > /config/verifyHash', 'cat <<\'EOF\' > /config/waitThenRun.sh', '#!/bin/bash', 'while true; do echo \"waiting for cloud libs install to complete\"', ' if [ -f /config/cloud/cloudLibsReady ]; then', ' break', ' else', ' sleep 10', ' fi', 'done', '\"$@\"', 'EOF', 'cat <<\'EOF\' > /config/cloud/gce/run_autoscale_update.sh', '#!/bin/bash', 'f5-rest-node /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/autoscale.js --cloud gce --provider-options \'storageBucket:' + storageName + ',mgmtPort:' + str(context.properties['manGuiPort']) + ',serviceAccount:' + context.properties['serviceAccount'] + ',instanceGroup:' + deployment + '-igm\' --host localhost --port 8443 --user cluster_admin --password-url file:///config/cloud/gce/.adminPassword --password-encrypted --device-group autoscale-group --cluster-action update --log-level silly --output /var/log/cloud/google/autoscale.log', 'EOF', 'cat <<\'EOF\' > /config/cloud/gce/run_autoscale_backup.sh', '#!/bin/bash', 'f5-rest-node /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/autoscale.js --cloud gce --provider-options \'storageBucket:' + storageName + ',mgmtPort:' + str(context.properties['manGuiPort']) + ',serviceAccount:' + context.properties['serviceAccount'] + ',instanceGroup:' + deployment + '-igm\' --host localhost --port 8443 --user cluster_admin --password-url file:///config/cloud/gce/.adminPassword --password-encrypted --device-group autoscale-group --cluster-action backup-ucs --log-level silly --output /var/log/cloud/google/autoscale.log', 'EOF', 'cat <<\'EOF\' > /config/cloud/gce/custom-config.sh', '#!/bin/bash', 'function wait_for_ready {', ' checks=0', ' ready_response=""', ' while [ $checks -lt 120 ] ; do', ' ready_response=$(curl -sku admin:$passwd -w "%{http_code}" -X GET https://localhost:${mgmtGuiPort}/mgmt/shared/appsvcs/info -o /dev/null)', ' if [[ $ready_response == *200 ]]; then', ' echo "AS3 is ready"', ' break', ' else', ' echo "AS3" is not ready: $checks, response: $ready_response', ' let checks=checks+1', ' sleep 5', ' fi', ' done', ' if [[ $ready_response != *200 ]]; then', ' error_exit "$LINENO: AS3 was not installed correctly. Exit."', ' fi', '}', 'date', 'echo "starting custom-config.sh"', 'tmsh save /sys config', 'echo "Attempting to Join or Initiate Autoscale Cluster"', '(crontab -l 2>/dev/null; echo \'*/1 * * * * /config/cloud/gce/run_autoscale_update.sh\') | crontab -', '(crontab -l 2>/dev/null; echo \'59 23 * * * /config/cloud/gce/run_autoscale_backup.sh\') | crontab -', 'f5-rest-node /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/autoscale.js --cloud gce --provider-options \'storageBucket:' + storageName + ',mgmtPort:' + str(context.properties['manGuiPort']) + ',serviceAccount:' + context.properties['serviceAccount'] + ',instanceGroup:' + deployment + '-igm\' --host localhost --port 8443 --user cluster_admin --password-url file:///config/cloud/gce/.adminPassword --password-encrypted --device-group autoscale-group --block-sync -c join --log-level silly -o /var/log/cloud/google/autoscale.log', 'if [ -f /config/cloud/master ];then', ' if $(jq \'.ucsLoaded\' < /config/cloud/master);then', ' echo "UCS backup loaded from backup folder in storage: ' + storageName + '."', ' else', ' echo "SELF-SELECTED as Primary ... Initiated Autoscale Cluster ... Loading default config"', ' tmsh modify cm device-group autoscale-group asm-sync enabled', ' source /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/waitForBigip.sh;wait-for-bigip', ' ', ' ### START CUSTOM CONFIGURATION: Policy Name/Policy URL, etc. ', ' applicationDnsName="' + str(context.properties['applicationDnsName']) + '"', ' applicationPort="' + str(context.properties['applicationPort']) + '"', ' asm_policy="/config/cloud/asm-policy-linux-' + context.properties['policyLevel'] + '.xml"', ' manGuiPort="' + str(context.properties['manGuiPort']) + '"', ' passwd=$(f5-rest-node /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/decryptDataFromFile.js --data-file /config/cloud/gce/.adminPassword)', ' deployed="no"', ' file_loc="/config/cloud/custom_config"', ' url_regex="(http:\/\/|https:\/\/)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$"', ' if [[ ' + str(context.properties['declarationUrl']) + ' =~ $url_regex ]]; then', ' response_code=$(/usr/bin/curl -sk -w "%{http_code}" ' + str(context.properties['declarationUrl']) + ' -o $file_loc)', ' if [[ $response_code == 200 ]]; then', ' echo "Custom config download complete; checking for valid JSON."', ' cat $file_loc | jq .class', ' if [[ $? == 0 ]]; then', ' wait_for_ready', ' response_code=$(/usr/bin/curl -skvvu cluster_admin:$passwd -w "%{http_code}" -X POST -H "Content-Type: application/json" -H "Expect:" https://localhost:${manGuiPort}/mgmt/shared/appsvcs/declare -d @$file_loc -o /dev/null)', ' if [[ $response_code == *200 || $response_code == *502 ]]; then', ' echo "Deployment of custom application succeeded."', ' deployed="yes"', ' else', ' echo "Failed to deploy custom application; continuing..."', ' fi', ' else', ' echo "Custom config was not valid JSON, continuing..."', ' fi', ' else', ' echo "Failed to download custom config; continuing..."', ' fi', ' else', ' echo "Custom config was not a URL, continuing..."', ' fi', ' if [[ $deployed == "no" && ' + str(context.properties['declarationUrl']) + ' == "default" ]]; then', ' payload=\'{"class":"ADC","schemaVersion":"3.0.0","label":"autoscale_waf","id":"AUTOSCALE_WAF","remark":"Autoscale WAF","waf":{"class":"Tenant","Shared":{"class":"Application","template":"shared","serviceAddress":{"class":"Service_Address","virtualAddress":"0.0.0.0"},"policyWAF":{"class":"WAF_Policy","file":"/tmp/as30-linux-medium.xml"}},"http":{"class":"Application","template":"http","serviceMain":{"class":"Service_HTTP","virtualAddresses":[{"use":"/waf/Shared/serviceAddress"}],"snat":"auto","securityLogProfiles":[{"bigip":"/Common/Log illegal requests"}],"pool":"pool","policyWAF":{"use":"/waf/Shared/policyWAF"}},"pool":{"class":"Pool","monitors":["http"],"members":[{"autoPopulate":true,"hostname":"demo.example.com","servicePort":80,"addressDiscovery":"gce","updateInterval":15,"tagKey":"applicationPoolTagKey","tagValue":"applicationPoolTagValue","addressRealm":"private","region":""}]}}}}\'', ' payload=$(echo $payload | jq -c --arg asm_policy $asm_policy --arg pool_http_port $applicationPort --arg vs_http_port $applicationPort \'.waf.Shared.policyWAF.file = $asm_policy | .waf.http.pool.members[0].servicePort = ($pool_http_port | tonumber) | .waf.http.serviceMain.virtualPort = ($vs_http_port | tonumber)\')', ' payload=$(echo $payload | jq -c \'del(.waf.http.pool.members[0].updateInterval) | del(.waf.http.pool.members[0].tagKey) | del(.waf.http.pool.members[0].tagValue) | del(.waf.http.pool.members[0].addressRealm) | del(.waf.http.pool.members[0].region)\')', ' payload=$(echo $payload | jq -c --arg pool_member $applicationDnsName \'.waf.http.pool.members[0].hostname = $pool_member | .waf.http.pool.members[0].addressDiscovery = "fqdn"\')', ' response_code=$(/usr/bin/curl -skvvu cluster_admin:$passwd -w "%{http_code}" -X POST -H "Content-Type: application/json" -H "Expect:" https://localhost:${manGuiPort}/mgmt/shared/appsvcs/declare -d "$payload" -o /dev/null)', ' if [[ $response_code == 200 || $response_code == 502 ]]; then', ' echo "Deployment of application succeeded."', ' else', ' echo "Failed to deploy application"', ' exit 1', ' fi', ' fi', ' ### END CUSTOM CONFIGURATION', ' tmsh save /sys config', ' bigstart restart restnoded', ' f5-rest-node /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/autoscale.js --cloud gce --provider-options \'storageBucket:' + storageName + ',mgmtPort:' + str(context.properties['manGuiPort']) + ',serviceAccount:' + context.properties['serviceAccount'] + ',instanceGroup:' + deployment + '-igm\' --host localhost --port 8443 --user cluster_admin --password-url file:///config/cloud/gce/.adminPassword --password-encrypted -c unblock-sync --log-level silly --output /var/log/cloud/google/autoscale.log', ' fi', 'fi', 'tmsh save /sys config', 'date', 'echo "custom-config.sh complete"', 'EOF', 'cat <<\'EOF\' > /config/cloud/gce/rm-password.sh', '#!/bin/bash', 'date', 'echo \'starting rm-password.sh\'', 'rm /config/cloud/gce/.adminPassword', 'date', 'EOF', 'checks=0', 'while [ $checks -lt 12 ]; do echo checking downloads directory', ' if [ -d "/var/config/rest/downloads" ]; then', ' echo downloads directory ready', ' break', ' fi', ' echo downloads directory not ready yet', ' let checks=checks+1', ' sleep 10', 'done', 'if [ ! -d "/var/config/rest/downloads" ]; then', ' mkdir -p /var/config/rest/downloads', 'fi', 'curl -s -f --retry 20 -o /config/cloud/f5-cloud-libs.tar.gz https://cdn.f5.com/product/cloudsolutions/f5-cloud-libs/v4.26.5/f5-cloud-libs.tar.gz', 'curl -s -f --retry 20 -o /config/cloud/f5-cloud-libs-gce.tar.gz https://cdn.f5.com/product/cloudsolutions/f5-cloud-libs-gce/v2.9.1/f5-cloud-libs-gce.tar.gz', 'curl -s -f --retry 20 -o /var/config/rest/downloads/f5-appsvcs-3.31.0-6.noarch.rpm https://cdn.f5.com/product/cloudsolutions/f5-appsvcs-extension/v3.31.0/f5-appsvcs-3.31.0-6.noarch.rpm', 'curl -s -f --retry 20 -o /config/cloud/asm-policy-linux.tar.gz http://cdn.f5.com/product/cloudsolutions/solution-scripts/asm-policy-linux.tar.gz', 'chmod 755 /config/verifyHash', 'chmod 755 /config/installCloudLibs.sh', 'chmod 755 /config/waitThenRun.sh', 'chmod 755 /config/cloud/gce/custom-config.sh', 'chmod 755 /config/cloud/gce/rm-password.sh', 'chmod 755 /config/cloud/gce/run_autoscale_update.sh', 'chmod 755 /config/cloud/gce/run_autoscale_backup.sh', 'mkdir -p /var/log/cloud/google', 'nohup /config/installCloudLibs.sh &>> /var/log/cloud/google/install.log < /dev/null &', 'nohup /config/waitThenRun.sh f5-rest-node /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/runScript.js --signal PASSWORD_CREATED --file f5-rest-node --cl-args \'/config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/generatePassword --file /config/cloud/gce/.adminPassword --encrypt\' --log-level silly -o /var/log/cloud/google/generatePassword.log &>> /var/log/cloud/google/install.log < /dev/null &', 'nohup /config/waitThenRun.sh f5-rest-node /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/runScript.js --wait-for PASSWORD_CREATED --signal ADMIN_CREATED --file /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/createUser.sh --cl-args \'--user cluster_admin --password-file /config/cloud/gce/.adminPassword --password-encrypted\' --log-level silly -o /var/log/cloud/google/createUser.log &>> /var/log/cloud/google/install.log < /dev/null &', CUSTHASH, 'nohup /config/waitThenRun.sh f5-rest-node /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/onboard.js --port 8443 --ssl-port ' + str(context.properties['manGuiPort']) + ' --wait-for ADMIN_CREATED -o /var/log/cloud/google/onboard.log --log-level silly --no-reboot --install-ilx-package file:///var/config/rest/downloads/f5-appsvcs-3.31.0-6.noarch.rpm --host localhost --user cluster_admin --password-url file:///config/cloud/gce/.adminPassword --password-encrypted --hostname $(curl http://metadata.google.internal/computeMetadata/v1/instance/hostname -H "Metadata-Flavor: Google") --ntp 0.us.pool.ntp.org --ntp 1.us.pool.ntp.org --tz UTC ' + '--modules ' + PROVISIONING_MODULES + ' --db provision.1nicautoconfig:disable' + SENDANALYTICS + ' &>> /var/log/cloud/google/install.log < /dev/null &', 'nohup /config/waitThenRun.sh f5-rest-node /config/cloud/gce/node_modules/@f5devcentral/f5-cloud-libs/scripts/runScript.js --file /config/cloud/gce/custom-config.sh --cwd /config/cloud/gce -o /var/log/cloud/google/custom-config.log --log-level silly --wait-for ONBOARD_DONE --signal CUSTOM_CONFIG_DONE &>> /var/log/cloud/google/install.log < /dev/null &', 'touch /config/startupFinished', ]) ) }] } return metadata def GenerateConfig(context): # set variables import random ## set variables storageNumber = str(random.randint(10000, 99999)) storageName = 'f5-bigip-' + context.env['deployment'] + '-' + storageNumber deployment = context.env['deployment'] # build resources resources = [ Storage(context,storageName), Instance(context,storageName,deployment), Igm(context,deployment), Autoscaler(context,deployment), HealthCheck(context,deployment), TargetPool(context,deployment), ForwardingRule(context,deployment), FirewallRuleSync(context), FirewallRuleApp(context), FirewallRuleMgmt(context), ] return {'resources': resources}
#!/usr/bin/env python3 """Release script for ODL projects""" import re import os from subprocess import CalledProcessError from pkg_resources import parse_version from async_subprocess import ( call, check_call, check_output, ) from constants import ( GIT_RELEASE_NOTES_PATH, SCRIPT_DIR, YARN_PATH, ) from exception import ( DependencyException, ReleaseException, ) from github import create_pr from lib import ( get_default_branch, init_working_dir, ) from version import update_version async def dependency_exists(command): """Returns true if a command exists on the system""" return await call(["which", command], cwd="/") == 0 async def validate_dependencies(): """Error if a dependency is missing or invalid""" if not await dependency_exists("git"): raise DependencyException("Please install git https://git-scm.com/downloads") if not await dependency_exists("node"): raise DependencyException("Please install node.js https://nodejs.org/") if not await dependency_exists( GIT_RELEASE_NOTES_PATH ) or not await dependency_exists(YARN_PATH): raise DependencyException("Please run 'npm install' first") version_output = await check_output(["node", "--version"], cwd="/") version = version_output.decode() major_version = int(re.match(r"^v(\d+)\.", version).group(1)) if major_version < 6: raise DependencyException("node.js must be version 6.x or higher") async def any_new_commits(version, *, base_branch, root): """ Return true if there are any new commits since a release Args: version (str): A version string base_branch (str): The branch to compare against root (str): The project root directory Returns: bool: True if there are new commits """ return await any_commits_between_branches( branch1=f"v{version}", branch2=base_branch, root=root ) async def any_commits_between_branches(*, branch1, branch2, root): """ Return true if there are any commits between two branches Args: branch1 (str): The first branch to compare against branch2 (str): The second, more recent branch to compare against root (str): The project root directory Returns: bool: True if there are new commits """ output = await check_output( ["git", "rev-list", "--count", f"{branch1}..{branch2}", "--"], cwd=root ) return int(output) != 0 async def create_release_notes(old_version, with_checkboxes, *, base_branch, root): """ Returns the release note text for the commits made for this version Args: old_version (str): The starting version of the range of commits with_checkboxes (bool): If true, create the release notes with spaces for checkboxes base_branch (str): The base branch to compare against root (str): The project root directory Returns: str: The release notes """ if with_checkboxes: filename = "release_notes.ejs" else: filename = "release_notes_rst.ejs" if not await any_new_commits(old_version, base_branch=base_branch, root=root): return "No new commits" output = await check_output( [ GIT_RELEASE_NOTES_PATH, f"v{old_version}..{base_branch}", os.path.join(SCRIPT_DIR, "util", filename), ], cwd=root, ) return f"{output.decode().strip()}\n" async def verify_new_commits(old_version, *, base_branch, root): """Check if there are new commits to release""" if not await any_new_commits(old_version, base_branch=base_branch, root=root): raise ReleaseException("No new commits to put in release") async def update_release_notes(old_version, new_version, *, base_branch, root): """Updates RELEASE.rst and commits it""" release_notes = await create_release_notes( old_version, with_checkboxes=False, base_branch=base_branch, root=root ) release_filename = os.path.join(root, "RELEASE.rst") try: with open(release_filename, "r", encoding="utf-8") as f: existing_note_lines = f.readlines() except FileNotFoundError: existing_note_lines = [] with open(release_filename, "w", encoding="utf-8") as f: f.write("Release Notes\n") f.write("=============\n") f.write("\n") version_line = f"Version {new_version}" f.write(f"{version_line}\n") f.write(f"{"-" * len(version_line)}\n") f.write("\n") f.write(release_notes) f.write("\n") # skip first four lines which contain the header we are replacing for old_line in existing_note_lines[3:]: f.write(old_line) await check_call(["git", "add", release_filename], cwd=root) await check_call( ["git", "commit", "-q", "--all", "--message", f"Release {new_version}"], cwd=root, ) async def build_release(*, root): """Deploy the release candidate""" await check_call( [ "git", "push", "--force", "-q", "origin", "release-candidate:release-candidate", ], cwd=root, ) async def generate_release_pr( *, github_access_token, repo_url, old_version, new_version, base_branch, root ): """ Make a release pull request for the deployed release-candidate branch Args: github_access_token (str): The github access token repo_url (str): URL for the repo old_version (str): The previous release version new_version (str): The version of the new release base_branch (str): The base branch to compare against root (str): The project root directory """ await create_pr( github_access_token=github_access_token, repo_url=repo_url, title=f"Release {new_version}", body=await create_release_notes( old_version, with_checkboxes=True, base_branch=base_branch, root=root ), head="release-candidate", base="release", ) async def release( *, github_access_token, repo_info, new_version, branch=None, commit_hash=None ): """ Run a release Args: github_access_token (str): The github access token repo_info (RepoInfo): RepoInfo for a repo new_version (str): The version of the new release branch (str): The branch to initialize the release from commit_hash (str): Commit hash to cherry pick in case of a hot fix """ await validate_dependencies() async with init_working_dir( github_access_token, repo_info.repo_url, branch=branch ) as working_dir: default_branch = await get_default_branch(working_dir) await check_call( ["git", "checkout", "-qb", "release-candidate"], cwd=working_dir ) if commit_hash: try: await check_call(["git", "cherry-pick", commit_hash], cwd=working_dir) except CalledProcessError as ex: raise ReleaseException( f"Cherry pick failed for the given hash {commit_hash}" ) from ex old_version = await update_version( repo_info=repo_info, new_version=new_version, working_dir=working_dir, readonly=False, ) if parse_version(old_version) >= parse_version(new_version): raise ReleaseException( f"old version is {old_version} but the new version {new_version} is not newer" ) base_branch = "release-candidate" if commit_hash else default_branch await verify_new_commits(old_version, base_branch=base_branch, root=working_dir) await update_release_notes( old_version, new_version, base_branch=base_branch, root=working_dir ) await build_release(root=working_dir) return await generate_release_pr( github_access_token=github_access_token, repo_url=repo_info.repo_url, old_version=old_version, new_version=new_version, base_branch=base_branch, root=working_dir, )
#!/usr/bin/env python3 """Release script for ODL projects""" import re import os from subprocess import CalledProcessError from pkg_resources import parse_version from async_subprocess import ( call, check_call, check_output, ) from constants import ( GIT_RELEASE_NOTES_PATH, SCRIPT_DIR, YARN_PATH, ) from exception import ( DependencyException, ReleaseException, ) from github import create_pr from lib import ( get_default_branch, init_working_dir, ) from version import update_version async def dependency_exists(command): """Returns true if a command exists on the system""" return await call(["which", command], cwd="/") == 0 async def validate_dependencies(): """Error if a dependency is missing or invalid""" if not await dependency_exists("git"): raise DependencyException("Please install git https://git-scm.com/downloads") if not await dependency_exists("node"): raise DependencyException("Please install node.js https://nodejs.org/") if not await dependency_exists( GIT_RELEASE_NOTES_PATH ) or not await dependency_exists(YARN_PATH): raise DependencyException("Please run 'npm install' first") version_output = await check_output(["node", "--version"], cwd="/") version = version_output.decode() major_version = int(re.match(r"^v(\d+)\.", version).group(1)) if major_version < 6: raise DependencyException("node.js must be version 6.x or higher") async def any_new_commits(version, *, base_branch, root): """ Return true if there are any new commits since a release Args: version (str): A version string base_branch (str): The branch to compare against root (str): The project root directory Returns: bool: True if there are new commits """ return await any_commits_between_branches( branch1=f"v{version}", branch2=base_branch, root=root ) async def any_commits_between_branches(*, branch1, branch2, root): """ Return true if there are any commits between two branches Args: branch1 (str): The first branch to compare against branch2 (str): The second, more recent branch to compare against root (str): The project root directory Returns: bool: True if there are new commits """ output = await check_output( ["git", "rev-list", "--count", f"{branch1}..{branch2}", "--"], cwd=root ) return int(output) != 0 async def create_release_notes(old_version, with_checkboxes, *, base_branch, root): """ Returns the release note text for the commits made for this version Args: old_version (str): The starting version of the range of commits with_checkboxes (bool): If true, create the release notes with spaces for checkboxes base_branch (str): The base branch to compare against root (str): The project root directory Returns: str: The release notes """ if with_checkboxes: filename = "release_notes.ejs" else: filename = "release_notes_rst.ejs" if not await any_new_commits(old_version, base_branch=base_branch, root=root): return "No new commits" output = await check_output( [ GIT_RELEASE_NOTES_PATH, f"v{old_version}..{base_branch}", os.path.join(SCRIPT_DIR, "util", filename), ], cwd=root, ) return f"{output.decode().strip()}\n" async def verify_new_commits(old_version, *, base_branch, root): """Check if there are new commits to release""" if not await any_new_commits(old_version, base_branch=base_branch, root=root): raise ReleaseException("No new commits to put in release") async def update_release_notes(old_version, new_version, *, base_branch, root): """Updates RELEASE.rst and commits it""" release_notes = await create_release_notes( old_version, with_checkboxes=False, base_branch=base_branch, root=root ) release_filename = os.path.join(root, "RELEASE.rst") try: with open(release_filename, "r", encoding="utf-8") as f: existing_note_lines = f.readlines() except FileNotFoundError: existing_note_lines = [] with open(release_filename, "w", encoding="utf-8") as f: f.write("Release Notes\n") f.write("=============\n") f.write("\n") version_line = f"Version {new_version}" f.write(f"{version_line}\n") f.write(f"{'-' * len(version_line)}\n") f.write("\n") f.write(release_notes) f.write("\n") # skip first four lines which contain the header we are replacing for old_line in existing_note_lines[3:]: f.write(old_line) await check_call(["git", "add", release_filename], cwd=root) await check_call( ["git", "commit", "-q", "--all", "--message", f"Release {new_version}"], cwd=root, ) async def build_release(*, root): """Deploy the release candidate""" await check_call( [ "git", "push", "--force", "-q", "origin", "release-candidate:release-candidate", ], cwd=root, ) async def generate_release_pr( *, github_access_token, repo_url, old_version, new_version, base_branch, root ): """ Make a release pull request for the deployed release-candidate branch Args: github_access_token (str): The github access token repo_url (str): URL for the repo old_version (str): The previous release version new_version (str): The version of the new release base_branch (str): The base branch to compare against root (str): The project root directory """ await create_pr( github_access_token=github_access_token, repo_url=repo_url, title=f"Release {new_version}", body=await create_release_notes( old_version, with_checkboxes=True, base_branch=base_branch, root=root ), head="release-candidate", base="release", ) async def release( *, github_access_token, repo_info, new_version, branch=None, commit_hash=None ): """ Run a release Args: github_access_token (str): The github access token repo_info (RepoInfo): RepoInfo for a repo new_version (str): The version of the new release branch (str): The branch to initialize the release from commit_hash (str): Commit hash to cherry pick in case of a hot fix """ await validate_dependencies() async with init_working_dir( github_access_token, repo_info.repo_url, branch=branch ) as working_dir: default_branch = await get_default_branch(working_dir) await check_call( ["git", "checkout", "-qb", "release-candidate"], cwd=working_dir ) if commit_hash: try: await check_call(["git", "cherry-pick", commit_hash], cwd=working_dir) except CalledProcessError as ex: raise ReleaseException( f"Cherry pick failed for the given hash {commit_hash}" ) from ex old_version = await update_version( repo_info=repo_info, new_version=new_version, working_dir=working_dir, readonly=False, ) if parse_version(old_version) >= parse_version(new_version): raise ReleaseException( f"old version is {old_version} but the new version {new_version} is not newer" ) base_branch = "release-candidate" if commit_hash else default_branch await verify_new_commits(old_version, base_branch=base_branch, root=working_dir) await update_release_notes( old_version, new_version, base_branch=base_branch, root=working_dir ) await build_release(root=working_dir) return await generate_release_pr( github_access_token=github_access_token, repo_url=repo_info.repo_url, old_version=old_version, new_version=new_version, base_branch=base_branch, root=working_dir, )
import os import shutil from pathlib import Path from typing import Any, Dict, List, Optional, Tuple import yaml from chia import __version__ from chia.consensus.coinbase import create_puzzlehash_for_pk from chia.ssl.create_ssl import generate_ca_signed_cert, get_chia_ca_crt_key, make_ca_cert from chia.util.bech32m import encode_puzzle_hash from chia.util.config import ( create_default_chia_config, initial_config_file, load_config, save_config, unflatten_properties, ) from chia.util.ints import uint32 from chia.util.keychain import Keychain from chia.util.path import mkdir from chia.wallet.derive_keys import master_sk_to_pool_sk, master_sk_to_wallet_sk private_node_names = {"full_node", "wallet", "farmer", "harvester", "timelord", "daemon"} public_node_names = {"full_node", "wallet", "farmer", "introducer", "timelord"} def dict_add_new_default(updated: Dict, default: Dict, do_not_migrate_keys: Dict[str, Any]): for k in do_not_migrate_keys: if k in updated and do_not_migrate_keys[k] == "": updated.pop(k) for k, v in default.items(): ignore = False if k in do_not_migrate_keys: do_not_data = do_not_migrate_keys[k] if isinstance(do_not_data, dict): ignore = False else: ignore = True if isinstance(v, dict) and k in updated and ignore is False: # If there is an intermediate key with empty string value, do not migrate all descendants if do_not_migrate_keys.get(k, None) == "": do_not_migrate_keys[k] = v dict_add_new_default(updated[k], default[k], do_not_migrate_keys.get(k, {})) elif k not in updated or ignore is True: updated[k] = v def check_keys(new_root: Path) -> None: keychain: Keychain = Keychain() all_sks = keychain.get_all_private_keys() if len(all_sks) == 0: print("No keys are present in the keychain. Generate them with 'silicoin keys generate'") return None config: Dict = load_config(new_root, "config.yaml") pool_child_pubkeys = [master_sk_to_pool_sk(sk).get_g1() for sk, _ in all_sks] all_targets = [] stop_searching_for_farmer = "xch_target_address" not in config["farmer"] stop_searching_for_pool = "xch_target_address" not in config["pool"] number_of_ph_to_search = 500 selected = config["selected_network"] prefix = config["network_overrides"]["config"][selected]["address_prefix"] for i in range(number_of_ph_to_search): if stop_searching_for_farmer and stop_searching_for_pool and i > 0: break for sk, _ in all_sks: all_targets.append( encode_puzzle_hash(create_puzzlehash_for_pk(master_sk_to_wallet_sk(sk, uint32(i)).get_g1()), prefix) ) if all_targets[-1] == config["farmer"].get("xch_target_address"): stop_searching_for_farmer = True if all_targets[-1] == config["pool"].get("xch_target_address"): stop_searching_for_pool = True # Set the destinations if "xch_target_address" not in config["farmer"]: print(f"Setting the xch destination address for coinbase fees reward to {all_targets[0]}") config["farmer"]["xch_target_address"] = all_targets[0] elif config["farmer"]["xch_target_address"] not in all_targets: print( f"WARNING: using a farmer address which we don't have the private" f" keys for. We searched the first {number_of_ph_to_search} addresses. Consider overriding " f"{config["farmer"]["xch_target_address"]} with {all_targets[0]}" ) if "pool" not in config: config["pool"] = {} if "xch_target_address" not in config["pool"]: print(f"Setting the xch destination address for coinbase reward to {all_targets[0]}") config["pool"]["xch_target_address"] = all_targets[0] elif config["pool"]["xch_target_address"] not in all_targets: print( f"WARNING: using a pool address which we don't have the private" f" keys for. We searched the first {number_of_ph_to_search} addresses. Consider overriding " f"{config["pool"]["xch_target_address"]} with {all_targets[0]}" ) # Set the pool pks in the farmer pool_pubkeys_hex = set(bytes(pk).hex() for pk in pool_child_pubkeys) if "pool_public_keys" in config["farmer"]: for pk_hex in config["farmer"]["pool_public_keys"]: # Add original ones in config pool_pubkeys_hex.add(pk_hex) config["farmer"]["pool_public_keys"] = pool_pubkeys_hex save_config(new_root, "config.yaml", config) def copy_files_rec(old_path: Path, new_path: Path): if old_path.is_file(): print(f"{new_path}") mkdir(new_path.parent) shutil.copy(old_path, new_path) elif old_path.is_dir(): for old_path_child in old_path.iterdir(): new_path_child = new_path / old_path_child.name copy_files_rec(old_path_child, new_path_child) def migrate_from( old_root: Path, new_root: Path, manifest: List[str], do_not_migrate_settings: List[str], ): """ Copy all the files in "manifest" to the new config directory. """ if old_root == new_root: print("same as new path, exiting") return 1 if not old_root.is_dir(): print(f"{old_root} not found - this is ok if you did not install this version") return 0 print(f"\n{old_root} found") print(f"Copying files from {old_root} to {new_root}\n") for f in manifest: old_path = old_root / f new_path = new_root / f copy_files_rec(old_path, new_path) # update config yaml with new keys config: Dict = load_config(new_root, "config.yaml") config_str: str = initial_config_file("config.yaml") default_config: Dict = yaml.safe_load(config_str) flattened_keys = unflatten_properties({k: "" for k in do_not_migrate_settings}) dict_add_new_default(config, default_config, flattened_keys) save_config(new_root, "config.yaml", config) create_all_ssl(new_root) return 1 def create_all_ssl(root: Path): # remove old key and crt config_dir = root / "config" old_key_path = config_dir / "trusted.key" old_crt_path = config_dir / "trusted.crt" if old_key_path.exists(): print(f"Old key not needed anymore, deleting {old_key_path}") os.remove(old_key_path) if old_crt_path.exists(): print(f"Old crt not needed anymore, deleting {old_crt_path}") os.remove(old_crt_path) ssl_dir = config_dir / "ssl" if not ssl_dir.exists(): ssl_dir.mkdir() ca_dir = ssl_dir / "ca" if not ca_dir.exists(): ca_dir.mkdir() private_ca_key_path = ca_dir / "private_ca.key" private_ca_crt_path = ca_dir / "private_ca.crt" chia_ca_crt, chia_ca_key = get_chia_ca_crt_key() chia_ca_crt_path = ca_dir / "chia_ca.crt" chia_ca_key_path = ca_dir / "chia_ca.key" chia_ca_crt_path.write_bytes(chia_ca_crt) chia_ca_key_path.write_bytes(chia_ca_key) if not private_ca_key_path.exists() or not private_ca_crt_path.exists(): # Create private CA print(f"Can't find private CA, creating a new one in {root} to generate TLS certificates") make_ca_cert(private_ca_crt_path, private_ca_key_path) # Create private certs for each node ca_key = private_ca_key_path.read_bytes() ca_crt = private_ca_crt_path.read_bytes() generate_ssl_for_nodes(ssl_dir, ca_crt, ca_key, True) else: # This is entered when user copied over private CA print(f"Found private CA in {root}, using it to generate TLS certificates") ca_key = private_ca_key_path.read_bytes() ca_crt = private_ca_crt_path.read_bytes() generate_ssl_for_nodes(ssl_dir, ca_crt, ca_key, True) chia_ca_crt, chia_ca_key = get_chia_ca_crt_key() generate_ssl_for_nodes(ssl_dir, chia_ca_crt, chia_ca_key, False, overwrite=False) def generate_ssl_for_nodes(ssl_dir: Path, ca_crt: bytes, ca_key: bytes, private: bool, overwrite=True): if private: names = private_node_names else: names = public_node_names for node_name in names: node_dir = ssl_dir / node_name if not node_dir.exists(): node_dir.mkdir() if private: prefix = "private" else: prefix = "public" key_path = node_dir / f"{prefix}_{node_name}.key" crt_path = node_dir / f"{prefix}_{node_name}.crt" if key_path.exists() and crt_path.exists() and overwrite is False: continue generate_ca_signed_cert(ca_crt, ca_key, crt_path, key_path) def copy_cert_files(cert_path: Path, new_path: Path): for ext in "*.crt", "*.key": for old_path_child in cert_path.glob(ext): new_path_child = new_path / old_path_child.name copy_files_rec(old_path_child, new_path_child) def init(create_certs: Optional[Path], root_path: Path): if create_certs is not None: if root_path.exists(): if os.path.isdir(create_certs): ca_dir: Path = root_path / "config/ssl/ca" if ca_dir.exists(): print(f"Deleting your OLD CA in {ca_dir}") shutil.rmtree(ca_dir) print(f"Copying your CA from {create_certs} to {ca_dir}") copy_cert_files(create_certs, ca_dir) create_all_ssl(root_path) else: print(f"** Directory {create_certs} does not exist **") else: print(f"** {root_path} does not exist. Executing core init **") # sanity check here to prevent infinite recursion if chia_init(root_path) == 0 and root_path.exists(): return init(create_certs, root_path) print(f"** {root_path} was not created. Exiting **") return -1 else: return chia_init(root_path) def chia_version_number() -> Tuple[str, str, str, str]: scm_full_version = __version__ left_full_version = scm_full_version.split("+") version = left_full_version[0].split(".") scm_major_version = version[0] scm_minor_version = version[1] if len(version) > 2: smc_patch_version = version[2] patch_release_number = smc_patch_version else: smc_patch_version = "" major_release_number = scm_major_version minor_release_number = scm_minor_version dev_release_number = "" # If this is a beta dev release - get which beta it is if "0b" in scm_minor_version: original_minor_ver_list = scm_minor_version.split("0b") major_release_number = str(1 - int(scm_major_version)) # decrement the major release for beta minor_release_number = scm_major_version patch_release_number = original_minor_ver_list[1] if smc_patch_version and "dev" in smc_patch_version: dev_release_number = "." + smc_patch_version elif "0rc" in version[1]: original_minor_ver_list = scm_minor_version.split("0rc") major_release_number = str(1 - int(scm_major_version)) # decrement the major release for release candidate minor_release_number = str(int(scm_major_version) + 1) # RC is 0.2.1 for RC 1 patch_release_number = original_minor_ver_list[1] if smc_patch_version and "dev" in smc_patch_version: dev_release_number = "." + smc_patch_version else: major_release_number = scm_major_version minor_release_number = scm_minor_version patch_release_number = smc_patch_version dev_release_number = "" install_release_number = major_release_number + "." + minor_release_number if len(patch_release_number) > 0: install_release_number += "." + patch_release_number if len(dev_release_number) > 0: install_release_number += dev_release_number return major_release_number, minor_release_number, patch_release_number, dev_release_number def chia_minor_release_number(): res = int(chia_version_number()[2]) print(f"Install release number: {res}") return res def chia_full_version_str() -> str: major, minor, patch, dev = chia_version_number() return f"{major}.{minor}.{patch}{dev}" def chia_init(root_path: Path): if os.environ.get("CHIA_ROOT", None) is not None: print( f"warning, your CHIA_ROOT is set to {os.environ["CHIA_ROOT"]}. " f"Please unset the environment variable and run silicoin init again\n" f"or manually migrate config.yaml" ) print(f"Chia directory {root_path}") if root_path.is_dir() and Path(root_path / "config" / "config.yaml").exists(): # This is reached if CHIA_ROOT is set, or if user has run silicoin init twice # before a new update. check_keys(root_path) print(f"{root_path} already exists, no migration action taken") return -1 create_default_chia_config(root_path) create_all_ssl(root_path) check_keys(root_path) print("") print("To see your keys, run 'silicoin keys show --show-mnemonic-seed'") return 0
import os import shutil from pathlib import Path from typing import Any, Dict, List, Optional, Tuple import yaml from chia import __version__ from chia.consensus.coinbase import create_puzzlehash_for_pk from chia.ssl.create_ssl import generate_ca_signed_cert, get_chia_ca_crt_key, make_ca_cert from chia.util.bech32m import encode_puzzle_hash from chia.util.config import ( create_default_chia_config, initial_config_file, load_config, save_config, unflatten_properties, ) from chia.util.ints import uint32 from chia.util.keychain import Keychain from chia.util.path import mkdir from chia.wallet.derive_keys import master_sk_to_pool_sk, master_sk_to_wallet_sk private_node_names = {"full_node", "wallet", "farmer", "harvester", "timelord", "daemon"} public_node_names = {"full_node", "wallet", "farmer", "introducer", "timelord"} def dict_add_new_default(updated: Dict, default: Dict, do_not_migrate_keys: Dict[str, Any]): for k in do_not_migrate_keys: if k in updated and do_not_migrate_keys[k] == "": updated.pop(k) for k, v in default.items(): ignore = False if k in do_not_migrate_keys: do_not_data = do_not_migrate_keys[k] if isinstance(do_not_data, dict): ignore = False else: ignore = True if isinstance(v, dict) and k in updated and ignore is False: # If there is an intermediate key with empty string value, do not migrate all descendants if do_not_migrate_keys.get(k, None) == "": do_not_migrate_keys[k] = v dict_add_new_default(updated[k], default[k], do_not_migrate_keys.get(k, {})) elif k not in updated or ignore is True: updated[k] = v def check_keys(new_root: Path) -> None: keychain: Keychain = Keychain() all_sks = keychain.get_all_private_keys() if len(all_sks) == 0: print("No keys are present in the keychain. Generate them with 'silicoin keys generate'") return None config: Dict = load_config(new_root, "config.yaml") pool_child_pubkeys = [master_sk_to_pool_sk(sk).get_g1() for sk, _ in all_sks] all_targets = [] stop_searching_for_farmer = "xch_target_address" not in config["farmer"] stop_searching_for_pool = "xch_target_address" not in config["pool"] number_of_ph_to_search = 500 selected = config["selected_network"] prefix = config["network_overrides"]["config"][selected]["address_prefix"] for i in range(number_of_ph_to_search): if stop_searching_for_farmer and stop_searching_for_pool and i > 0: break for sk, _ in all_sks: all_targets.append( encode_puzzle_hash(create_puzzlehash_for_pk(master_sk_to_wallet_sk(sk, uint32(i)).get_g1()), prefix) ) if all_targets[-1] == config["farmer"].get("xch_target_address"): stop_searching_for_farmer = True if all_targets[-1] == config["pool"].get("xch_target_address"): stop_searching_for_pool = True # Set the destinations if "xch_target_address" not in config["farmer"]: print(f"Setting the xch destination address for coinbase fees reward to {all_targets[0]}") config["farmer"]["xch_target_address"] = all_targets[0] elif config["farmer"]["xch_target_address"] not in all_targets: print( f"WARNING: using a farmer address which we don't have the private" f" keys for. We searched the first {number_of_ph_to_search} addresses. Consider overriding " f"{config['farmer']['xch_target_address']} with {all_targets[0]}" ) if "pool" not in config: config["pool"] = {} if "xch_target_address" not in config["pool"]: print(f"Setting the xch destination address for coinbase reward to {all_targets[0]}") config["pool"]["xch_target_address"] = all_targets[0] elif config["pool"]["xch_target_address"] not in all_targets: print( f"WARNING: using a pool address which we don't have the private" f" keys for. We searched the first {number_of_ph_to_search} addresses. Consider overriding " f"{config['pool']['xch_target_address']} with {all_targets[0]}" ) # Set the pool pks in the farmer pool_pubkeys_hex = set(bytes(pk).hex() for pk in pool_child_pubkeys) if "pool_public_keys" in config["farmer"]: for pk_hex in config["farmer"]["pool_public_keys"]: # Add original ones in config pool_pubkeys_hex.add(pk_hex) config["farmer"]["pool_public_keys"] = pool_pubkeys_hex save_config(new_root, "config.yaml", config) def copy_files_rec(old_path: Path, new_path: Path): if old_path.is_file(): print(f"{new_path}") mkdir(new_path.parent) shutil.copy(old_path, new_path) elif old_path.is_dir(): for old_path_child in old_path.iterdir(): new_path_child = new_path / old_path_child.name copy_files_rec(old_path_child, new_path_child) def migrate_from( old_root: Path, new_root: Path, manifest: List[str], do_not_migrate_settings: List[str], ): """ Copy all the files in "manifest" to the new config directory. """ if old_root == new_root: print("same as new path, exiting") return 1 if not old_root.is_dir(): print(f"{old_root} not found - this is ok if you did not install this version") return 0 print(f"\n{old_root} found") print(f"Copying files from {old_root} to {new_root}\n") for f in manifest: old_path = old_root / f new_path = new_root / f copy_files_rec(old_path, new_path) # update config yaml with new keys config: Dict = load_config(new_root, "config.yaml") config_str: str = initial_config_file("config.yaml") default_config: Dict = yaml.safe_load(config_str) flattened_keys = unflatten_properties({k: "" for k in do_not_migrate_settings}) dict_add_new_default(config, default_config, flattened_keys) save_config(new_root, "config.yaml", config) create_all_ssl(new_root) return 1 def create_all_ssl(root: Path): # remove old key and crt config_dir = root / "config" old_key_path = config_dir / "trusted.key" old_crt_path = config_dir / "trusted.crt" if old_key_path.exists(): print(f"Old key not needed anymore, deleting {old_key_path}") os.remove(old_key_path) if old_crt_path.exists(): print(f"Old crt not needed anymore, deleting {old_crt_path}") os.remove(old_crt_path) ssl_dir = config_dir / "ssl" if not ssl_dir.exists(): ssl_dir.mkdir() ca_dir = ssl_dir / "ca" if not ca_dir.exists(): ca_dir.mkdir() private_ca_key_path = ca_dir / "private_ca.key" private_ca_crt_path = ca_dir / "private_ca.crt" chia_ca_crt, chia_ca_key = get_chia_ca_crt_key() chia_ca_crt_path = ca_dir / "chia_ca.crt" chia_ca_key_path = ca_dir / "chia_ca.key" chia_ca_crt_path.write_bytes(chia_ca_crt) chia_ca_key_path.write_bytes(chia_ca_key) if not private_ca_key_path.exists() or not private_ca_crt_path.exists(): # Create private CA print(f"Can't find private CA, creating a new one in {root} to generate TLS certificates") make_ca_cert(private_ca_crt_path, private_ca_key_path) # Create private certs for each node ca_key = private_ca_key_path.read_bytes() ca_crt = private_ca_crt_path.read_bytes() generate_ssl_for_nodes(ssl_dir, ca_crt, ca_key, True) else: # This is entered when user copied over private CA print(f"Found private CA in {root}, using it to generate TLS certificates") ca_key = private_ca_key_path.read_bytes() ca_crt = private_ca_crt_path.read_bytes() generate_ssl_for_nodes(ssl_dir, ca_crt, ca_key, True) chia_ca_crt, chia_ca_key = get_chia_ca_crt_key() generate_ssl_for_nodes(ssl_dir, chia_ca_crt, chia_ca_key, False, overwrite=False) def generate_ssl_for_nodes(ssl_dir: Path, ca_crt: bytes, ca_key: bytes, private: bool, overwrite=True): if private: names = private_node_names else: names = public_node_names for node_name in names: node_dir = ssl_dir / node_name if not node_dir.exists(): node_dir.mkdir() if private: prefix = "private" else: prefix = "public" key_path = node_dir / f"{prefix}_{node_name}.key" crt_path = node_dir / f"{prefix}_{node_name}.crt" if key_path.exists() and crt_path.exists() and overwrite is False: continue generate_ca_signed_cert(ca_crt, ca_key, crt_path, key_path) def copy_cert_files(cert_path: Path, new_path: Path): for ext in "*.crt", "*.key": for old_path_child in cert_path.glob(ext): new_path_child = new_path / old_path_child.name copy_files_rec(old_path_child, new_path_child) def init(create_certs: Optional[Path], root_path: Path): if create_certs is not None: if root_path.exists(): if os.path.isdir(create_certs): ca_dir: Path = root_path / "config/ssl/ca" if ca_dir.exists(): print(f"Deleting your OLD CA in {ca_dir}") shutil.rmtree(ca_dir) print(f"Copying your CA from {create_certs} to {ca_dir}") copy_cert_files(create_certs, ca_dir) create_all_ssl(root_path) else: print(f"** Directory {create_certs} does not exist **") else: print(f"** {root_path} does not exist. Executing core init **") # sanity check here to prevent infinite recursion if chia_init(root_path) == 0 and root_path.exists(): return init(create_certs, root_path) print(f"** {root_path} was not created. Exiting **") return -1 else: return chia_init(root_path) def chia_version_number() -> Tuple[str, str, str, str]: scm_full_version = __version__ left_full_version = scm_full_version.split("+") version = left_full_version[0].split(".") scm_major_version = version[0] scm_minor_version = version[1] if len(version) > 2: smc_patch_version = version[2] patch_release_number = smc_patch_version else: smc_patch_version = "" major_release_number = scm_major_version minor_release_number = scm_minor_version dev_release_number = "" # If this is a beta dev release - get which beta it is if "0b" in scm_minor_version: original_minor_ver_list = scm_minor_version.split("0b") major_release_number = str(1 - int(scm_major_version)) # decrement the major release for beta minor_release_number = scm_major_version patch_release_number = original_minor_ver_list[1] if smc_patch_version and "dev" in smc_patch_version: dev_release_number = "." + smc_patch_version elif "0rc" in version[1]: original_minor_ver_list = scm_minor_version.split("0rc") major_release_number = str(1 - int(scm_major_version)) # decrement the major release for release candidate minor_release_number = str(int(scm_major_version) + 1) # RC is 0.2.1 for RC 1 patch_release_number = original_minor_ver_list[1] if smc_patch_version and "dev" in smc_patch_version: dev_release_number = "." + smc_patch_version else: major_release_number = scm_major_version minor_release_number = scm_minor_version patch_release_number = smc_patch_version dev_release_number = "" install_release_number = major_release_number + "." + minor_release_number if len(patch_release_number) > 0: install_release_number += "." + patch_release_number if len(dev_release_number) > 0: install_release_number += dev_release_number return major_release_number, minor_release_number, patch_release_number, dev_release_number def chia_minor_release_number(): res = int(chia_version_number()[2]) print(f"Install release number: {res}") return res def chia_full_version_str() -> str: major, minor, patch, dev = chia_version_number() return f"{major}.{minor}.{patch}{dev}" def chia_init(root_path: Path): if os.environ.get("CHIA_ROOT", None) is not None: print( f"warning, your CHIA_ROOT is set to {os.environ['CHIA_ROOT']}. " f"Please unset the environment variable and run silicoin init again\n" f"or manually migrate config.yaml" ) print(f"Chia directory {root_path}") if root_path.is_dir() and Path(root_path / "config" / "config.yaml").exists(): # This is reached if CHIA_ROOT is set, or if user has run silicoin init twice # before a new update. check_keys(root_path) print(f"{root_path} already exists, no migration action taken") return -1 create_default_chia_config(root_path) create_all_ssl(root_path) check_keys(root_path) print("") print("To see your keys, run 'silicoin keys show --show-mnemonic-seed'") return 0
## ## © Copyright 2021- IBM Inc. All rights reserved # SPDX-License-Identifier: MIT ## import logging from . import rdfxml from . import utils logger = logging.getLogger(__name__) ################################################################################################# class No_Type_System_Mixin(): def __init__(self,*args,**kwargs): self.has_typesystem=False class Type_System_Mixin(): def __init__(self,*args,**kwargs): self.typesystem_loaded = False self.has_typesystem=True self.clear_typesystem() def clear_typesystem(self): self.shapes = {} self.properties = {} self.enums = {} self.values = {} self.typesystem_loaded = False self._gettypecache = {} def textreport(self): def quote(s): if " " in s: return f"'{s}'" else: return s rows = [] report = "" def addtoreport(s, end='\n'): nonlocal report report += s + end reportedproperties = [] # print a nicely sorted report with shapes at left, then properties (with type, if defined) in that shape, then enumerations in that property for shapeuri in sorted(self.shapes.keys(),key=lambda k: self.shapes[k]['name'].lower()): rows.append( [f"{quote(self.shapes[shapeuri]["name"]):25}"] ) for propertyuri in sorted(self.shapes[shapeuri]['properties'], key=lambda k: self.properties[k]['name'].lower()): reportedproperties.append(propertyuri) rows.append( [ "",f"{quote(self.properties[propertyuri]["name"])}"] ) if self.properties[propertyuri]['altname'] is not None: rows[-1].append( f"{self.properties[propertyuri]["altname"]}" ) else: rows[-1].append("") rows[-1].append( f"{rdfxml.uri_to_default_prefixed_tag(propertyuri)}" ) if self.properties[propertyuri].get('value_type'): rows[-1].append( f"{self.properties[propertyuri]["value_type"]}" ) else: rows[-1].append( "" ) newrowlen = len(rows[-1])-3 # add enums as additional rows for enum_uri in sorted(self.properties[propertyuri]['enums'],key=lambda k:self.enums[k]['name'].lower()): eid = self.enums[enum_uri].get('id') or enum_uri rows.append( [""]*newrowlen+[f"{quote(self.enums[enum_uri]["name"])}",eid,enum_uri ] ) logger.info( f"appended for enum {rows[-1]}" ) if len(rows)>0: addtoreport( "<h2>Shapes<h2>\n" ) report += utils.print_in_html( rows,['Shape','Property Name','Property label','URI'] ) # now report properties without shape rows = [] for propertyuri in sorted(self.properties, key=lambda k: self.properties[k]['name'].lower()): if propertyuri not in reportedproperties: rows.append( [ f"{quote(self.properties[propertyuri]["name"])}" ] ) if self.properties[propertyuri]['altname'] is not None: rows[-1].append( f"{self.properties[propertyuri]["altname"]}" ) else: rows[-1].append("") rows[-1].append( f"{rdfxml.uri_to_default_prefixed_tag(propertyuri)}" ) # addtoreport( f"{INDENT}{propertyuri}", end="" ) if self.properties[propertyuri].get('value_type'): rows[-1].append( f"{self.properties[propertyuri]["value_type"]}" ) else: rows[-1].append( "" ) newrowlen = len(rows[-1])-3 # add enums as additional rows for enum_uri in sorted(self.properties[propertyuri]['enums'],key=lambda k:self.enums[k]['name'].lower()): eid = self.enums[enum_uri].get('id') or enum_uri rows.append( [""]*newrowlen+[f"{quote(self.enums[enum_uri]["name"])}",eid,enum_uri ] ) logger.info( f"appended for enum {rows[-1]}" ) if len(rows)>0: addtoreport( "<h2>Properties with no shape</h2>\n" ) report += utils.print_in_html( rows,['Shape','Property Name','Property label','URI'] ) return report # normalise results to either a URI or if a tag expand it, or the name def normalise_uri( self, uri, exception_if_name=False ): if uri is None: result = None elif uri.startswith( 'http://') or uri.startswith( 'https://'): result = uri elif ':' in uri: result = rdfxml.tag_to_uri( uri ) logger.info( f"tag_to_uri {uri=} {result=}" ) else: raise Exception( f"Expecting a uri but this doesn't look like a URI {uri}" ) return result def is_known_shape_uri(self,shape_uri ): logger.info( f"is_known_shape_uri {shape_uri=}" ) shape_uri = self.normalise_uri( shape_uri ) result = self.shapes.get(shape_uri) is not None logger.info( f"is_known_shape_uri {shape_uri=} returning {result=}" ) return result def register_shape( self, shape_name, shape_uri ): logger.info( f"register_shape {shape_name=} {shape_uri=}" ) shape_uri = self.normalise_uri( shape_uri) if shape_uri in self.shapes: raise Exception( f"Shape {shape_uri} already defined!" ) # add the URI as the main registration for the shape self.shapes[shape_uri] = {'name':shape_name,'shape':shape_uri,'properties':[]} self.loaded = True def get_shape_uri( self, shape_name ): logger.info( f"get_shape_uri {shape_name=}" ) shapes = [k for k,v in self.shapes.items() if v['name']==shape_name ] if len(shapes)==1: result = shapes[0] else: result = None return result def get_shape_name( self, shape_uri ): shape_uri = self.normalise_uri( shape_uri) result = self.shapes.get(shape_uri) return result def is_known_property_uri( self, property_uri, *, shape_uri=None, raiseifnotfound=True ): logger.info( f"is_known_property_uri {property_uri=} {shape_uri=}" ) property_uri = self.normalise_uri( property_uri ) shape_uri = self.normalise_uri( shape_uri ) if property_uri in self.properties: if self.properties[property_uri]['shape']==shape_uri: result = True else: if raiseifnotfound: raise Exception( f"Property {property_uri} not registered with shape {shape_uri}" ) result = False else: result = False logger.info( f"is_known_property_uri {property_uri=} {shape_uri=} returning {result=}" ) return result def register_property( self, property_name, property_uri, *, property_value_type=None, shape_uri=None, altname = None, do_not_overwrite=True, property_definition_uri=None ): logger.info( f"register_property {property_name=} {property_uri=} {shape_uri=}" ) property_uri = self.normalise_uri( property_uri ) shape_uri = self.normalise_uri( shape_uri ) if not do_not_overwrite or property_uri not in self.properties: self.properties[property_uri] = {'name': property_name, 'shape': shape_uri, 'enums': [], 'value_type': property_value_type, 'altname':altname} if altname and property_definition_uri and ( not do_not_overwrite or property_definition_uri not in self.properties): self.properties[property_definition_uri] = {'name': altname, 'shape': shape_uri, 'enums': [], 'value_type': property_value_type, 'altname':None} self.properties[rdfxml.uri_to_default_prefixed_tag(property_definition_uri)] = {'name': altname, 'shape': shape_uri, 'enums': [], 'value_type': property_value_type, 'altname':None} if shape_uri is not None: self.shapes[shape_uri]['properties'].append(property_uri) self.loaded = True def get_property_uri( self, property_name, *, shape_uri=None ): logger.info( f"get_property_uri {property_name=} {shape_uri=}" ) shape_uri = self.normalise_uri( shape_uri ) properties = [k for k,v in self.properties.items() if v['name']==property_name and v['shape']==shape_uri] if len(properties)==1: result = properties[0] else: # try using altname altproperties = [k for k,v in self.properties.items() if v['altname']==property_name and v['shape']==shape_uri] if len(altproperties)==1: result = altproperties[0] logger.info( f"Property {property_name} found using altname" ) else: if len(altproperties)>1: altnames = [self.properties[k]['altname'] for k in properties] raise Exception( f"Property {property_name} is ambiguous - maybe use the altname - {altnames}" ) else: # try for a property ignoring the shape - as long as all the ones with the name have the same URI after normalising to a uri if tag/prefix present properties = [k for k,v in self.properties.items() if v['name']==property_name] if len(properties)==1 or (len(properties)>1 and all([rdfxml.tag_to_uri(k)==rdfxml.tag_to_uri(properties[0]) for k in properties[1:]]) ): result = properties[0] else: result = None logger.info( f"get_property_uri {property_name=} {shape_uri=} returning {result=}" ) return result def get_property_name( self, property_uri, shapeuri=None ): logger.info( f"get_property_name {property_uri=} {shape_uri=}" ) property_uri = self.normalise_uri( property_uri ) result = self.properties.get(property_uri) return result def is_known_enum_uri( self, enum_uri ): enum_uri = self.normalise_uri( enum_uri ) result = self.enums.get(enum_uri) logger.info( f"is_known_enum_uri {enum_uri=} returning {result=}" ) return result def register_enum( self, enum_name, enum_uri, property_uri, *, id=None ): logger.info( f"register_enum {enum_name=} {enum_uri=} {property_uri=} {id=}" ) # add the enum to the property enum_uri = self.normalise_uri( enum_uri ) property_uri = self.normalise_uri( property_uri ) self.enums[enum_uri] = {'name': enum_name, 'id':id, 'property': property_uri} self.properties[property_uri]['enums'].append(enum_uri) self.loaded = True def get_enum_uri(self, enum_name, property_uri): property_uri = self.normalise_uri( property_uri ) result = None for enumuri in self.properties[property_uri]['enums']: if self.enums[enumuri]['name']==enum_name: result = enumuri break return result def get_enum_name( self, enum_uri ): property_uri = self.normalise_uri( property_uri ) return self.enums[enum_uri]['name'] def get_enum_id( self, enum_name, property_uri ): logger.info( f"get_enum_id {enum_name=} {property_uri=}" ) property_uri = self.normalise_uri( property_uri ) result = None logger.info( f"{self.properties[property_uri]=}" ) logger.info( f"{self.properties[property_uri]["enums"]=}" ) for enum_uri in self.properties[property_uri]['enums']: if self.enums[enum_uri]['name']==enum_name: result = self.enums[enum_uri]['id'] or enum_uri break logger.info( f"get_enum_id {enum_name=} {property_uri=} {result=}" ) return result # generic uri/name def is_known_uri( self, uri ): logger.debug( f"iku {uri}" ) uri = self.normalise_uri( uri ) result = ( self.shapes.get(uri) or self.properties.get(uri) or self.enums.get(uri) or self.values.get(uri) ) is not None logger.info( f"is_known_uri {uri=} returning {result=} s={self.shapes.get(uri)} p={self.properties.get(uri)} e={self.enums.get(uri)} v={self.values.get(uri)}" ) return result def register_name( self, name, uri ): uri = self.normalise_uri( uri ) self.values[uri]={'name': name } self.loaded = True def get_uri_name( self, uri ): uri = self.normalise_uri( uri ) result = self.shapes.get(uri) or self.properties.get(uri) or self.enums.get(uri) or self.values.get(uri) if result is not None: result = result['name'] logger.info( f"get_uri_name {uri=} returning {result=}" ) return result def get_name_uri( self, name ): result = self.get_shape_uri(name) or self.get_property_uri(name) or self.get_enum_uri(name) or self.get_value_uri(name) return result
## ## © Copyright 2021- IBM Inc. All rights reserved # SPDX-License-Identifier: MIT ## import logging from . import rdfxml from . import utils logger = logging.getLogger(__name__) ################################################################################################# class No_Type_System_Mixin(): def __init__(self,*args,**kwargs): self.has_typesystem=False class Type_System_Mixin(): def __init__(self,*args,**kwargs): self.typesystem_loaded = False self.has_typesystem=True self.clear_typesystem() def clear_typesystem(self): self.shapes = {} self.properties = {} self.enums = {} self.values = {} self.typesystem_loaded = False self._gettypecache = {} def textreport(self): def quote(s): if " " in s: return f"'{s}'" else: return s rows = [] report = "" def addtoreport(s, end='\n'): nonlocal report report += s + end reportedproperties = [] # print a nicely sorted report with shapes at left, then properties (with type, if defined) in that shape, then enumerations in that property for shapeuri in sorted(self.shapes.keys(),key=lambda k: self.shapes[k]['name'].lower()): rows.append( [f"{quote(self.shapes[shapeuri]['name']):25}"] ) for propertyuri in sorted(self.shapes[shapeuri]['properties'], key=lambda k: self.properties[k]['name'].lower()): reportedproperties.append(propertyuri) rows.append( [ "",f"{quote(self.properties[propertyuri]['name'])}"] ) if self.properties[propertyuri]['altname'] is not None: rows[-1].append( f"{self.properties[propertyuri]['altname']}" ) else: rows[-1].append("") rows[-1].append( f"{rdfxml.uri_to_default_prefixed_tag(propertyuri)}" ) if self.properties[propertyuri].get('value_type'): rows[-1].append( f"{self.properties[propertyuri]['value_type']}" ) else: rows[-1].append( "" ) newrowlen = len(rows[-1])-3 # add enums as additional rows for enum_uri in sorted(self.properties[propertyuri]['enums'],key=lambda k:self.enums[k]['name'].lower()): eid = self.enums[enum_uri].get('id') or enum_uri rows.append( [""]*newrowlen+[f"{quote(self.enums[enum_uri]['name'])}",eid,enum_uri ] ) logger.info( f"appended for enum {rows[-1]}" ) if len(rows)>0: addtoreport( "<h2>Shapes<h2>\n" ) report += utils.print_in_html( rows,['Shape','Property Name','Property label','URI'] ) # now report properties without shape rows = [] for propertyuri in sorted(self.properties, key=lambda k: self.properties[k]['name'].lower()): if propertyuri not in reportedproperties: rows.append( [ f"{quote(self.properties[propertyuri]['name'])}" ] ) if self.properties[propertyuri]['altname'] is not None: rows[-1].append( f"{self.properties[propertyuri]['altname']}" ) else: rows[-1].append("") rows[-1].append( f"{rdfxml.uri_to_default_prefixed_tag(propertyuri)}" ) # addtoreport( f"{INDENT}{propertyuri}", end="" ) if self.properties[propertyuri].get('value_type'): rows[-1].append( f"{self.properties[propertyuri]['value_type']}" ) else: rows[-1].append( "" ) newrowlen = len(rows[-1])-3 # add enums as additional rows for enum_uri in sorted(self.properties[propertyuri]['enums'],key=lambda k:self.enums[k]['name'].lower()): eid = self.enums[enum_uri].get('id') or enum_uri rows.append( [""]*newrowlen+[f"{quote(self.enums[enum_uri]['name'])}",eid,enum_uri ] ) logger.info( f"appended for enum {rows[-1]}" ) if len(rows)>0: addtoreport( "<h2>Properties with no shape</h2>\n" ) report += utils.print_in_html( rows,['Shape','Property Name','Property label','URI'] ) return report # normalise results to either a URI or if a tag expand it, or the name def normalise_uri( self, uri, exception_if_name=False ): if uri is None: result = None elif uri.startswith( 'http://') or uri.startswith( 'https://'): result = uri elif ':' in uri: result = rdfxml.tag_to_uri( uri ) logger.info( f"tag_to_uri {uri=} {result=}" ) else: raise Exception( f"Expecting a uri but this doesn't look like a URI {uri}" ) return result def is_known_shape_uri(self,shape_uri ): logger.info( f"is_known_shape_uri {shape_uri=}" ) shape_uri = self.normalise_uri( shape_uri ) result = self.shapes.get(shape_uri) is not None logger.info( f"is_known_shape_uri {shape_uri=} returning {result=}" ) return result def register_shape( self, shape_name, shape_uri ): logger.info( f"register_shape {shape_name=} {shape_uri=}" ) shape_uri = self.normalise_uri( shape_uri) if shape_uri in self.shapes: raise Exception( f"Shape {shape_uri} already defined!" ) # add the URI as the main registration for the shape self.shapes[shape_uri] = {'name':shape_name,'shape':shape_uri,'properties':[]} self.loaded = True def get_shape_uri( self, shape_name ): logger.info( f"get_shape_uri {shape_name=}" ) shapes = [k for k,v in self.shapes.items() if v['name']==shape_name ] if len(shapes)==1: result = shapes[0] else: result = None return result def get_shape_name( self, shape_uri ): shape_uri = self.normalise_uri( shape_uri) result = self.shapes.get(shape_uri) return result def is_known_property_uri( self, property_uri, *, shape_uri=None, raiseifnotfound=True ): logger.info( f"is_known_property_uri {property_uri=} {shape_uri=}" ) property_uri = self.normalise_uri( property_uri ) shape_uri = self.normalise_uri( shape_uri ) if property_uri in self.properties: if self.properties[property_uri]['shape']==shape_uri: result = True else: if raiseifnotfound: raise Exception( f"Property {property_uri} not registered with shape {shape_uri}" ) result = False else: result = False logger.info( f"is_known_property_uri {property_uri=} {shape_uri=} returning {result=}" ) return result def register_property( self, property_name, property_uri, *, property_value_type=None, shape_uri=None, altname = None, do_not_overwrite=True, property_definition_uri=None ): logger.info( f"register_property {property_name=} {property_uri=} {shape_uri=}" ) property_uri = self.normalise_uri( property_uri ) shape_uri = self.normalise_uri( shape_uri ) if not do_not_overwrite or property_uri not in self.properties: self.properties[property_uri] = {'name': property_name, 'shape': shape_uri, 'enums': [], 'value_type': property_value_type, 'altname':altname} if altname and property_definition_uri and ( not do_not_overwrite or property_definition_uri not in self.properties): self.properties[property_definition_uri] = {'name': altname, 'shape': shape_uri, 'enums': [], 'value_type': property_value_type, 'altname':None} self.properties[rdfxml.uri_to_default_prefixed_tag(property_definition_uri)] = {'name': altname, 'shape': shape_uri, 'enums': [], 'value_type': property_value_type, 'altname':None} if shape_uri is not None: self.shapes[shape_uri]['properties'].append(property_uri) self.loaded = True def get_property_uri( self, property_name, *, shape_uri=None ): logger.info( f"get_property_uri {property_name=} {shape_uri=}" ) shape_uri = self.normalise_uri( shape_uri ) properties = [k for k,v in self.properties.items() if v['name']==property_name and v['shape']==shape_uri] if len(properties)==1: result = properties[0] else: # try using altname altproperties = [k for k,v in self.properties.items() if v['altname']==property_name and v['shape']==shape_uri] if len(altproperties)==1: result = altproperties[0] logger.info( f"Property {property_name} found using altname" ) else: if len(altproperties)>1: altnames = [self.properties[k]['altname'] for k in properties] raise Exception( f"Property {property_name} is ambiguous - maybe use the altname - {altnames}" ) else: # try for a property ignoring the shape - as long as all the ones with the name have the same URI after normalising to a uri if tag/prefix present properties = [k for k,v in self.properties.items() if v['name']==property_name] if len(properties)==1 or (len(properties)>1 and all([rdfxml.tag_to_uri(k)==rdfxml.tag_to_uri(properties[0]) for k in properties[1:]]) ): result = properties[0] else: result = None logger.info( f"get_property_uri {property_name=} {shape_uri=} returning {result=}" ) return result def get_property_name( self, property_uri, shapeuri=None ): logger.info( f"get_property_name {property_uri=} {shape_uri=}" ) property_uri = self.normalise_uri( property_uri ) result = self.properties.get(property_uri) return result def is_known_enum_uri( self, enum_uri ): enum_uri = self.normalise_uri( enum_uri ) result = self.enums.get(enum_uri) logger.info( f"is_known_enum_uri {enum_uri=} returning {result=}" ) return result def register_enum( self, enum_name, enum_uri, property_uri, *, id=None ): logger.info( f"register_enum {enum_name=} {enum_uri=} {property_uri=} {id=}" ) # add the enum to the property enum_uri = self.normalise_uri( enum_uri ) property_uri = self.normalise_uri( property_uri ) self.enums[enum_uri] = {'name': enum_name, 'id':id, 'property': property_uri} self.properties[property_uri]['enums'].append(enum_uri) self.loaded = True def get_enum_uri(self, enum_name, property_uri): property_uri = self.normalise_uri( property_uri ) result = None for enumuri in self.properties[property_uri]['enums']: if self.enums[enumuri]['name']==enum_name: result = enumuri break return result def get_enum_name( self, enum_uri ): property_uri = self.normalise_uri( property_uri ) return self.enums[enum_uri]['name'] def get_enum_id( self, enum_name, property_uri ): logger.info( f"get_enum_id {enum_name=} {property_uri=}" ) property_uri = self.normalise_uri( property_uri ) result = None logger.info( f"{self.properties[property_uri]=}" ) logger.info( f"{self.properties[property_uri]['enums']=}" ) for enum_uri in self.properties[property_uri]['enums']: if self.enums[enum_uri]['name']==enum_name: result = self.enums[enum_uri]['id'] or enum_uri break logger.info( f"get_enum_id {enum_name=} {property_uri=} {result=}" ) return result # generic uri/name def is_known_uri( self, uri ): logger.debug( f"iku {uri}" ) uri = self.normalise_uri( uri ) result = ( self.shapes.get(uri) or self.properties.get(uri) or self.enums.get(uri) or self.values.get(uri) ) is not None logger.info( f"is_known_uri {uri=} returning {result=} s={self.shapes.get(uri)} p={self.properties.get(uri)} e={self.enums.get(uri)} v={self.values.get(uri)}" ) return result def register_name( self, name, uri ): uri = self.normalise_uri( uri ) self.values[uri]={'name': name } self.loaded = True def get_uri_name( self, uri ): uri = self.normalise_uri( uri ) result = self.shapes.get(uri) or self.properties.get(uri) or self.enums.get(uri) or self.values.get(uri) if result is not None: result = result['name'] logger.info( f"get_uri_name {uri=} returning {result=}" ) return result def get_name_uri( self, name ): result = self.get_shape_uri(name) or self.get_property_uri(name) or self.get_enum_uri(name) or self.get_value_uri(name) return result
import argparse from bs4 import BeautifulSoup import multiprocessing as mp from multiprocessing.pool import ThreadPool import os import pandas as pd import pathlib import requests import subprocess from tqdm.auto import tqdm from utils import load_config ''' load config and secrets ''' # config = load_config(path='../', config_file='config.yaml')['kowalski'] config = load_config(config_file='config.yaml')['kowalski'] def collect_urls(rc): bu = os.path.join(base_url, f'rc{rc:02d}') response = requests.get(bu, auth=(config['ztf_depot']['username'], config['ztf_depot']['password'])) html = response.text # link_list = [] soup = BeautifulSoup(html, 'html.parser') links = soup.findAll('a') for link in links: txt = link.getText() if 'fr' in txt: bu_fr = os.path.join(bu, txt) response_fr = requests.get( bu_fr, auth=(config['ztf_depot']['username'], config['ztf_depot']['password']) ) html_fr = response_fr.text soup_fr = BeautifulSoup(html_fr, 'html.parser') links_fr = soup_fr.findAll('a') for link_fr in links_fr: txt_fr = link_fr.getText() if txt_fr.endswith('.pytable'): # print('\t', txt_fr) urls.append({'rc': rc, 'name': txt_fr, 'url': os.path.join(bu_fr, txt_fr)}) # fixme: # break def fetch_url(urlrc, source='ipac'): url, _rc = urlrc p = os.path.join(str(path), str(_rc), os.path.basename(url)) if not os.path.exists(p): if source == 'ipac': subprocess.run(['wget', f"--http-user={config["ztf_depot"]["username"]}", f"--http-passwd={config["ztf_depot"]["password"]}", '-q', '--timeout=600', '--waitretry=10', '--tries=5', '-O', p, url]) elif source == 'supernova': _url = url.replace('https://', '/media/Data2/Matchfiles/') subprocess.run(['scp', f'duev@supernova.caltech.edu:{_url}', path]) # time.sleep(0.5) def gunzip(f): subprocess.run(['gunzip', f]) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--tag', type=str, default='20200401', help='matchfile release time tag') args = parser.parse_args() t_tag = args.tag path_base = pathlib.Path('./') # path_base = pathlib.Path('/_tmp/') path = path_base / f'ztf_matchfiles_{t_tag}/' if not path.exists(): path.mkdir(exist_ok=True, parents=True) for rc in range(0, 64): path_rc = path / str(rc) if not path_rc.exists(): path_rc.mkdir(exist_ok=True, parents=True) path_urls = path_base / f'ztf_matchfiles_{t_tag}.csv' # n_rc = 1 n_rc = 64 if not path_urls.exists(): base_url = 'https://ztfweb.ipac.caltech.edu/ztf/ops/srcmatch/' # store urls urls = [] print('Collecting urls of matchfiles to download:') # collect urls of matchfiles to download with ThreadPool(processes=20) as pool: list(tqdm(pool.imap(collect_urls, range(0, n_rc)), total=n_rc)) df_mf = pd.DataFrame.from_records(urls) print(df_mf) df_mf.to_csv(path_urls, index=False) else: df_mf = pd.read_csv(path_urls) print(df_mf) # check what's (already) on GCS: ongs = [] for rc in tqdm(range(0, n_rc), total=n_rc): ongs_rc = subprocess.check_output([ 'gsutil', 'ls', f'gs://ztf-matchfiles-{t_tag}/{rc}/', ]).decode('utf-8').strip().split('\n') ongs += [pathlib.Path(ong).name for ong in ongs_rc if ong.endswith('pytable')] # print(ongs) # matchfiles that are not on GCS: # print(df_mf['name'].isin(ongs)) w = ~(df_mf['name'].isin(ongs)) # print(pd.unique(df_mf.loc[w, 'rc'])) print(f'Downloading {w.sum()} matchfiles:') url_list = [(r.url, r.rc) for r in df_mf.loc[w].itertuples()] # download with mp.Pool(processes=4) as pool: list(tqdm(pool.imap(fetch_url, url_list), total=len(url_list))) # move to GCS: for rc in tqdm(range(0, n_rc), total=n_rc): # move to gs subprocess.run(["/usr/local/bin/gsutil", "-m", "mv", str(path / f"{rc}/*.pytable"), f"gs://ztf-matchfiles-{t_tag}/{rc}/"]) # remove locally # subprocess.run(["rm", "rf", f"/_tmp/ztf_matchfiles_{t_tag}/{rc}/"])
import argparse from bs4 import BeautifulSoup import multiprocessing as mp from multiprocessing.pool import ThreadPool import os import pandas as pd import pathlib import requests import subprocess from tqdm.auto import tqdm from utils import load_config ''' load config and secrets ''' # config = load_config(path='../', config_file='config.yaml')['kowalski'] config = load_config(config_file='config.yaml')['kowalski'] def collect_urls(rc): bu = os.path.join(base_url, f'rc{rc:02d}') response = requests.get(bu, auth=(config['ztf_depot']['username'], config['ztf_depot']['password'])) html = response.text # link_list = [] soup = BeautifulSoup(html, 'html.parser') links = soup.findAll('a') for link in links: txt = link.getText() if 'fr' in txt: bu_fr = os.path.join(bu, txt) response_fr = requests.get( bu_fr, auth=(config['ztf_depot']['username'], config['ztf_depot']['password']) ) html_fr = response_fr.text soup_fr = BeautifulSoup(html_fr, 'html.parser') links_fr = soup_fr.findAll('a') for link_fr in links_fr: txt_fr = link_fr.getText() if txt_fr.endswith('.pytable'): # print('\t', txt_fr) urls.append({'rc': rc, 'name': txt_fr, 'url': os.path.join(bu_fr, txt_fr)}) # fixme: # break def fetch_url(urlrc, source='ipac'): url, _rc = urlrc p = os.path.join(str(path), str(_rc), os.path.basename(url)) if not os.path.exists(p): if source == 'ipac': subprocess.run(['wget', f"--http-user={config['ztf_depot']['username']}", f"--http-passwd={config['ztf_depot']['password']}", '-q', '--timeout=600', '--waitretry=10', '--tries=5', '-O', p, url]) elif source == 'supernova': _url = url.replace('https://', '/media/Data2/Matchfiles/') subprocess.run(['scp', f'duev@supernova.caltech.edu:{_url}', path]) # time.sleep(0.5) def gunzip(f): subprocess.run(['gunzip', f]) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--tag', type=str, default='20200401', help='matchfile release time tag') args = parser.parse_args() t_tag = args.tag path_base = pathlib.Path('./') # path_base = pathlib.Path('/_tmp/') path = path_base / f'ztf_matchfiles_{t_tag}/' if not path.exists(): path.mkdir(exist_ok=True, parents=True) for rc in range(0, 64): path_rc = path / str(rc) if not path_rc.exists(): path_rc.mkdir(exist_ok=True, parents=True) path_urls = path_base / f'ztf_matchfiles_{t_tag}.csv' # n_rc = 1 n_rc = 64 if not path_urls.exists(): base_url = 'https://ztfweb.ipac.caltech.edu/ztf/ops/srcmatch/' # store urls urls = [] print('Collecting urls of matchfiles to download:') # collect urls of matchfiles to download with ThreadPool(processes=20) as pool: list(tqdm(pool.imap(collect_urls, range(0, n_rc)), total=n_rc)) df_mf = pd.DataFrame.from_records(urls) print(df_mf) df_mf.to_csv(path_urls, index=False) else: df_mf = pd.read_csv(path_urls) print(df_mf) # check what's (already) on GCS: ongs = [] for rc in tqdm(range(0, n_rc), total=n_rc): ongs_rc = subprocess.check_output([ 'gsutil', 'ls', f'gs://ztf-matchfiles-{t_tag}/{rc}/', ]).decode('utf-8').strip().split('\n') ongs += [pathlib.Path(ong).name for ong in ongs_rc if ong.endswith('pytable')] # print(ongs) # matchfiles that are not on GCS: # print(df_mf['name'].isin(ongs)) w = ~(df_mf['name'].isin(ongs)) # print(pd.unique(df_mf.loc[w, 'rc'])) print(f'Downloading {w.sum()} matchfiles:') url_list = [(r.url, r.rc) for r in df_mf.loc[w].itertuples()] # download with mp.Pool(processes=4) as pool: list(tqdm(pool.imap(fetch_url, url_list), total=len(url_list))) # move to GCS: for rc in tqdm(range(0, n_rc), total=n_rc): # move to gs subprocess.run(["/usr/local/bin/gsutil", "-m", "mv", str(path / f"{rc}/*.pytable"), f"gs://ztf-matchfiles-{t_tag}/{rc}/"]) # remove locally # subprocess.run(["rm", "rf", f"/_tmp/ztf_matchfiles_{t_tag}/{rc}/"])
from __future__ import annotations import json import typing from typing import Literal, TYPE_CHECKING, Union from lxml import html import pydantic from compass.core.interface_base import InterfaceBase from compass.core.schemas import hierarchy as schema from compass.core.settings import Settings from compass.core.utility import compass_restify if TYPE_CHECKING: import requests # TYPES_ENDPOINT_LEVELS values are meaningful values as they become the API endpoint paths TYPES_ENDPOINT_LEVELS = Literal[ "countries", "hq_sections", "regions", "country_sections", "counties", "region_sections", "districts", "county_sections", "groups", "district_sections", "group_sections", ] endpoints = {i: f"/{i.replace("_", "/")}" for i in typing.get_args(TYPES_ENDPOINT_LEVELS)} class HierarchyScraper(InterfaceBase): def __init__(self, session: requests.Session, validate: bool = False): """Constructor for HierarchyScraper. takes an initialised Session object from Logon """ super().__init__(session) self.validate = validate gufh_native = list[dict[str, Union[int, str, None]]] gufh_pydantic = Union[schema.HierarchySection, schema.HierarchyUnit] # see CompassClient::retrieveLevel or retrieveSections in PGS\Needle php def get_units_from_hierarchy(self, parent_unit: int, level: TYPES_ENDPOINT_LEVELS) -> Union[gufh_native, gufh_pydantic, None]: """Get all children of a given unit. If LiveData=Y is passed, the resulting JSON additionally contains: - (duplicated) parent id - the unit address - number of members - SectionType1 and SectionTypeDesc1 keys, if requesting sections data TODO Args: parent_unit: The unit ID to get descendants from level: string org type, used for selecting API endpoint Returns: Mapping of unit properties to data. E.g.: {'id': ..., 'name': '...', 'parent_id': ..., 'status': '...', 'address': '...', 'member_count': ...} Todo: can we do this without needing to provide the level string? raises? (from requests etc) """ # Get API endpoint from level level_endpoint = endpoints[level] # Are we requesting sections here? is_sections = "/sections" in level_endpoint result = self._post(f"{Settings.base_url}/hierarchy{level_endpoint}", json={"LiveData": "Y", "ParentID": f"{parent_unit}"}) result_json = result.json() # Handle unauthorised access TODO raise??? if result_json == {"Message": "Authorization has been denied for this request."}: return [{"id": None, "name": None}] result_units = [] for unit_dict in result_json: parsed = { "id": int(unit_dict["Value"]), "name": unit_dict["Description"], "parent_id": unit_dict["Parent"], } if unit_dict["Tag"]: # TODO possible error states - what can we expect here as an invariant? tag = json.loads(unit_dict["Tag"])[0] parsed["status"] = tag["org_status"] parsed["address"] = tag["address"] parsed["member_count"] = tag["Members"] # Only include section_type if there is section type data if "SectionTypeDesc" in tag: parsed["section_type"] = tag["SectionTypeDesc"] result_units.append(parsed) if self.validate: return pydantic.parse_obj_as(list[schema.HierarchySection if is_sections else schema.HierarchyUnit], result_units) else: return result_units gmwriu_native = dict[str, Union[int, str]] gmwriu_pydantic = schema.HierarchyMember def get_members_with_roles_in_unit( self, unit_number: int, include_name: bool = False, include_primary_role: bool = False ) -> list[Union[gmwriu_native, gmwriu_pydantic]]: """Get details of members with roles in a given unit. Keys within the member_data JSON are (as at 13/01/220): - contact_number (membership number) - name (member's name) - visibility_status (this is meaningless as we can only see Y people) - address (this doesn't reliably give us postcode and is a lot of data) - role (This is Primary role and so only sometimes useful) Args: unit_number: Compass unit number include_name: include member name in returned data include_primary_role: include primary role in returned data Returns: A list of member records. Keys are included through args E.g.: [ {"contact_number": ..., ...}, ... ] Todo: raises? """ keys_to_keep = ("contact_number",) if include_name: keys_to_keep = (*keys_to_keep, "name") if include_primary_role: keys_to_keep = (*keys_to_keep, "role") # Construct request data # It seems like the time UID value can be constant -- keeping old code in case something breaks # dt = datetime.datetime.now() # time_uid = f"{dt.hour}{dt.minute}{dt.microsecond // 1000}" time_uid = str(12_34_567) data = {"SearchType": "HIERARCHY", "OrganisationNumber": unit_number, "UI": time_uid} # Execute search # JSON data MUST be in the rather odd format of {"Key": key, "Value": value} for each (key, value) pair self._post(f"{Settings.base_url}/Search/Members", json=compass_restify(data)) # Fetch results from Compass search_results = self._get(f"{Settings.base_url}/SearchResults.aspx") # Gets the compass form from the returned document form = html.fromstring(search_results.content).forms[0] del search_results # If the search hasn't worked the form returns an InvalidSearchError - check for this and raise an error if needed if form.action == "./ScoutsPortal.aspx?Invalid=SearchError": raise Exception("Invalid Search") # Get the encoded JSON data from the HTML member_data_string = form.fields["ctl00$plInnerPanel_head$txt_h_Data"] or "[]" del form # parse the data and return it as a usable Python object (list) member_data = json.loads(member_data_string) if self.validate: return [schema.HierarchyMember(**{key: member[key] for key in keys_to_keep}) for member in member_data] else: return [{key: member[key] for key in keys_to_keep} for member in member_data]
from __future__ import annotations import json import typing from typing import Literal, TYPE_CHECKING, Union from lxml import html import pydantic from compass.core.interface_base import InterfaceBase from compass.core.schemas import hierarchy as schema from compass.core.settings import Settings from compass.core.utility import compass_restify if TYPE_CHECKING: import requests # TYPES_ENDPOINT_LEVELS values are meaningful values as they become the API endpoint paths TYPES_ENDPOINT_LEVELS = Literal[ "countries", "hq_sections", "regions", "country_sections", "counties", "region_sections", "districts", "county_sections", "groups", "district_sections", "group_sections", ] endpoints = {i: f"/{i.replace('_', '/')}" for i in typing.get_args(TYPES_ENDPOINT_LEVELS)} class HierarchyScraper(InterfaceBase): def __init__(self, session: requests.Session, validate: bool = False): """Constructor for HierarchyScraper. takes an initialised Session object from Logon """ super().__init__(session) self.validate = validate gufh_native = list[dict[str, Union[int, str, None]]] gufh_pydantic = Union[schema.HierarchySection, schema.HierarchyUnit] # see CompassClient::retrieveLevel or retrieveSections in PGS\Needle php def get_units_from_hierarchy(self, parent_unit: int, level: TYPES_ENDPOINT_LEVELS) -> Union[gufh_native, gufh_pydantic, None]: """Get all children of a given unit. If LiveData=Y is passed, the resulting JSON additionally contains: - (duplicated) parent id - the unit address - number of members - SectionType1 and SectionTypeDesc1 keys, if requesting sections data TODO Args: parent_unit: The unit ID to get descendants from level: string org type, used for selecting API endpoint Returns: Mapping of unit properties to data. E.g.: {'id': ..., 'name': '...', 'parent_id': ..., 'status': '...', 'address': '...', 'member_count': ...} Todo: can we do this without needing to provide the level string? raises? (from requests etc) """ # Get API endpoint from level level_endpoint = endpoints[level] # Are we requesting sections here? is_sections = "/sections" in level_endpoint result = self._post(f"{Settings.base_url}/hierarchy{level_endpoint}", json={"LiveData": "Y", "ParentID": f"{parent_unit}"}) result_json = result.json() # Handle unauthorised access TODO raise??? if result_json == {"Message": "Authorization has been denied for this request."}: return [{"id": None, "name": None}] result_units = [] for unit_dict in result_json: parsed = { "id": int(unit_dict["Value"]), "name": unit_dict["Description"], "parent_id": unit_dict["Parent"], } if unit_dict["Tag"]: # TODO possible error states - what can we expect here as an invariant? tag = json.loads(unit_dict["Tag"])[0] parsed["status"] = tag["org_status"] parsed["address"] = tag["address"] parsed["member_count"] = tag["Members"] # Only include section_type if there is section type data if "SectionTypeDesc" in tag: parsed["section_type"] = tag["SectionTypeDesc"] result_units.append(parsed) if self.validate: return pydantic.parse_obj_as(list[schema.HierarchySection if is_sections else schema.HierarchyUnit], result_units) else: return result_units gmwriu_native = dict[str, Union[int, str]] gmwriu_pydantic = schema.HierarchyMember def get_members_with_roles_in_unit( self, unit_number: int, include_name: bool = False, include_primary_role: bool = False ) -> list[Union[gmwriu_native, gmwriu_pydantic]]: """Get details of members with roles in a given unit. Keys within the member_data JSON are (as at 13/01/220): - contact_number (membership number) - name (member's name) - visibility_status (this is meaningless as we can only see Y people) - address (this doesn't reliably give us postcode and is a lot of data) - role (This is Primary role and so only sometimes useful) Args: unit_number: Compass unit number include_name: include member name in returned data include_primary_role: include primary role in returned data Returns: A list of member records. Keys are included through args E.g.: [ {"contact_number": ..., ...}, ... ] Todo: raises? """ keys_to_keep = ("contact_number",) if include_name: keys_to_keep = (*keys_to_keep, "name") if include_primary_role: keys_to_keep = (*keys_to_keep, "role") # Construct request data # It seems like the time UID value can be constant -- keeping old code in case something breaks # dt = datetime.datetime.now() # time_uid = f"{dt.hour}{dt.minute}{dt.microsecond // 1000}" time_uid = str(12_34_567) data = {"SearchType": "HIERARCHY", "OrganisationNumber": unit_number, "UI": time_uid} # Execute search # JSON data MUST be in the rather odd format of {"Key": key, "Value": value} for each (key, value) pair self._post(f"{Settings.base_url}/Search/Members", json=compass_restify(data)) # Fetch results from Compass search_results = self._get(f"{Settings.base_url}/SearchResults.aspx") # Gets the compass form from the returned document form = html.fromstring(search_results.content).forms[0] del search_results # If the search hasn't worked the form returns an InvalidSearchError - check for this and raise an error if needed if form.action == "./ScoutsPortal.aspx?Invalid=SearchError": raise Exception("Invalid Search") # Get the encoded JSON data from the HTML member_data_string = form.fields["ctl00$plInnerPanel_head$txt_h_Data"] or "[]" del form # parse the data and return it as a usable Python object (list) member_data = json.loads(member_data_string) if self.validate: return [schema.HierarchyMember(**{key: member[key] for key in keys_to_keep}) for member in member_data] else: return [{key: member[key] for key in keys_to_keep} for member in member_data]
""" Module containing Notes class """ import logging from ..common.common import SectionHandler # pylint: disable=too-few-public-methods class Notes(SectionHandler): """ Responsible for converting the Notes sections: - /cvrf:cvrfdoc/cvrf:DocumentNotes - /cvrf:cvrfdoc/vuln:Vulnerability[i+1]/vuln:Notes """ def __init__(self): super().__init__() self.enum_categories = { 'description', 'details', 'faq', 'general', 'legal_disclaimer', 'other', 'summary' } def _process_mandatory_and_optional(self, root_element): notes = [] for elem_note in root_element.Note: # mandatory new_note = dict( text=elem_note.text, category=elem_note.get('Type').lower().replace(' ', '_'), ) if new_note['category'] not in self.enum_categories: log_msg = f'Invalid document notes category {new_note['category']}. Should be' \ f' one of: {','.join(str(x) for x in sorted(self.enum_categories))}!' logging.error(log_msg) SectionHandler.error_occurred = True # optional if elem_note.get('Audience'): new_note['audience'] = elem_note.get('Audience') if elem_note.get('Title'): new_note['title'] = elem_note.get('Title') notes.append(new_note) if notes and len(notes) > 0: self.csaf = notes def _process_mandatory_elements(self, root_element): return self._process_mandatory_and_optional(root_element=root_element) def _process_optional_elements(self, root_element): # No optional elements pass
""" Module containing Notes class """ import logging from ..common.common import SectionHandler # pylint: disable=too-few-public-methods class Notes(SectionHandler): """ Responsible for converting the Notes sections: - /cvrf:cvrfdoc/cvrf:DocumentNotes - /cvrf:cvrfdoc/vuln:Vulnerability[i+1]/vuln:Notes """ def __init__(self): super().__init__() self.enum_categories = { 'description', 'details', 'faq', 'general', 'legal_disclaimer', 'other', 'summary' } def _process_mandatory_and_optional(self, root_element): notes = [] for elem_note in root_element.Note: # mandatory new_note = dict( text=elem_note.text, category=elem_note.get('Type').lower().replace(' ', '_'), ) if new_note['category'] not in self.enum_categories: log_msg = f'Invalid document notes category {new_note["category"]}. Should be' \ f' one of: {",".join(str(x) for x in sorted(self.enum_categories))}!' logging.error(log_msg) SectionHandler.error_occurred = True # optional if elem_note.get('Audience'): new_note['audience'] = elem_note.get('Audience') if elem_note.get('Title'): new_note['title'] = elem_note.get('Title') notes.append(new_note) if notes and len(notes) > 0: self.csaf = notes def _process_mandatory_elements(self, root_element): return self._process_mandatory_and_optional(root_element=root_element) def _process_optional_elements(self, root_element): # No optional elements pass
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import random import re openings_by_name, openings_by_pgn = {}, {} keys_by_name, keys_by_pgn = [], [] # Give me a new opening def get_random_opening(openings_by_name, keys_by_name): key = random.choice(keys_by_name) return openings_by_name[key] # Tell me about the Amar Opening # Tell me 5 variations of the Amar Opening def get_chosen_opening(name, openings_by_name, keys_by_name, limit=None): keys = keys_by_name matches = list(filter(lambda key: key.startswith(name), keys)) if limit is not None and limit > 0: matches = matches[:limit] result = [] for match in matches: result.append(openings_by_name[match]) return result # Which openings start with b3? (all the...) # Tell me 5 variations that start with g4 def get_opening_by_first_moves(first_moves, openings_by_pgn, keys_by_pgn, limit=None): keys = keys_by_pgn matches = list(filter(lambda key: key.startswith(first_moves), keys)) if limit is not None and limit > 0: matches = matches[:limit] result = [] for match in matches: result.append(openings_by_pgn[match]) return result # Openings with ECO = A00 def get_opening_by_eco(eco, openings_by_eco, keys_by_eco, limit=None): keys = keys_by_eco matches = list(filter(lambda key: key == eco, keys)) if limit is not None and limit > 0: matches = matches[:limit] result = [] for match in matches: result.append(openings_by_eco[match]) return result def main(): """ Main program """ # Initialize global variables global openings_by_name, openings_by_pgn global keys_by_name, keys_by_pgn if len(keys_by_name) == 0 or len(keys_by_pgn) == 0: with open('openings_by_name.json', encoding='utf-8') as f: openings_by_name = json.load(f) with open('openings_by_pgn.json', encoding='utf-8') as f: openings_by_pgn = json.load(f) with open('keys_by_name.json', encoding='utf-8') as f: keys_by_name = json.load(f) with open('keys_by_pgn.json', encoding='utf-8') as f: keys_by_pgn = json.load(f) opening = get_random_opening(openings_by_name, keys_by_name) print(f"Your new opening is the {opening["name"]} (ECO {opening["eco"]})-> {opening["pgn"]}") keyword = 'hungarian opening' openings = get_chosen_opening(keyword, openings_by_name, keys_by_name) print(f"There are {len(openings)} variations of the {keyword}:") for opening in openings: print(f"The {opening["name"]}, with ECO {opening["eco"]}-> {opening["pgn"]}") keyword = 'g3 d5' openings = get_opening_by_first_moves(keyword, openings_by_pgn, keys_by_pgn) print(f"There are {len(openings)} variations that start with {keyword}:") for opening in openings: print(f"The {opening["name"]} (ECO {opening["eco"]})-> {opening["pgn"]}") if __name__ == "__main__": main()
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import random import re openings_by_name, openings_by_pgn = {}, {} keys_by_name, keys_by_pgn = [], [] # Give me a new opening def get_random_opening(openings_by_name, keys_by_name): key = random.choice(keys_by_name) return openings_by_name[key] # Tell me about the Amar Opening # Tell me 5 variations of the Amar Opening def get_chosen_opening(name, openings_by_name, keys_by_name, limit=None): keys = keys_by_name matches = list(filter(lambda key: key.startswith(name), keys)) if limit is not None and limit > 0: matches = matches[:limit] result = [] for match in matches: result.append(openings_by_name[match]) return result # Which openings start with b3? (all the...) # Tell me 5 variations that start with g4 def get_opening_by_first_moves(first_moves, openings_by_pgn, keys_by_pgn, limit=None): keys = keys_by_pgn matches = list(filter(lambda key: key.startswith(first_moves), keys)) if limit is not None and limit > 0: matches = matches[:limit] result = [] for match in matches: result.append(openings_by_pgn[match]) return result # Openings with ECO = A00 def get_opening_by_eco(eco, openings_by_eco, keys_by_eco, limit=None): keys = keys_by_eco matches = list(filter(lambda key: key == eco, keys)) if limit is not None and limit > 0: matches = matches[:limit] result = [] for match in matches: result.append(openings_by_eco[match]) return result def main(): """ Main program """ # Initialize global variables global openings_by_name, openings_by_pgn global keys_by_name, keys_by_pgn if len(keys_by_name) == 0 or len(keys_by_pgn) == 0: with open('openings_by_name.json', encoding='utf-8') as f: openings_by_name = json.load(f) with open('openings_by_pgn.json', encoding='utf-8') as f: openings_by_pgn = json.load(f) with open('keys_by_name.json', encoding='utf-8') as f: keys_by_name = json.load(f) with open('keys_by_pgn.json', encoding='utf-8') as f: keys_by_pgn = json.load(f) opening = get_random_opening(openings_by_name, keys_by_name) print(f"Your new opening is the {opening['name']} (ECO {opening['eco']})-> {opening['pgn']}") keyword = 'hungarian opening' openings = get_chosen_opening(keyword, openings_by_name, keys_by_name) print(f"There are {len(openings)} variations of the {keyword}:") for opening in openings: print(f"The {opening['name']}, with ECO {opening['eco']}-> {opening['pgn']}") keyword = 'g3 d5' openings = get_opening_by_first_moves(keyword, openings_by_pgn, keys_by_pgn) print(f"There are {len(openings)} variations that start with {keyword}:") for opening in openings: print(f"The {opening['name']} (ECO {opening['eco']})-> {opening['pgn']}") if __name__ == "__main__": main()
import pandas as pd import os import sys from docx import Document from pathlib import Path from nbdev.showdoc import doc import ipywidgets as widgets import numpy as np from IPython.display import display from ipywidgets import HTML from functools import partial import openpyxl import json import sched, time import threading from threading import Thread, Event # database files root = Path('/data/f101_auto') db_path = root/'db' docx_path = db_path/'docx' review_path = docx_path/'review' xlsx_path = db_path/'xlsx' template_path = xlsx_path/'template.xlsx' # temporary files download_temp = root/'download/temp' download_temp_docx = download_temp/'docx' download_dir = root/'download/data' download_zip = root/'download/data.zip' class DB: def __init__(self, db_path=db_path): self.db_path = db_path self.json_path = db_path/'json' self.json_file = self.json_path/'db.json' self.docx_path = db_path/'docx' self.review_path = self.docx_path/'review' self.db_path.mkdir(parents=True, exist_ok=True) self.json_path.mkdir(parents=True, exist_ok=True) self.docx_path.mkdir(parents=True, exist_ok=True) self.review_path.mkdir(parents=True, exist_ok=True) self.listeners = [] if(not os.path.isfile(self.json_file)): data = {'n_employees': 0, 'courses':[]} self.save(data) # polling self.delay = 2 self.last_check = -1 self.stopFlag = Event() self.poll_thread = PollThread(on_poll=self.__poll_file, delay_sec=self.delay, stop_event=self.stopFlag) def start_poll(self): self.poll_thread.start() def stop_poll(self): self.stopFlag.set() def get_db(self): db = {} json_data = self.__get_json() scores_df = self.get_scores() db['scores'] = scores_df db['surveyed'] = list(scores_df.index) db['courses'] = json_data['courses'] db['n_employees'] = json_data['n_employees'] return db def add_course(self, course): data = self.__get_json() data['courses'].append(course) self.save(data) self.__update_review() def remove_course(self, course): data = self.__get_json() data['courses'].remove(course) self.save(data) self.__update_review() def rename_course(slef, course, new_course): data = self.__get_json() data['courses'].remove(course) data['courses'].append(new_course) self.save(data) # change the word file names for doc_path in self.docx_path.ls(): docx_name = docx_path.stem course_title, name = [s.strip() for s in docx_name.split('-')] if(course_title == course): new_name = f"{new_course} - {name}.docx" os.rename(doc_path, self.docx_path/new_name) self.__update_review() def set_n_employees(self, n): data = self.__get_json() data['n_employees'] = n self.save(data) def get_courses(self): return self.__get_json()['courses'] def get_review(self): return [p.name for p in self.review_path.ls() if p.suffix == '.docx'] def get_scores(self): # scores = {} # surveyed = [] docx_paths = [p for p in self.docx_path.ls() if p.suffix == '.docx'] df = pd.DataFrame(columns=self.get_courses(), dtype=float) for docx_path in docx_paths: docx_data = self.get_docx_data(docx_path) course, name, avg_score = docx_data['course'], docx_data['name'], docx_data['avg_score'] df.loc[name,course] = avg_score return df def get_courses_docx(self): res = {} docx_paths = [p for p in self.docx_path.ls() if p.suffix == '.docx'] for docx_path in docx_paths: docx_data = self.get_docx_data(docx_path) course, name, avg_score = docx_data['course'], docx_data['name'], docx_data['avg_score'] if course not in res.keys(): res[course] = [] res[course].append(docx_path) return res def __get_json(self): with open(self.json_file, "r") as json_file: data = json.load(json_file) return data def save(self, data): ''' data: a dictionary of course (a list) and n_employees ''' if(sorted(list(data.keys())) != sorted(['courses', 'n_employees'])): raise ValueError('Invalid dictionary entries') with open(self.json_file, "w") as outfile: json.dump(data, outfile) self.notify() def get_docx_data(self, docx_path): data = {} docx_name = docx_path.stem course_title, name = [s.strip() for s in docx_name.split('-')] # read file tables_map = { "name": 0, "course_info": 1, "subject_opinion": slice(3,11), "expectation": 15, "support_material": 16, "duration_sat": 17 } docx = Document(docx_path) # get subject opinion and compute average score scores = {} for table in docx.tables[tables_map["subject_opinion"]]: for row in table.rows: cells = row.cells subject = cells[0].text rating = cells[2].text reason = cells[4].text # print(f"{len(rating)}, {len(subject)}, {len(reason)}, {len(cells)}") if(rating and subject): scores[subject] = float(rating) avg_score = sum(scores.values()) / len(scores) data['course'] = course_title data['name'] = name data['avg_score'] = avg_score data['course_doc'] = docx.tables[tables_map["course_info"]].rows[0].cells[1].text return data def submit_docx(self, name, course_title, uploader, year=2020): if not (bool(name) and bool(course_title) and bool(uploader.value)): raise ValueError('All fields must be filled.') #establish files paths based on selection docx_name = f"{course_title} - {name}.docx" if(course_title == 'Other'): # change docx_name based on content docx_name = f"tmp - {name}.docx" docx_file = self.review_path/docx_name else: docx_file = self.docx_path/docx_name # save it to file file = list(uploader.value.values())[0] content = file['content'] with open(docx_file, "wb") as new_file: b_array = bytearray(content) new_file.write(b_array) if(course_title == 'Other'): # read the file and rename it self.__rename_docx_from_data(docx_file) self.__update_review() def review(self, docx_name, course): docx_file = self.review_path/docx_name self.change_course_docx(docx_file, course) def change_course_docx(self, docx_file, course): ''' Assign a document in the review folder to a course ''' course_title, name = [s.strip() for s in docx_file.name.split('-')] docx_name_new = f"{course} - {name}" path = docx_file.parent docx_file_new = path/docx_name_new os.rename(docx_file, docx_file_new) self.__update_review() def __rename_docx_from_data(self, docx_file): course_title, name = [s.strip() for s in docx_file.name.split('-')] data = self.get_docx_data(docx_file) docx_name_new = f"{data["course_doc"]} - {name}" docx_file_new = self.review_path/docx_name_new os.rename(docx_file, docx_file_new) def __update_review(self): # move all docs with no course to review folder and changes coursename to the one in the docx for doc_path in self.docx_path.ls(): if doc_path.suffix != '.docx': continue docx_name = doc_path.stem course_title, name = [s.strip() for s in docx_name.split('-')] if(course_title not in self.get_courses()): new_docx_file = self.review_path/doc_path.name os.rename(doc_path, new_docx_file) self.__rename_docx_from_data(new_docx_file) # move all docs from review to main folder for doc_path in self.review_path.ls(): if doc_path.suffix != '.docx': continue docx_name = doc_path.stem course_title, name = [s.strip() for s in docx_name.split('-')] if(course_title in self.get_courses()): os.rename(doc_path, self.docx_path/doc_path.name) self.notify() def __data_modified(self): prev_check = self.last_check self.last_check = time.time() if os.path.getmtime(self.json_file) > prev_check: return True if os.path.getmtime(self.docx_path) > prev_check: return True if os.path.getmtime(self.review_path) > prev_check: return True return False def __poll_file(self): if self.__data_modified(): self.notify() def notify(self): for listener in self.listeners: listener.notify() def listen(self, l): self.listeners.append(l) # from https://stackoverflow.com/questions/12435211/python-threading-timer-repeat-function-every-n-seconds class PollThread(Thread): def __init__(self, on_poll, delay_sec=1, stop_event=Event()): Thread.__init__(self) self.stopped = stop_event self.on_poll = on_poll self.delay_sec = delay_sec def run(self): while not self.stopped.wait(self.delay_sec): self.on_poll() def stop(self): self.stopped.set()
import pandas as pd import os import sys from docx import Document from pathlib import Path from nbdev.showdoc import doc import ipywidgets as widgets import numpy as np from IPython.display import display from ipywidgets import HTML from functools import partial import openpyxl import json import sched, time import threading from threading import Thread, Event # database files root = Path('/data/f101_auto') db_path = root/'db' docx_path = db_path/'docx' review_path = docx_path/'review' xlsx_path = db_path/'xlsx' template_path = xlsx_path/'template.xlsx' # temporary files download_temp = root/'download/temp' download_temp_docx = download_temp/'docx' download_dir = root/'download/data' download_zip = root/'download/data.zip' class DB: def __init__(self, db_path=db_path): self.db_path = db_path self.json_path = db_path/'json' self.json_file = self.json_path/'db.json' self.docx_path = db_path/'docx' self.review_path = self.docx_path/'review' self.db_path.mkdir(parents=True, exist_ok=True) self.json_path.mkdir(parents=True, exist_ok=True) self.docx_path.mkdir(parents=True, exist_ok=True) self.review_path.mkdir(parents=True, exist_ok=True) self.listeners = [] if(not os.path.isfile(self.json_file)): data = {'n_employees': 0, 'courses':[]} self.save(data) # polling self.delay = 2 self.last_check = -1 self.stopFlag = Event() self.poll_thread = PollThread(on_poll=self.__poll_file, delay_sec=self.delay, stop_event=self.stopFlag) def start_poll(self): self.poll_thread.start() def stop_poll(self): self.stopFlag.set() def get_db(self): db = {} json_data = self.__get_json() scores_df = self.get_scores() db['scores'] = scores_df db['surveyed'] = list(scores_df.index) db['courses'] = json_data['courses'] db['n_employees'] = json_data['n_employees'] return db def add_course(self, course): data = self.__get_json() data['courses'].append(course) self.save(data) self.__update_review() def remove_course(self, course): data = self.__get_json() data['courses'].remove(course) self.save(data) self.__update_review() def rename_course(slef, course, new_course): data = self.__get_json() data['courses'].remove(course) data['courses'].append(new_course) self.save(data) # change the word file names for doc_path in self.docx_path.ls(): docx_name = docx_path.stem course_title, name = [s.strip() for s in docx_name.split('-')] if(course_title == course): new_name = f"{new_course} - {name}.docx" os.rename(doc_path, self.docx_path/new_name) self.__update_review() def set_n_employees(self, n): data = self.__get_json() data['n_employees'] = n self.save(data) def get_courses(self): return self.__get_json()['courses'] def get_review(self): return [p.name for p in self.review_path.ls() if p.suffix == '.docx'] def get_scores(self): # scores = {} # surveyed = [] docx_paths = [p for p in self.docx_path.ls() if p.suffix == '.docx'] df = pd.DataFrame(columns=self.get_courses(), dtype=float) for docx_path in docx_paths: docx_data = self.get_docx_data(docx_path) course, name, avg_score = docx_data['course'], docx_data['name'], docx_data['avg_score'] df.loc[name,course] = avg_score return df def get_courses_docx(self): res = {} docx_paths = [p for p in self.docx_path.ls() if p.suffix == '.docx'] for docx_path in docx_paths: docx_data = self.get_docx_data(docx_path) course, name, avg_score = docx_data['course'], docx_data['name'], docx_data['avg_score'] if course not in res.keys(): res[course] = [] res[course].append(docx_path) return res def __get_json(self): with open(self.json_file, "r") as json_file: data = json.load(json_file) return data def save(self, data): ''' data: a dictionary of course (a list) and n_employees ''' if(sorted(list(data.keys())) != sorted(['courses', 'n_employees'])): raise ValueError('Invalid dictionary entries') with open(self.json_file, "w") as outfile: json.dump(data, outfile) self.notify() def get_docx_data(self, docx_path): data = {} docx_name = docx_path.stem course_title, name = [s.strip() for s in docx_name.split('-')] # read file tables_map = { "name": 0, "course_info": 1, "subject_opinion": slice(3,11), "expectation": 15, "support_material": 16, "duration_sat": 17 } docx = Document(docx_path) # get subject opinion and compute average score scores = {} for table in docx.tables[tables_map["subject_opinion"]]: for row in table.rows: cells = row.cells subject = cells[0].text rating = cells[2].text reason = cells[4].text # print(f"{len(rating)}, {len(subject)}, {len(reason)}, {len(cells)}") if(rating and subject): scores[subject] = float(rating) avg_score = sum(scores.values()) / len(scores) data['course'] = course_title data['name'] = name data['avg_score'] = avg_score data['course_doc'] = docx.tables[tables_map["course_info"]].rows[0].cells[1].text return data def submit_docx(self, name, course_title, uploader, year=2020): if not (bool(name) and bool(course_title) and bool(uploader.value)): raise ValueError('All fields must be filled.') #establish files paths based on selection docx_name = f"{course_title} - {name}.docx" if(course_title == 'Other'): # change docx_name based on content docx_name = f"tmp - {name}.docx" docx_file = self.review_path/docx_name else: docx_file = self.docx_path/docx_name # save it to file file = list(uploader.value.values())[0] content = file['content'] with open(docx_file, "wb") as new_file: b_array = bytearray(content) new_file.write(b_array) if(course_title == 'Other'): # read the file and rename it self.__rename_docx_from_data(docx_file) self.__update_review() def review(self, docx_name, course): docx_file = self.review_path/docx_name self.change_course_docx(docx_file, course) def change_course_docx(self, docx_file, course): ''' Assign a document in the review folder to a course ''' course_title, name = [s.strip() for s in docx_file.name.split('-')] docx_name_new = f"{course} - {name}" path = docx_file.parent docx_file_new = path/docx_name_new os.rename(docx_file, docx_file_new) self.__update_review() def __rename_docx_from_data(self, docx_file): course_title, name = [s.strip() for s in docx_file.name.split('-')] data = self.get_docx_data(docx_file) docx_name_new = f"{data['course_doc']} - {name}" docx_file_new = self.review_path/docx_name_new os.rename(docx_file, docx_file_new) def __update_review(self): # move all docs with no course to review folder and changes coursename to the one in the docx for doc_path in self.docx_path.ls(): if doc_path.suffix != '.docx': continue docx_name = doc_path.stem course_title, name = [s.strip() for s in docx_name.split('-')] if(course_title not in self.get_courses()): new_docx_file = self.review_path/doc_path.name os.rename(doc_path, new_docx_file) self.__rename_docx_from_data(new_docx_file) # move all docs from review to main folder for doc_path in self.review_path.ls(): if doc_path.suffix != '.docx': continue docx_name = doc_path.stem course_title, name = [s.strip() for s in docx_name.split('-')] if(course_title in self.get_courses()): os.rename(doc_path, self.docx_path/doc_path.name) self.notify() def __data_modified(self): prev_check = self.last_check self.last_check = time.time() if os.path.getmtime(self.json_file) > prev_check: return True if os.path.getmtime(self.docx_path) > prev_check: return True if os.path.getmtime(self.review_path) > prev_check: return True return False def __poll_file(self): if self.__data_modified(): self.notify() def notify(self): for listener in self.listeners: listener.notify() def listen(self, l): self.listeners.append(l) # from https://stackoverflow.com/questions/12435211/python-threading-timer-repeat-function-every-n-seconds class PollThread(Thread): def __init__(self, on_poll, delay_sec=1, stop_event=Event()): Thread.__init__(self) self.stopped = stop_event self.on_poll = on_poll self.delay_sec = delay_sec def run(self): while not self.stopped.wait(self.delay_sec): self.on_poll() def stop(self): self.stopped.set()
class Song: song_lyrics=() def __init__(self, title="",author="",lyrics=()): self.__title=title self.__author=author self.__lyrics=lyrics #self.lines=lines print(f"New Song made {self.__title} by artist/group {self.__author}") def set_title(self, new_title): self.__title=new_title return self def set_author(self, new_author): self.__author=new_author return self def set_lyrics(self, new_lyrics): self.__lyrics=new_lyrics return self def get_title(self): return self.__title def get_author(self): return self.__author def get_lyrics(self): return self.__lyrics def sing(self, max_lines=-1): print(self.__title, self.__author,sep="-") if max_lines==-1: song_lyrics=self.__lyrics else: song_lyrics=self.__lyrics[:max_lines] for line in song_lyrics: print(line,sep="\n") return self def yell(self,max_lines=-1): print(self.__title, self.__author, sep="-") if max_lines == -1: song_lyrics = self.__lyrics else: song_lyrics = self.__lyrics[:max_lines] for line in song_lyrics: c = "" for item in line: c+=str(item).upper() print(c) return self class Rap(Song): def break_it(self,max_lines=-1,drop="yeah"): print(self.get_title(), self.get_author(), sep="-") song_lyrics = self.get_lyrics() if max_lines != -1: song_lyrics = song_lyrics[:max_lines] for word in song_lyrics: my_list=word.split() new_list="" for i in my_list: new_list+=i+" " +drop.upper()+" " print(new_list) return self ziemelmeita=Song("Ziemeļmeita","Jumprava",["Gāju meklēt ziemeļmeitu","Garu, tālu ceļu veicu"]) # print(ziemelmeita) # print(type(ziemelmeita)) print(ziemelmeita.sing(1).yell()) print(f"{"#"*50}") print(ziemelmeita.sing(1).yell().sing().yell()) zrap = Rap("Ziemeļmeita", "Jumprava", ["Gāju meklēt ziemeļmeitu","Garu, tālu ceļu veicu"]) zrap.break_it(10, "yah")
class Song: song_lyrics=() def __init__(self, title="",author="",lyrics=()): self.__title=title self.__author=author self.__lyrics=lyrics #self.lines=lines print(f"New Song made {self.__title} by artist/group {self.__author}") def set_title(self, new_title): self.__title=new_title return self def set_author(self, new_author): self.__author=new_author return self def set_lyrics(self, new_lyrics): self.__lyrics=new_lyrics return self def get_title(self): return self.__title def get_author(self): return self.__author def get_lyrics(self): return self.__lyrics def sing(self, max_lines=-1): print(self.__title, self.__author,sep="-") if max_lines==-1: song_lyrics=self.__lyrics else: song_lyrics=self.__lyrics[:max_lines] for line in song_lyrics: print(line,sep="\n") return self def yell(self,max_lines=-1): print(self.__title, self.__author, sep="-") if max_lines == -1: song_lyrics = self.__lyrics else: song_lyrics = self.__lyrics[:max_lines] for line in song_lyrics: c = "" for item in line: c+=str(item).upper() print(c) return self class Rap(Song): def break_it(self,max_lines=-1,drop="yeah"): print(self.get_title(), self.get_author(), sep="-") song_lyrics = self.get_lyrics() if max_lines != -1: song_lyrics = song_lyrics[:max_lines] for word in song_lyrics: my_list=word.split() new_list="" for i in my_list: new_list+=i+" " +drop.upper()+" " print(new_list) return self ziemelmeita=Song("Ziemeļmeita","Jumprava",["Gāju meklēt ziemeļmeitu","Garu, tālu ceļu veicu"]) # print(ziemelmeita) # print(type(ziemelmeita)) print(ziemelmeita.sing(1).yell()) print(f"{'#'*50}") print(ziemelmeita.sing(1).yell().sing().yell()) zrap = Rap("Ziemeļmeita", "Jumprava", ["Gāju meklēt ziemeļmeitu","Garu, tālu ceļu veicu"]) zrap.break_it(10, "yah")
# 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. # # thanks to the owner of X-tra-Telegram for tts fix # # Recode by @mrismanaziz # FROM Man-Userbot # t.me/SharingUserbot # """ Userbot module containing various scrapers. """ import asyncio import io import json import os import re import shutil import time from asyncio import sleep from os import popen from random import choice from re import findall, match from time import sleep from urllib.parse import quote_plus import asyncurban import barcode import qrcode import requests from barcode.writer import ImageWriter from bs4 import BeautifulSoup from emoji import get_emoji_regexp from google_trans_new import LANGUAGES, google_translator from gtts import gTTS from gtts.lang import tts_langs from humanize import naturalsize from requests import exceptions, get, post from search_engine_parser import YahooSearch as GoogleSearch from telethon.tl.types import DocumentAttributeAudio, MessageMediaPhoto from wikipedia import summary from wikipedia.exceptions import DisambiguationError, PageError from youtube_dl import YoutubeDL from youtube_dl.utils import ( ContentTooShortError, DownloadError, ExtractorError, GeoRestrictedError, MaxDownloadsReached, PostProcessingError, UnavailableVideoError, XAttrMetadataError, ) from youtube_search import YoutubeSearch from userbot import ( BOTLOG, BOTLOG_CHATID, CMD_HELP, LOGS, OCR_SPACE_API_KEY, REM_BG_API_KEY, TEMP_DOWNLOAD_DIRECTORY, bot, ) from userbot.events import register from userbot.utils import chrome, googleimagesdownload, options, progress CARBONLANG = "auto" TEMP_DOWNLOAD_DIRECTORY = "/root/userbot/.bin" async def ocr_space_file( filename, overlay=False, api_key=OCR_SPACE_API_KEY, language="eng" ): """OCR.space API request with local file. Python3.5 - not tested on 2.7 :param filename: Your file path & name. :param overlay: Is OCR.space overlay required in your response. Defaults to False. :param api_key: OCR.space API key. Defaults to 'helloworld'. :param language: Language code to be used in OCR. List of available language codes can be found on https://ocr.space/OCRAPI Defaults to 'eng'. :return: Result in JSON format. """ payload = { "isOverlayRequired": overlay, "apikey": api_key, "language": language, } with open(filename, "rb") as f: r = requests.post( "https://api.ocr.space/parse/image", files={filename: f}, data=payload, ) return r.json() DOGBIN_URL = "https://del.dog/" NEKOBIN_URL = "https://nekobin.com/" @register(outgoing=True, pattern=r"^\.crblang (.*)") async def setlang(prog): global CARBONLANG CARBONLANG = prog.pattern_match.group(1) await prog.edit(f"Bahasa untuk carbon.now.sh mulai {CARBONLANG}") @register(outgoing=True, pattern="^.carbon") async def carbon_api(e): """A Wrapper for carbon.now.sh""" await e.edit("`Processing..`") CARBON = "https://carbon.now.sh/?l={lang}&code={code}" global CARBONLANG textx = await e.get_reply_message() pcode = e.text if pcode[8:]: pcode = str(pcode[8:]) elif textx: pcode = str(textx.message) # Importing message to module code = quote_plus(pcode) # Converting to urlencoded await e.edit("`Processing..\n25%`") if os.path.isfile("/root/userbot/.bin/carbon.png"): os.remove("/root/userbot/.bin/carbon.png") url = CARBON.format(code=code, lang=CARBONLANG) chrome_options = Options() chrome_options.add_argument("--headless") chrome_options.binary_location = GOOGLE_CHROME_BIN chrome_options.add_argument("--window-size=1920x1080") chrome_options.add_argument("--disable-dev-shm-usage") chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-gpu") prefs = {"download.default_directory": "/root/userbot/.bin"} chrome_options.add_experimental_option("prefs", prefs) driver = webdriver.Chrome(executable_path=CHROME_DRIVER, options=chrome_options) driver.get(url) await e.edit("`Processing..\n50%`") download_path = "/root/userbot/.bin" driver.command_executor._commands["send_command"] = ( "POST", "/session/$sessionId/chromium/send_command", ) params = { "cmd": "Page.setDownloadBehavior", "params": {"behavior": "allow", "downloadPath": download_path}, } driver.execute("send_command", params) driver.find_element_by_xpath("//button[contains(text(),'Export')]").click() # driver.find_element_by_xpath("//button[contains(text(),'4x')]").click() # driver.find_element_by_xpath("//button[contains(text(),'PNG')]").click() await e.edit("`Processing..\n75%`") # Waiting for downloading while not os.path.isfile("/root/userbot/.bin/carbon.png"): await sleep(0.5) await e.edit("`Processing..\n100%`") file = "/root/userbot/.bin/carbon.png" await e.edit("`Uploading..`") await e.client.send_file( e.chat_id, file, caption="Made using [Carbon](https://carbon.now.sh/about/),\ \na project by [Dawn Labs](https://dawnlabs.io/)", force_document=True, reply_to=e.message.reply_to_msg_id, ) os.remove("/root/userbot/.bin/carbon.png") driver.quit() # Removing carbon.png after uploading await e.delete() # Deleting msg @register(outgoing=True, pattern=r"^\.img (.*)") async def img_sampler(event): """For .img command, search and return images matching the query.""" await event.edit("`Sedang Mencari Gambar Yang Anda Cari...`") query = event.pattern_match.group(1) lim = findall(r"lim=\d+", query) try: lim = lim[0] lim = lim.replace("lim=", "") query = query.replace("lim=" + lim[0], "") except IndexError: lim = 15 response = googleimagesdownload() # creating list of arguments arguments = { "keywords": query, "limit": lim, "format": "jpg", "no_directory": "no_directory", } # passing the arguments to the function paths = response.download(arguments) lst = paths[0][query] await event.client.send_file( await event.client.get_input_entity(event.chat_id), lst ) shutil.rmtree(os.path.dirname(os.path.abspath(lst[0]))) await event.delete() @register(outgoing=True, pattern=r"^\.currency (.*)") async def moni(event): input_str = event.pattern_match.group(1) input_sgra = input_str.split(" ") if len(input_sgra) != 3: return await event.edit("`Invalid syntax.`") try: number = float(input_sgra[0]) currency_from = input_sgra[1].upper() currency_to = input_sgra[2].upper() request_url = f"https://api.ratesapi.io/api/latest?base={currency_from}" current_response = get(request_url).json() if currency_to in current_response["rates"]: current_rate = float(current_response["rates"][currency_to]) rebmun = round(number * current_rate, 2) await event.edit( "{} {} = {} {}".format(number, currency_from, rebmun, currency_to) ) else: await event.edit( "`Sepertinya ini adalah mata uang asing, yang tidak dapat saya konversi sekarang.`" ) except Exception as e: await event.edit(str(e)) @register(outgoing=True, pattern=r"^\.google (.*)") async def gsearch(q_event): """For .google command, do a Google search.""" match = q_event.pattern_match.group(1) page = findall(r"page=\d+", match) try: page = page[0] page = page.replace("page=", "") match = match.replace("page=" + page[0], "") except IndexError: page = 1 try: search_args = (str(match), int(page)) gsearch = GoogleSearch() gresults = await gsearch.async_search(*search_args) msg = "" for i in range(5): try: title = gresults["titles"][i] link = gresults["links"][i] desc = gresults["descriptions"][i] msg += f"[{title}]({link})\n`{desc}`\n\n" except IndexError: break except BaseException as g_e: return await q_event.edit(f"**Error : ** `{g_e}`") await q_event.edit( "**Search Query:**\n`" + match + "`\n\n**Results:**\n" + msg, link_preview=False ) @register(outgoing=True, pattern=r"^\.wiki (.*)") async def wiki(wiki_q): """For .wiki command, fetch content from Wikipedia.""" match = wiki_q.pattern_match.group(1) try: summary(match) except DisambiguationError as error: await wiki_q.edit(f"Ditemukan halaman yang tidak ambigu.\n\n{error}") return except PageError as pageerror: await wiki_q.edit(f"Halaman tidak ditemukan.\n\n{pageerror}") return result = summary(match) if len(result) >= 4096: with open("output.txt", "w+") as file: file.write(result) await wiki_q.client.send_file( wiki_q.chat_id, "output.txt", reply_to=wiki_q.id, caption="`Output terlalu besar, dikirim sebagai file`", ) if os.path.exists("output.txt"): os.remove("output.txt") return await wiki_q.edit("**Search:**\n`" + match + "`\n\n**Result:**\n" + result) @register(outgoing=True, pattern=r"^\.ud (.*)") async def _(event): if event.fwd_from: return await event.edit("processing...") word = event.pattern_match.group(1) urban = asyncurban.UrbanDictionary() try: mean = await urban.get_word(word) await event.edit( "Text: **{}**\n\nBerarti: **{}**\n\nContoh: __{}__".format( mean.word, mean.definition, mean.example ) ) except asyncurban.WordNotFoundError: await event.edit("Tidak ada hasil untuk **" + word + "**") @register(outgoing=True, pattern=r"^\.tts(?: |$)([\s\S]*)") async def text_to_speech(query): """For .tts command, a wrapper for Google Text-to-Speech.""" if query.is_reply and not query.pattern_match.group(1): message = await query.get_reply_message() message = str(message.message) else: message = str(query.pattern_match.group(1)) if not message: return await query.edit( "**Berikan teks atau balas pesan untuk Text-to-Speech!**" ) await query.edit("`Processing...`") try: from userbot.modules.sql_helper.globals import gvarstatus except AttributeError: return await query.edit("**Running on Non-SQL mode!**") if gvarstatus("tts_lang") is not None: target_lang = str(gvarstatus("tts_lang")) else: target_lang = "id" try: gTTS(message, lang=target_lang) except AssertionError: return await query.edit( "**Teksnya kosong.**\n" "Tidak ada yang tersisa untuk dibicarakan setelah pra-pemrosesan, pembuatan token, dan pembersihan." ) except ValueError: return await query.edit("**Bahasa tidak didukung.**") except RuntimeError: return await query.edit("**Error saat memuat kamus bahasa.**") tts = gTTS(message, lang=target_lang) tts.save("k.mp3") with open("k.mp3", "rb") as audio: linelist = list(audio) linecount = len(linelist) if linecount == 1: tts = gTTS(message, lang=target_lang) tts.save("k.mp3") with open("k.mp3"): await query.client.send_file(query.chat_id, "k.mp3", voice_note=True) os.remove("k.mp3") await query.delete() @register(outgoing=True, pattern=r"^\.tr(?: |$)([\s\S]*)") async def translateme(trans): """For .tr command, translate the given text using Google Translate.""" if trans.is_reply and not trans.pattern_match.group(1): message = await trans.get_reply_message() message = str(message.message) else: message = str(trans.pattern_match.group(1)) if not message: return await trans.edit( "**Berikan teks atau balas pesan untuk diterjemahkan!**" ) await trans.edit("`Processing...`") translator = google_translator() try: from userbot.modules.sql_helper.globals import gvarstatus except AttributeError: return await trans.edit("**Running on Non-SQL mode!**") if gvarstatus("tr_lang") is not None: target_lang = str(gvarstatus("tr_lang")) else: target_lang = "id" try: reply_text = translator.translate(deEmojify(message), lang_tgt=target_lang) except ValueError: return await trans.edit( "**Bahasa yang dipilih tidak valid, Gunakan **`.lang tr <kode bahasa>`" ) try: source_lan = translator.detect(deEmojify(message))[1].title() except BaseException: source_lan = "(Google tidak memberikan info ini)" reply_text = f"**Terjemahan** Dari `{source_lan}` Ke `{LANGUAGES.get(target_lang).title()}`\n\n{reply_text}" await trans.edit(reply_text) @register(pattern=r"\.lang (tr|tts) (.*)", outgoing=True) async def lang(value): """For .lang command, change the default langauge of userbot scrapers.""" util = value.pattern_match.group(1).lower() try: from userbot.modules.sql_helper.globals import addgvar, delgvar, gvarstatus except AttributeError: return await lang.edit("**Running on Non-SQL mode!**") if util == "tr": scraper = "Translate" arg = value.pattern_match.group(2).lower() if arg not in LANGUAGES: return await value.edit( f"**Kode bahasa tidak valid!**\nKode bahasa yang tersedia:\n\n`{LANGUAGES}`" ) if gvarstatus("tr_lang"): delgvar("tr_lang") addgvar("tr_lang", arg) LANG = LANGUAGES[arg] elif util == "tts": scraper = "Text to Speech" arg = value.pattern_match.group(2).lower() if arg not in tts_langs(): return await value.edit( f"**Kode bahasa tidak valid!**\nKode bahasa yang tersedia:\n\n`{tts_langs()}`" ) if gvarstatus("tts_lang"): delgvar("tts_lang") addgvar("tts_lang", arg) LANG = tts_langs()[arg] await value.edit( f"**Bahasa untuk** `{scraper}` **diganti menjadi** `{LANG.title()}`" ) if BOTLOG: await value.client.send_message( BOTLOG_CHATID, f"**Bahasa untuk** `{scraper}` **diganti menjadi** `{LANG.title()}`", ) @register(outgoing=True, pattern=r"^\.yt (\d*) *(.*)") async def yt_search(video_q): """For .yt command, do a YouTube search from Telegram.""" if video_q.pattern_match.group(1) != "": counter = int(video_q.pattern_match.group(1)) if counter > 10: counter = int(10) if counter <= 0: counter = int(1) else: counter = int(5) query = video_q.pattern_match.group(2) if not query: await video_q.edit("`Masukkan keyword untuk dicari`") await video_q.edit("`Processing...`") try: results = json.loads(YoutubeSearch(query, max_results=counter).to_json()) except KeyError: return await video_q.edit( "`Pencarian Youtube menjadi lambat.\nTidak dapat mencari keyword ini!`" ) output = f"**Pencarian Keyword:**\n`{query}`\n\n**Hasil:**\n\n" for i in results["videos"]: try: title = i["title"] link = "https://youtube.com" + i["url_suffix"] channel = i["channel"] duration = i["duration"] views = i["views"] output += f"[{title}]({link})\nChannel: `{channel}`\nDuration: {duration} | {views}\n\n" except IndexError: break await video_q.edit(output, link_preview=False) @register(outgoing=True, pattern=r".yt(audio|video) (.*)") async def download_video(v_url): """For .yt command, download media from YouTube and many other sites.""" dl_type = v_url.pattern_match.group(1).lower() url = v_url.pattern_match.group(2) await v_url.edit("`Preparing to download...`") video = False audio = False if dl_type == "audio": opts = { "format": "bestaudio", "addmetadata": True, "key": "FFmpegMetadata", "writethumbnail": True, "prefer_ffmpeg": True, "geo_bypass": True, "nocheckcertificate": True, "postprocessors": [ { "key": "FFmpegExtractAudio", "preferredcodec": "mp3", "preferredquality": "320", } ], "outtmpl": "%(id)s.%(ext)s", "quiet": True, "logtostderr": False, } audio = True elif dl_type == "video": opts = { "format": "best", "addmetadata": True, "key": "FFmpegMetadata", "prefer_ffmpeg": True, "geo_bypass": True, "nocheckcertificate": True, "postprocessors": [ {"key": "FFmpegVideoConvertor", "preferedformat": "mp4"} ], "outtmpl": "%(id)s.%(ext)s", "logtostderr": False, "quiet": True, } video = True try: await v_url.edit("`Fetching data, please wait..`") with YoutubeDL(opts) as rip: rip_data = rip.extract_info(url) except DownloadError as DE: return await v_url.edit(f"`{str(DE)}`") except ContentTooShortError: return await v_url.edit("`The download content was too short.`") except GeoRestrictedError: return await v_url.edit( "`Video is not available from your geographic location " "due to geographic restrictions imposed by a website.`" ) except MaxDownloadsReached: return await v_url.edit("`Max-downloads limit has been reached.`") except PostProcessingError: return await v_url.edit("`There was an error during post processing.`") except UnavailableVideoError: return await v_url.edit("`Media is not available in the requested format.`") except XAttrMetadataError as XAME: return await v_url.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`") except ExtractorError: return await v_url.edit("`There was an error during info extraction.`") except Exception as e: return await v_url.edit(f"{str(type(e)): {str(e)}}") c_time = time.time() if audio: await v_url.edit( f"**Sedang Mengupload Lagu:**\n`{rip_data.get("title")}`" f"\nby **{rip_data.get("uploader")}**" ) f_name = rip_data.get("id") + ".mp3" with open(f_name, "rb") as f: result = await upload_file( client=v_url.client, file=f, name=f_name, progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress( d, t, v_url, c_time, "Uploading..", f"{rip_data["title"]}.mp3" ) ), ) img_extensions = ["jpg", "jpeg", "webp"] img_filenames = [ fn_img for fn_img in os.listdir() if any(fn_img.endswith(ext_img) for ext_img in img_extensions) ] thumb_image = img_filenames[0] metadata = extractMetadata(createParser(f_name)) duration = 0 if metadata.has("duration"): duration = metadata.get("duration").seconds await v_url.client.send_file( v_url.chat_id, result, supports_streaming=True, attributes=[ DocumentAttributeAudio( duration=duration, title=rip_data.get("title"), performer=rip_data.get("uploader"), ) ], thumb=thumb_image, ) os.remove(thumb_image) os.remove(f_name) await v_url.delete() elif video: await v_url.edit( f"**Sedang Mengupload Video:**\n`{rip_data.get("title")}`" f"\nby **{rip_data.get("uploader")}**" ) f_name = rip_data.get("id") + ".mp4" with open(f_name, "rb") as f: result = await upload_file( client=v_url.client, file=f, name=f_name, progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress( d, t, v_url, c_time, "Uploading..", f"{rip_data["title"]}.mp4" ) ), ) thumb_image = await get_video_thumb(f_name, "thumb.png") metadata = extractMetadata(createParser(f_name)) duration = 0 width = 0 height = 0 if metadata.has("duration"): duration = metadata.get("duration").seconds if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") await v_url.client.send_file( v_url.chat_id, result, thumb=thumb_image, attributes=[ DocumentAttributeVideo( duration=duration, w=width, h=height, supports_streaming=True, ) ], caption=rip_data["title"], ) os.remove(f_name) os.remove(thumb_image) await v_url.delete() def deEmojify(inputString): """Remove emojis and other non-safe characters from string""" return get_emoji_regexp().sub("", inputString) @register(outgoing=True, pattern="^.rbg(?: |$)(.*)") async def kbg(remob): """For .rbg command, Remove Image Background.""" if REM_BG_API_KEY is None: await remob.edit( "`Error: Remove.BG API key missing! Add it to environment vars or config.env.`" ) return input_str = remob.pattern_match.group(1) message_id = remob.message.id if remob.reply_to_msg_id: message_id = remob.reply_to_msg_id reply_message = await remob.get_reply_message() await remob.edit("`Processing..`") try: if isinstance( reply_message.media, MessageMediaPhoto ) or "image" in reply_message.media.document.mime_type.split("/"): downloaded_file_name = await remob.client.download_media( reply_message, TEMP_DOWNLOAD_DIRECTORY ) await remob.edit("`Removing background from this image..`") output_file_name = await ReTrieveFile(downloaded_file_name) os.remove(downloaded_file_name) else: await remob.edit("`Bagaimana cara menghapus latar belakang ini ?`") except Exception as e: await remob.edit(str(e)) return elif input_str: await remob.edit( f"`Removing background from online image hosted at`\n{input_str}" ) output_file_name = await ReTrieveURL(input_str) else: await remob.edit("`Saya butuh sesuatu untuk menghapus latar belakang.`") return contentType = output_file_name.headers.get("content-type") if "image" in contentType: with io.BytesIO(output_file_name.content) as remove_bg_image: remove_bg_image.name = "removed_bg.png" await remob.client.send_file( remob.chat_id, remove_bg_image, caption="Support @SharingUserbot", force_document=True, reply_to=message_id, ) await remob.delete() else: await remob.edit( "**Error (Invalid API key, I guess ?)**\n`{}`".format( output_file_name.content.decode("UTF-8") ) ) # this method will call the API, and return in the appropriate format # with the name provided. async def ReTrieveFile(input_file_name): headers = { "X-API-Key": REM_BG_API_KEY, } files = { "image_file": (input_file_name, open(input_file_name, "rb")), } return requests.post( "https://api.remove.bg/v1.0/removebg", headers=headers, files=files, allow_redirects=True, stream=True, ) async def ReTrieveURL(input_url): headers = { "X-API-Key": REM_BG_API_KEY, } data = {"image_url": input_url} return requests.post( "https://api.remove.bg/v1.0/removebg", headers=headers, data=data, allow_redirects=True, stream=True, ) @register(pattern=r".ocr (.*)", outgoing=True) async def ocr(event): if not OCR_SPACE_API_KEY: return await event.edit( "`Error: OCR.Space API key is missing! Add it to environment variables or config.env.`" ) await event.edit("`Sedang Membaca...`") if not os.path.isdir(TEMP_DOWNLOAD_DIRECTORY): os.makedirs(TEMP_DOWNLOAD_DIRECTORY) lang_code = event.pattern_match.group(1) downloaded_file_name = await bot.download_media( await event.get_reply_message(), TEMP_DOWNLOAD_DIRECTORY ) test_file = await ocr_space_file(filename=downloaded_file_name, language=lang_code) try: ParsedText = test_file["ParsedResults"][0]["ParsedText"] except BaseException: await event.edit( "`Tidak bisa membacanya.`\n`Saya rasa saya perlu kacamata baru.`" ) else: await event.edit(f"`Inilah yang bisa saya baca darinya:`\n\n{ParsedText}") os.remove(downloaded_file_name) @register(pattern=r"^.decode$", outgoing=True) async def parseqr(qr_e): """For .decode command, get QR Code/BarCode content from the replied photo.""" downloaded_file_name = await qr_e.client.download_media( await qr_e.get_reply_message() ) # parse the Official ZXing webpage to decode the QRCode command_to_exec = [ "curl", "-X", "POST", "-F", "f=@" + downloaded_file_name + "", "https://zxing.org/w/decode", ] process = await asyncio.create_subprocess_exec( *command_to_exec, # stdout must a pipe to be accessible as process.stdout stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) # Wait for the subprocess to finish stdout, stderr = await process.communicate() e_response = stderr.decode().strip() t_response = stdout.decode().strip() os.remove(downloaded_file_name) if not t_response: LOGS.info(e_response) LOGS.info(t_response) return await qr_e.edit("Gagal untuk decode.") soup = BeautifulSoup(t_response, "html.parser") qr_contents = soup.find_all("pre")[0].text await qr_e.edit(qr_contents) @register(pattern=r".barcode(?: |$)([\s\S]*)", outgoing=True) async def bq(event): """For .barcode command, genrate a barcode containing the given content.""" await event.edit("`Processing..`") input_str = event.pattern_match.group(1) message = "SYNTAX: `.barcode <long text to include>`" reply_msg_id = event.message.id if input_str: message = input_str elif event.reply_to_msg_id: previous_message = await event.get_reply_message() reply_msg_id = previous_message.id if previous_message.media: downloaded_file_name = await event.client.download_media(previous_message) m_list = None with open(downloaded_file_name, "rb") as fd: m_list = fd.readlines() message = "".join(m.decode("UTF-8") + "\r\n" for m in m_list) os.remove(downloaded_file_name) else: message = previous_message.message else: return event.edit("SYNTAX: `.barcode <long text to include>`") bar_code_type = "code128" try: bar_code_mode_f = barcode.get(bar_code_type, message, writer=ImageWriter()) filename = bar_code_mode_f.save(bar_code_type) await event.client.send_file(event.chat_id, filename, reply_to=reply_msg_id) os.remove(filename) except Exception as e: return await event.edit(str(e)) await event.delete() @register(pattern=r".makeqr(?: |$)([\s\S]*)", outgoing=True) async def make_qr(makeqr): """For .makeqr command, make a QR Code containing the given content.""" input_str = makeqr.pattern_match.group(1) message = "SYNTAX: `.makeqr <long text to include>`" reply_msg_id = None if input_str: message = input_str elif makeqr.reply_to_msg_id: previous_message = await makeqr.get_reply_message() reply_msg_id = previous_message.id if previous_message.media: downloaded_file_name = await makeqr.client.download_media(previous_message) m_list = None with open(downloaded_file_name, "rb") as file: m_list = file.readlines() message = "".join(media.decode("UTF-8") + "\r\n" for media in m_list) os.remove(downloaded_file_name) else: message = previous_message.message qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4, ) qr.add_data(message) qr.make(fit=True) img = qr.make_image(fill_color="black", back_color="white") img.save("img_file.webp", "PNG") await makeqr.client.send_file( makeqr.chat_id, "img_file.webp", reply_to=reply_msg_id ) os.remove("img_file.webp") await makeqr.delete() @register(outgoing=True, pattern=r"^.direct(?: |$)([\s\S]*)") async def direct_link_generator(request): """direct links generator""" await request.edit("`Processing...`") textx = await request.get_reply_message() message = request.pattern_match.group(1) if message: pass elif textx: message = textx.text else: await request.edit("`Usage: .direct <url>`") return reply = "" links = re.findall(r"\bhttps?://.*\.\S+", message) if not links: reply = "`No links found!`" await request.edit(reply) for link in links: if "drive.google.com" in link: reply += gdrive(link) elif "zippyshare.com" in link: reply += zippy_share(link) elif "yadi.sk" in link: reply += yandex_disk(link) elif "cloud.mail.ru" in link: reply += cm_ru(link) elif "mediafire.com" in link: reply += mediafire(link) elif "sourceforge.net" in link: reply += sourceforge(link) elif "osdn.net" in link: reply += osdn(link) elif "github.com" in link: reply += github(link) elif "androidfilehost.com" in link: reply += androidfilehost(link) else: reply += re.findall(r"\bhttps?://(.*?[^/]+)", link)[0] + "is not supported" await request.edit(reply) def gdrive(url: str) -> str: """GDrive direct links generator""" drive = "https://drive.google.com" try: link = re.findall(r"\bhttps?://drive\.google\.com\S+", url)[0] except IndexError: reply = "`No Google drive links found`\n" return reply file_id = "" reply = "" if link.find("view") != -1: file_id = link.split("/")[-2] elif link.find("open?id=") != -1: file_id = link.split("open?id=")[1].strip() elif link.find("uc?id=") != -1: file_id = link.split("uc?id=")[1].strip() url = f"{drive}/uc?export=download&id={file_id}" download = requests.get(url, stream=True, allow_redirects=False) cookies = download.cookies try: # In case of small file size, Google downloads directly dl_url = download.headers["location"] if "accounts.google.com" in dl_url: # non-public file reply += "`Link is not public!`\n" return reply name = "Direct Download Link" except KeyError: # In case of download warning page page = BeautifulSoup(download.content, "lxml") export = drive + page.find("a", {"id": "uc-download-link"}).get("href") name = page.find("span", {"class": "uc-name-size"}).text response = requests.get( export, stream=True, allow_redirects=False, cookies=cookies ) dl_url = response.headers["location"] if "accounts.google.com" in dl_url: reply += "Link is not public!" return reply reply += f"[{name}]({dl_url})\n" return reply def zippy_share(url: str) -> str: link = re.findall("https:/.(.*?).zippyshare", url)[0] response_content = (requests.get(url)).content bs_obj = BeautifulSoup(response_content, "lxml") try: js_script = bs_obj.find("div", {"class": "center",}).find_all( "script" )[1] except BaseException: js_script = bs_obj.find("div", {"class": "right",}).find_all( "script" )[0] js_content = re.findall(r'\.href.=."/(.*?)";', str(js_script)) js_content = 'var x = "/' + js_content[0] + '"' evaljs = EvalJs() setattr(evaljs, "x", None) evaljs.execute(js_content) js_content = getattr(evaljs, "x") dl_url = f"https://{link}.zippyshare.com{js_content}" file_name = basename(dl_url) return f"[{urllib.parse.unquote_plus(file_name)}]({dl_url})" def yandex_disk(url: str) -> str: """Yandex.Disk direct links generator Based on https://github.com/wldhx/yadisk-direct""" reply = "" try: link = re.findall(r"\bhttps?://.*yadi\.sk\S+", url)[0] except IndexError: reply = "`No Yandex.Disk links found`\n" return reply api = "https://cloud-api.yandex.net/v1/disk/public/resources/download?public_key={}" try: dl_url = requests.get(api.format(link)).json()["href"] name = dl_url.split("filename=")[1].split("&disposition")[0] reply += f"[{name}]({dl_url})\n" except KeyError: reply += "`Error: File not found / Download limit reached`\n" return reply return reply def cm_ru(url: str) -> str: """cloud.mail.ru direct links generator Using https://github.com/JrMasterModelBuilder/cmrudl.py""" reply = "" try: link = re.findall(r"\bhttps?://.*cloud\.mail\.ru\S+", url)[0] except IndexError: reply = "`No cloud.mail.ru links found`\n" return reply command = f"bin/cmrudl -s {link}" result = popen(command).read() result = result.splitlines()[-1] try: data = json.loads(result) except json.decoder.JSONDecodeError: reply += "`Error: Can't extract the link`\n" return reply dl_url = data["download"] name = data["file_name"] size = naturalsize(int(data["file_size"])) reply += f"[{name} ({size})]({dl_url})\n" return reply def mediafire(url: str) -> str: """MediaFire direct links generator""" try: link = re.findall(r"\bhttps?://.*mediafire\.com\S+", url)[0] except IndexError: reply = "`No MediaFire links found`\n" return reply reply = "" page = BeautifulSoup(requests.get(link).content, "lxml") info = page.find("a", {"aria-label": "Download file"}) dl_url = info.get("href") size = re.findall(r"\(.*\)", info.text)[0] name = page.find("div", {"class": "filename"}).text reply += f"[{name} {size}]({dl_url})\n" return reply def sourceforge(url: str) -> str: """SourceForge direct links generator""" try: link = re.findall(r"\bhttps?://.*sourceforge\.net\S+", url)[0] except IndexError: reply = "`No SourceForge links found`\n" return reply file_path = re.findall(r"files(.*)/download", link)[0] reply = f"Mirrors for __{file_path.split("/")[-1]}__\n" project = re.findall(r"projects?/(.*?)/files", link)[0] mirrors = ( f"https://sourceforge.net/settings/mirror_choices?" f"projectname={project}&filename={file_path}" ) page = BeautifulSoup(requests.get(mirrors).content, "html.parser") info = page.find("ul", {"id": "mirrorList"}).findAll("li") for mirror in info[1:]: name = re.findall(r"\((.*)\)", mirror.text.strip())[0] dl_url = ( f'https://{mirror['id']}.dl.sourceforge.net/project/{project}/{file_path}' ) reply += f"[{name}]({dl_url}) " return reply def osdn(url: str) -> str: """OSDN direct links generator""" osdn_link = "https://osdn.net" try: link = re.findall(r"\bhttps?://.*osdn\.net\S+", url)[0] except IndexError: reply = "`No OSDN links found`\n" return reply page = BeautifulSoup(requests.get(link, allow_redirects=True).content, "lxml") info = page.find("a", {"class": "mirror_link"}) link = urllib.parse.unquote(osdn_link + info["href"]) reply = f"Mirrors for __{link.split("/")[-1]}__\n" mirrors = page.find("form", {"id": "mirror-select-form"}).findAll("tr") for data in mirrors[1:]: mirror = data.find("input")["value"] name = re.findall(r"\((.*)\)", data.findAll("td")[-1].text.strip())[0] dl_url = re.sub(r"m=(.*)&f", f"m={mirror}&f", link) reply += f"[{name}]({dl_url}) " return reply def github(url: str) -> str: """GitHub direct links generator""" try: link = re.findall(r"\bhttps?://.*github\.com.*releases\S+", url)[0] except IndexError: reply = "`No GitHub Releases links found`\n" return reply reply = "" dl_url = "" download = requests.get(url, stream=True, allow_redirects=False) try: dl_url = download.headers["location"] except KeyError: reply += "`Error: Can't extract the link`\n" name = link.split("/")[-1] reply += f"[{name}]({dl_url}) " return reply def androidfilehost(url: str) -> str: """AFH direct links generator""" try: link = re.findall(r"\bhttps?://.*androidfilehost.*fid.*\S+", url)[0] except IndexError: reply = "`No AFH links found`\n" return reply fid = re.findall(r"\?fid=(.*)", link)[0] session = requests.Session() user_agent = useragent() headers = {"user-agent": user_agent} res = session.get(link, headers=headers, allow_redirects=True) headers = { "origin": "https://androidfilehost.com", "accept-encoding": "gzip, deflate, br", "accept-language": "en-US,en;q=0.9", "user-agent": user_agent, "content-type": "application/x-www-form-urlencoded; charset=UTF-8", "x-mod-sbb-ctype": "xhr", "accept": "*/*", "referer": f"https://androidfilehost.com/?fid={fid}", "authority": "androidfilehost.com", "x-requested-with": "XMLHttpRequest", } data = {"submit": "submit", "action": "getdownloadmirrors", "fid": f"{fid}"} mirrors = None reply = "" error = "`Error: Can't find Mirrors for the link`\n" try: req = session.post( "https://androidfilehost.com/libs/otf/mirrors.otf.php", headers=headers, data=data, cookies=res.cookies, ) mirrors = req.json()["MIRRORS"] except (json.decoder.JSONDecodeError, TypeError): reply += error if not mirrors: reply += error return reply for item in mirrors: name = item["name"] dl_url = item["url"] reply += f"[{name}]({dl_url}) " return reply def useragent(): """ useragent random setter """ useragents = BeautifulSoup( requests.get( "https://developers.whatismybrowser.com/" "useragents/explore/operating_system_name/android/" ).content, "lxml", ).findAll("td", {"class": "useragent"}) user_agent = choice(useragents) return user_agent.text @register(outgoing=True, pattern=r"^\.paste(?: |$)([\s\S]*)") async def paste(pstl): dogbin_final_url = "" match = pstl.pattern_match.group(1).strip() reply_id = pstl.reply_to_msg_id if not match and not reply_id: return await pstl.edit("`Elon Musk said I cannot paste void.`") if match: message = match elif reply_id: message = await pstl.get_reply_message() if message.media: downloaded_file_name = await pstl.client.download_media( message, TEMP_DOWNLOAD_DIRECTORY, ) m_list = None with open(downloaded_file_name, "rb") as fd: m_list = fd.readlines() message = "".join(m.decode("UTF-8") for m in m_list) os.remove(downloaded_file_name) else: message = message.message # Dogbin await pstl.edit("`Pasting text . . .`") resp = post(DOGBIN_URL + "documents", data=message.encode("utf-8")) if resp.status_code == 200: response = resp.json() key = response["key"] dogbin_final_url = DOGBIN_URL + key if response["isUrl"]: reply_text = ( "`Pasted successfully!`\n\n" f"[Shortened URL]({dogbin_final_url})\n\n" "`Original(non-shortened) URLs`\n" f"[Dogbin URL]({DOGBIN_URL}v/{key})\n" f"[View RAW]({DOGBIN_URL}raw/{key})" ) else: reply_text = ( "`Pasted successfully!`\n\n" f"[Dogbin URL]({dogbin_final_url})\n" f"[View RAW]({DOGBIN_URL}raw/{key})" ) else: reply_text = "`Failed to reach Dogbin`" await pstl.edit(reply_text) @register(outgoing=True, pattern=r"^\.getpaste(?: |$)(.*)") async def get_dogbin_content(dog_url): textx = await dog_url.get_reply_message() message = dog_url.pattern_match.group(1) await dog_url.edit("`Getting dogbin content...`") if textx: message = str(textx.message) format_normal = f"{DOGBIN_URL}" format_view = f"{DOGBIN_URL}v/" if message.startswith(format_view): message = message[len(format_view) :] elif message.startswith(format_normal): message = message[len(format_normal) :] elif message.startswith("del.dog/"): message = message[len("del.dog/") :] else: return await dog_url.edit("`Is that even a dogbin url?`") resp = get(f"{DOGBIN_URL}raw/{message}") try: resp.raise_for_status() except exceptions.HTTPError as HTTPErr: await dog_url.edit( "Request returned an unsuccessful status code.\n\n" + str(HTTPErr) ) return except exceptions.Timeout as TimeoutErr: await dog_url.edit("Request timed out." + str(TimeoutErr)) return except exceptions.TooManyRedirects as RedirectsErr: await dog_url.edit( "Request exceeded the configured number of maximum redirections." + str(RedirectsErr) ) return reply_text = ( "`Fetched dogbin URL content successfully!`" "\n\n`Content:` " + resp.text ) await dog_url.edit(reply_text) @register(outgoing=True, pattern=r"^\.neko(?: |$)([\s\S]*)") async def neko(nekobin): """For .paste command, pastes the text directly to dogbin.""" nekobin_final_url = "" match = nekobin.pattern_match.group(1).strip() reply_id = nekobin.reply_to_msg_id if not match and not reply_id: return await pstl.edit("`Cannot paste text.`") if match: message = match elif reply_id: message = await nekobin.get_reply_message() if message.media: downloaded_file_name = await nekobin.client.download_media( message, TEMP_DOWNLOAD_DIRECTORY, ) m_list = None with open(downloaded_file_name, "rb") as fd: m_list = fd.readlines() message = "".join(m.decode("UTF-8") for m in m_list) os.remove(downloaded_file_name) else: message = message.text # Nekobin await nekobin.edit("`Pasting text . . .`") resp = post(NEKOBIN_URL + "api/documents", json={"content": message}) if resp.status_code == 201: response = resp.json() key = response["result"]["key"] nekobin_final_url = NEKOBIN_URL + key reply_text = ( "`Pasted successfully!`\n\n" f"[Nekobin URL]({nekobin_final_url})\n" f"[View RAW]({NEKOBIN_URL}raw/{key})" ) else: reply_text = "`Gagal menjangkau Nekobin`" await nekobin.edit(reply_text) @register(pattern=r"^\.ss (.*)", outgoing=True) async def capture(url): """For .ss command, capture a website's screenshot and send the photo.""" await url.edit("`Processing...`") chrome_options = await options() chrome_options.add_argument("--test-type") chrome_options.add_argument("--ignore-certificate-errors") chrome_options.arguments.remove("--window-size=1920x1080") driver = await chrome(chrome_options=chrome_options) input_str = url.pattern_match.group(1) link_match = match(r"\bhttps?://.*\.\S+", input_str) if link_match: link = link_match.group() else: return await url.edit("`I need a valid link to take screenshots from.`") driver.get(link) height = driver.execute_script( "return Math.max(document.body.scrollHeight, document.body.offsetHeight, " "document.documentElement.clientHeight, document.documentElement.scrollHeight, " "document.documentElement.offsetHeight);" ) width = driver.execute_script( "return Math.max(document.body.scrollWidth, document.body.offsetWidth, " "document.documentElement.clientWidth, document.documentElement.scrollWidth, " "document.documentElement.offsetWidth);" ) driver.set_window_size(width + 125, height + 125) wait_for = height / 1000 await url.edit( "`Generating screenshot of the page...`" f"\n`Height of page = {height}px`" f"\n`Width of page = {width}px`" f"\n`Waiting ({int(wait_for)}s) for the page to load.`" ) await sleep(int(wait_for)) im_png = driver.get_screenshot_as_png() # saves screenshot of entire page driver.quit() message_id = url.message.id if url.reply_to_msg_id: message_id = url.reply_to_msg_id with io.BytesIO(im_png) as out_file: out_file.name = "screencapture.png" await url.edit("`Uploading screenshot as file..`") await url.client.send_file( url.chat_id, out_file, caption=input_str, force_document=True, reply_to=message_id, ) await url.delete() CMD_HELP.update( { "tts": "**Plugin : **`tts`\ \n\n • **Syntax :** `.tts` <text/reply>\ \n • **Function : **Menerjemahkan teks ke ucapan untuk bahasa yang disetel. \ \n\n • **NOTE :** Gunakan .lang tts <kode bahasa> untuk menyetel bahasa untuk tr **(Bahasa Default adalah bahasa Indonesia)**\ " } ) CMD_HELP.update( { "translate": "**Plugin : **`Terjemahan`\ \n\n • **Syntax :** `.tr` <text/reply>\ \n • **Function : **Menerjemahkan teks ke bahasa yang disetel.\ \n\n • **NOTE :** Gunakan .lang tr <kode bahasa> untuk menyetel bahasa untuk tr **(Bahasa Default adalah bahasa Indonesia)**\ " } ) CMD_HELP.update( { "paste": "**Plugin : **`paste`\ \n\n • **Syntax :** `.paste` <text/reply>\ \n • **Function : **Buat paste atau url yang dipersingkat menggunakan dog in.\ \n\n • **Syntax :** `.getpaste` <text/reply>\ \n • **Function : **Buat paste atau url yang dipersingkat menggunakan dog in.\ \n\n • **Syntax :** `.neko` <text/reply>\ \n • **Function : **Buat paste atau url yang dipersingkat menggunakan dog in.\ " } ) CMD_HELP.update( { "carbon": "**Plugin : **`carbon`\ \n\n • **Syntax :** `.carbon` <text/reply>\ \n • **Function : **Percantik kode Anda menggunakan carbon.now.sh\ \n\n • **NOTE :** Gunakan .crblang <text> untuk menyetel bahasa kode Anda.\ " } ) CMD_HELP.update( { "removebg": "**Plugin : **`removebg`\ \n\n • **Syntax :** `.rbg` <Tautan ke Gambar> atau balas gambar apa pun (Peringatan: tidak berfungsi pada stiker.)\ \n • **Function : **Menghapus latar belakang gambar, menggunakan API remove.bg\ " } ) CMD_HELP.update( { "ocr": "**Plugin : **`ocr`\ \n\n • **Syntax :** `.ocr` <kode bahasa>\ \n • **Function : **Balas gambar atau stiker untuk mengekstrak teks media tersebut.\ " } ) CMD_HELP.update( { "youtube": "**Plugin : **`youtube`\ \n\n • **Syntax :** `.yt` <jumlah> <query>\ \n • **Function : **Melakukan Pencarian YouTube. Dapat menentukan jumlah hasil yang dibutuhkan (default adalah 5)\ " } ) CMD_HELP.update( { "google": "**Plugin : **`google`\ \n\n • **Syntax :** `.google` <query>\ \n • **Function : **Melakukan pencarian di google.\ " } ) CMD_HELP.update( { "wiki": "**Plugin : **`wiki`\ \n\n • **Syntax :** `.wiki` <query>\ \n • **Function : **Melakukan pencarian di Wikipedia.\ " } ) CMD_HELP.update( { "direct": "**Plugin : **`direct`\ \n\n • **Syntax :** `.direct` <url>\ \n • **Function : **Balas tautan atau tempel URL untuk membuat tautan unduhan langsung.\ \n\n • **Supported URL :** `Google Drive` - `Cloud Mail` - `Yandex.Disk` - `AFH` - `ZippyShare` - `MediaFire` - `SourceForge` - `OSDN` - `GitHub`\ " } ) CMD_HELP.update( { "barcode": "**Plugin : **`barcode`\ \n\n • **Syntax :** `.barcode` <content>\ \n • **Function :** Buat Kode Batang dari konten yang diberikan.\ \n\n • **Example :** `.barcode www.google.com`\ \n\n • **Syntax :** `.makeqr` <content>\ \n • **Function :** Buat Kode QR dari konten yang diberikan.\ \n\n • **Example :** `.makeqr www.google.com`\ \n\n • **NOTE :** Gunakan .decode <reply to barcode / qrcode> untuk mendapatkan konten yang didekodekan.\ " } ) CMD_HELP.update( { "image_search": "**Plugin : **`image_search`\ \n\n • **Syntax :** `.img` <search_query>\ \n • **Function : **Melakukan pencarian gambar di Google dan menampilkan 15 gambar.\ " } ) CMD_HELP.update( { "ytdl": "**Plugin : **`ytdl`\ \n\n • **Syntax :** `.ytaudio` <url>\ \n • **Function : **Untuk Mendownload lagu dari YouTube.\ \n\n • **Syntax :** `.ytvideo` <url>\ \n • **Function : **Untuk Mendownload video dari YouTube.\ " } ) CMD_HELP.update( { "screenshot": "**Plugin : **`screenshot`\ \n\n • **Syntax :** `.ss` <url>\ \n • **Function : **Mengambil tangkapan layar dari situs web dan mengirimkan tangkapan layar.\ \n • **Example : .ss http://www.google.com\ " } ) CMD_HELP.update( { "currency": "**Plugin : **`currency`\ \n\n • **Syntax :** `.currency` <amount> <from> <to>\ \n • **Function : **Mengonversi berbagai mata uang untuk Anda.\ " } ) CMD_HELP.update( { "ud": "**Plugin : **`Urban Dictionary`\ \n\n • **Syntax :** `.ud` <query>\ \n • **Function : **Melakukan pencarian di Urban Dictionary.\ " } )
# 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. # # thanks to the owner of X-tra-Telegram for tts fix # # Recode by @mrismanaziz # FROM Man-Userbot # t.me/SharingUserbot # """ Userbot module containing various scrapers. """ import asyncio import io import json import os import re import shutil import time from asyncio import sleep from os import popen from random import choice from re import findall, match from time import sleep from urllib.parse import quote_plus import asyncurban import barcode import qrcode import requests from barcode.writer import ImageWriter from bs4 import BeautifulSoup from emoji import get_emoji_regexp from google_trans_new import LANGUAGES, google_translator from gtts import gTTS from gtts.lang import tts_langs from humanize import naturalsize from requests import exceptions, get, post from search_engine_parser import YahooSearch as GoogleSearch from telethon.tl.types import DocumentAttributeAudio, MessageMediaPhoto from wikipedia import summary from wikipedia.exceptions import DisambiguationError, PageError from youtube_dl import YoutubeDL from youtube_dl.utils import ( ContentTooShortError, DownloadError, ExtractorError, GeoRestrictedError, MaxDownloadsReached, PostProcessingError, UnavailableVideoError, XAttrMetadataError, ) from youtube_search import YoutubeSearch from userbot import ( BOTLOG, BOTLOG_CHATID, CMD_HELP, LOGS, OCR_SPACE_API_KEY, REM_BG_API_KEY, TEMP_DOWNLOAD_DIRECTORY, bot, ) from userbot.events import register from userbot.utils import chrome, googleimagesdownload, options, progress CARBONLANG = "auto" TEMP_DOWNLOAD_DIRECTORY = "/root/userbot/.bin" async def ocr_space_file( filename, overlay=False, api_key=OCR_SPACE_API_KEY, language="eng" ): """OCR.space API request with local file. Python3.5 - not tested on 2.7 :param filename: Your file path & name. :param overlay: Is OCR.space overlay required in your response. Defaults to False. :param api_key: OCR.space API key. Defaults to 'helloworld'. :param language: Language code to be used in OCR. List of available language codes can be found on https://ocr.space/OCRAPI Defaults to 'eng'. :return: Result in JSON format. """ payload = { "isOverlayRequired": overlay, "apikey": api_key, "language": language, } with open(filename, "rb") as f: r = requests.post( "https://api.ocr.space/parse/image", files={filename: f}, data=payload, ) return r.json() DOGBIN_URL = "https://del.dog/" NEKOBIN_URL = "https://nekobin.com/" @register(outgoing=True, pattern=r"^\.crblang (.*)") async def setlang(prog): global CARBONLANG CARBONLANG = prog.pattern_match.group(1) await prog.edit(f"Bahasa untuk carbon.now.sh mulai {CARBONLANG}") @register(outgoing=True, pattern="^.carbon") async def carbon_api(e): """A Wrapper for carbon.now.sh""" await e.edit("`Processing..`") CARBON = "https://carbon.now.sh/?l={lang}&code={code}" global CARBONLANG textx = await e.get_reply_message() pcode = e.text if pcode[8:]: pcode = str(pcode[8:]) elif textx: pcode = str(textx.message) # Importing message to module code = quote_plus(pcode) # Converting to urlencoded await e.edit("`Processing..\n25%`") if os.path.isfile("/root/userbot/.bin/carbon.png"): os.remove("/root/userbot/.bin/carbon.png") url = CARBON.format(code=code, lang=CARBONLANG) chrome_options = Options() chrome_options.add_argument("--headless") chrome_options.binary_location = GOOGLE_CHROME_BIN chrome_options.add_argument("--window-size=1920x1080") chrome_options.add_argument("--disable-dev-shm-usage") chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-gpu") prefs = {"download.default_directory": "/root/userbot/.bin"} chrome_options.add_experimental_option("prefs", prefs) driver = webdriver.Chrome(executable_path=CHROME_DRIVER, options=chrome_options) driver.get(url) await e.edit("`Processing..\n50%`") download_path = "/root/userbot/.bin" driver.command_executor._commands["send_command"] = ( "POST", "/session/$sessionId/chromium/send_command", ) params = { "cmd": "Page.setDownloadBehavior", "params": {"behavior": "allow", "downloadPath": download_path}, } driver.execute("send_command", params) driver.find_element_by_xpath("//button[contains(text(),'Export')]").click() # driver.find_element_by_xpath("//button[contains(text(),'4x')]").click() # driver.find_element_by_xpath("//button[contains(text(),'PNG')]").click() await e.edit("`Processing..\n75%`") # Waiting for downloading while not os.path.isfile("/root/userbot/.bin/carbon.png"): await sleep(0.5) await e.edit("`Processing..\n100%`") file = "/root/userbot/.bin/carbon.png" await e.edit("`Uploading..`") await e.client.send_file( e.chat_id, file, caption="Made using [Carbon](https://carbon.now.sh/about/),\ \na project by [Dawn Labs](https://dawnlabs.io/)", force_document=True, reply_to=e.message.reply_to_msg_id, ) os.remove("/root/userbot/.bin/carbon.png") driver.quit() # Removing carbon.png after uploading await e.delete() # Deleting msg @register(outgoing=True, pattern=r"^\.img (.*)") async def img_sampler(event): """For .img command, search and return images matching the query.""" await event.edit("`Sedang Mencari Gambar Yang Anda Cari...`") query = event.pattern_match.group(1) lim = findall(r"lim=\d+", query) try: lim = lim[0] lim = lim.replace("lim=", "") query = query.replace("lim=" + lim[0], "") except IndexError: lim = 15 response = googleimagesdownload() # creating list of arguments arguments = { "keywords": query, "limit": lim, "format": "jpg", "no_directory": "no_directory", } # passing the arguments to the function paths = response.download(arguments) lst = paths[0][query] await event.client.send_file( await event.client.get_input_entity(event.chat_id), lst ) shutil.rmtree(os.path.dirname(os.path.abspath(lst[0]))) await event.delete() @register(outgoing=True, pattern=r"^\.currency (.*)") async def moni(event): input_str = event.pattern_match.group(1) input_sgra = input_str.split(" ") if len(input_sgra) != 3: return await event.edit("`Invalid syntax.`") try: number = float(input_sgra[0]) currency_from = input_sgra[1].upper() currency_to = input_sgra[2].upper() request_url = f"https://api.ratesapi.io/api/latest?base={currency_from}" current_response = get(request_url).json() if currency_to in current_response["rates"]: current_rate = float(current_response["rates"][currency_to]) rebmun = round(number * current_rate, 2) await event.edit( "{} {} = {} {}".format(number, currency_from, rebmun, currency_to) ) else: await event.edit( "`Sepertinya ini adalah mata uang asing, yang tidak dapat saya konversi sekarang.`" ) except Exception as e: await event.edit(str(e)) @register(outgoing=True, pattern=r"^\.google (.*)") async def gsearch(q_event): """For .google command, do a Google search.""" match = q_event.pattern_match.group(1) page = findall(r"page=\d+", match) try: page = page[0] page = page.replace("page=", "") match = match.replace("page=" + page[0], "") except IndexError: page = 1 try: search_args = (str(match), int(page)) gsearch = GoogleSearch() gresults = await gsearch.async_search(*search_args) msg = "" for i in range(5): try: title = gresults["titles"][i] link = gresults["links"][i] desc = gresults["descriptions"][i] msg += f"[{title}]({link})\n`{desc}`\n\n" except IndexError: break except BaseException as g_e: return await q_event.edit(f"**Error : ** `{g_e}`") await q_event.edit( "**Search Query:**\n`" + match + "`\n\n**Results:**\n" + msg, link_preview=False ) @register(outgoing=True, pattern=r"^\.wiki (.*)") async def wiki(wiki_q): """For .wiki command, fetch content from Wikipedia.""" match = wiki_q.pattern_match.group(1) try: summary(match) except DisambiguationError as error: await wiki_q.edit(f"Ditemukan halaman yang tidak ambigu.\n\n{error}") return except PageError as pageerror: await wiki_q.edit(f"Halaman tidak ditemukan.\n\n{pageerror}") return result = summary(match) if len(result) >= 4096: with open("output.txt", "w+") as file: file.write(result) await wiki_q.client.send_file( wiki_q.chat_id, "output.txt", reply_to=wiki_q.id, caption="`Output terlalu besar, dikirim sebagai file`", ) if os.path.exists("output.txt"): os.remove("output.txt") return await wiki_q.edit("**Search:**\n`" + match + "`\n\n**Result:**\n" + result) @register(outgoing=True, pattern=r"^\.ud (.*)") async def _(event): if event.fwd_from: return await event.edit("processing...") word = event.pattern_match.group(1) urban = asyncurban.UrbanDictionary() try: mean = await urban.get_word(word) await event.edit( "Text: **{}**\n\nBerarti: **{}**\n\nContoh: __{}__".format( mean.word, mean.definition, mean.example ) ) except asyncurban.WordNotFoundError: await event.edit("Tidak ada hasil untuk **" + word + "**") @register(outgoing=True, pattern=r"^\.tts(?: |$)([\s\S]*)") async def text_to_speech(query): """For .tts command, a wrapper for Google Text-to-Speech.""" if query.is_reply and not query.pattern_match.group(1): message = await query.get_reply_message() message = str(message.message) else: message = str(query.pattern_match.group(1)) if not message: return await query.edit( "**Berikan teks atau balas pesan untuk Text-to-Speech!**" ) await query.edit("`Processing...`") try: from userbot.modules.sql_helper.globals import gvarstatus except AttributeError: return await query.edit("**Running on Non-SQL mode!**") if gvarstatus("tts_lang") is not None: target_lang = str(gvarstatus("tts_lang")) else: target_lang = "id" try: gTTS(message, lang=target_lang) except AssertionError: return await query.edit( "**Teksnya kosong.**\n" "Tidak ada yang tersisa untuk dibicarakan setelah pra-pemrosesan, pembuatan token, dan pembersihan." ) except ValueError: return await query.edit("**Bahasa tidak didukung.**") except RuntimeError: return await query.edit("**Error saat memuat kamus bahasa.**") tts = gTTS(message, lang=target_lang) tts.save("k.mp3") with open("k.mp3", "rb") as audio: linelist = list(audio) linecount = len(linelist) if linecount == 1: tts = gTTS(message, lang=target_lang) tts.save("k.mp3") with open("k.mp3"): await query.client.send_file(query.chat_id, "k.mp3", voice_note=True) os.remove("k.mp3") await query.delete() @register(outgoing=True, pattern=r"^\.tr(?: |$)([\s\S]*)") async def translateme(trans): """For .tr command, translate the given text using Google Translate.""" if trans.is_reply and not trans.pattern_match.group(1): message = await trans.get_reply_message() message = str(message.message) else: message = str(trans.pattern_match.group(1)) if not message: return await trans.edit( "**Berikan teks atau balas pesan untuk diterjemahkan!**" ) await trans.edit("`Processing...`") translator = google_translator() try: from userbot.modules.sql_helper.globals import gvarstatus except AttributeError: return await trans.edit("**Running on Non-SQL mode!**") if gvarstatus("tr_lang") is not None: target_lang = str(gvarstatus("tr_lang")) else: target_lang = "id" try: reply_text = translator.translate(deEmojify(message), lang_tgt=target_lang) except ValueError: return await trans.edit( "**Bahasa yang dipilih tidak valid, Gunakan **`.lang tr <kode bahasa>`" ) try: source_lan = translator.detect(deEmojify(message))[1].title() except BaseException: source_lan = "(Google tidak memberikan info ini)" reply_text = f"**Terjemahan** Dari `{source_lan}` Ke `{LANGUAGES.get(target_lang).title()}`\n\n{reply_text}" await trans.edit(reply_text) @register(pattern=r"\.lang (tr|tts) (.*)", outgoing=True) async def lang(value): """For .lang command, change the default langauge of userbot scrapers.""" util = value.pattern_match.group(1).lower() try: from userbot.modules.sql_helper.globals import addgvar, delgvar, gvarstatus except AttributeError: return await lang.edit("**Running on Non-SQL mode!**") if util == "tr": scraper = "Translate" arg = value.pattern_match.group(2).lower() if arg not in LANGUAGES: return await value.edit( f"**Kode bahasa tidak valid!**\nKode bahasa yang tersedia:\n\n`{LANGUAGES}`" ) if gvarstatus("tr_lang"): delgvar("tr_lang") addgvar("tr_lang", arg) LANG = LANGUAGES[arg] elif util == "tts": scraper = "Text to Speech" arg = value.pattern_match.group(2).lower() if arg not in tts_langs(): return await value.edit( f"**Kode bahasa tidak valid!**\nKode bahasa yang tersedia:\n\n`{tts_langs()}`" ) if gvarstatus("tts_lang"): delgvar("tts_lang") addgvar("tts_lang", arg) LANG = tts_langs()[arg] await value.edit( f"**Bahasa untuk** `{scraper}` **diganti menjadi** `{LANG.title()}`" ) if BOTLOG: await value.client.send_message( BOTLOG_CHATID, f"**Bahasa untuk** `{scraper}` **diganti menjadi** `{LANG.title()}`", ) @register(outgoing=True, pattern=r"^\.yt (\d*) *(.*)") async def yt_search(video_q): """For .yt command, do a YouTube search from Telegram.""" if video_q.pattern_match.group(1) != "": counter = int(video_q.pattern_match.group(1)) if counter > 10: counter = int(10) if counter <= 0: counter = int(1) else: counter = int(5) query = video_q.pattern_match.group(2) if not query: await video_q.edit("`Masukkan keyword untuk dicari`") await video_q.edit("`Processing...`") try: results = json.loads(YoutubeSearch(query, max_results=counter).to_json()) except KeyError: return await video_q.edit( "`Pencarian Youtube menjadi lambat.\nTidak dapat mencari keyword ini!`" ) output = f"**Pencarian Keyword:**\n`{query}`\n\n**Hasil:**\n\n" for i in results["videos"]: try: title = i["title"] link = "https://youtube.com" + i["url_suffix"] channel = i["channel"] duration = i["duration"] views = i["views"] output += f"[{title}]({link})\nChannel: `{channel}`\nDuration: {duration} | {views}\n\n" except IndexError: break await video_q.edit(output, link_preview=False) @register(outgoing=True, pattern=r".yt(audio|video) (.*)") async def download_video(v_url): """For .yt command, download media from YouTube and many other sites.""" dl_type = v_url.pattern_match.group(1).lower() url = v_url.pattern_match.group(2) await v_url.edit("`Preparing to download...`") video = False audio = False if dl_type == "audio": opts = { "format": "bestaudio", "addmetadata": True, "key": "FFmpegMetadata", "writethumbnail": True, "prefer_ffmpeg": True, "geo_bypass": True, "nocheckcertificate": True, "postprocessors": [ { "key": "FFmpegExtractAudio", "preferredcodec": "mp3", "preferredquality": "320", } ], "outtmpl": "%(id)s.%(ext)s", "quiet": True, "logtostderr": False, } audio = True elif dl_type == "video": opts = { "format": "best", "addmetadata": True, "key": "FFmpegMetadata", "prefer_ffmpeg": True, "geo_bypass": True, "nocheckcertificate": True, "postprocessors": [ {"key": "FFmpegVideoConvertor", "preferedformat": "mp4"} ], "outtmpl": "%(id)s.%(ext)s", "logtostderr": False, "quiet": True, } video = True try: await v_url.edit("`Fetching data, please wait..`") with YoutubeDL(opts) as rip: rip_data = rip.extract_info(url) except DownloadError as DE: return await v_url.edit(f"`{str(DE)}`") except ContentTooShortError: return await v_url.edit("`The download content was too short.`") except GeoRestrictedError: return await v_url.edit( "`Video is not available from your geographic location " "due to geographic restrictions imposed by a website.`" ) except MaxDownloadsReached: return await v_url.edit("`Max-downloads limit has been reached.`") except PostProcessingError: return await v_url.edit("`There was an error during post processing.`") except UnavailableVideoError: return await v_url.edit("`Media is not available in the requested format.`") except XAttrMetadataError as XAME: return await v_url.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`") except ExtractorError: return await v_url.edit("`There was an error during info extraction.`") except Exception as e: return await v_url.edit(f"{str(type(e)): {str(e)}}") c_time = time.time() if audio: await v_url.edit( f"**Sedang Mengupload Lagu:**\n`{rip_data.get('title')}`" f"\nby **{rip_data.get('uploader')}**" ) f_name = rip_data.get("id") + ".mp3" with open(f_name, "rb") as f: result = await upload_file( client=v_url.client, file=f, name=f_name, progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress( d, t, v_url, c_time, "Uploading..", f"{rip_data['title']}.mp3" ) ), ) img_extensions = ["jpg", "jpeg", "webp"] img_filenames = [ fn_img for fn_img in os.listdir() if any(fn_img.endswith(ext_img) for ext_img in img_extensions) ] thumb_image = img_filenames[0] metadata = extractMetadata(createParser(f_name)) duration = 0 if metadata.has("duration"): duration = metadata.get("duration").seconds await v_url.client.send_file( v_url.chat_id, result, supports_streaming=True, attributes=[ DocumentAttributeAudio( duration=duration, title=rip_data.get("title"), performer=rip_data.get("uploader"), ) ], thumb=thumb_image, ) os.remove(thumb_image) os.remove(f_name) await v_url.delete() elif video: await v_url.edit( f"**Sedang Mengupload Video:**\n`{rip_data.get('title')}`" f"\nby **{rip_data.get('uploader')}**" ) f_name = rip_data.get("id") + ".mp4" with open(f_name, "rb") as f: result = await upload_file( client=v_url.client, file=f, name=f_name, progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress( d, t, v_url, c_time, "Uploading..", f"{rip_data['title']}.mp4" ) ), ) thumb_image = await get_video_thumb(f_name, "thumb.png") metadata = extractMetadata(createParser(f_name)) duration = 0 width = 0 height = 0 if metadata.has("duration"): duration = metadata.get("duration").seconds if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") await v_url.client.send_file( v_url.chat_id, result, thumb=thumb_image, attributes=[ DocumentAttributeVideo( duration=duration, w=width, h=height, supports_streaming=True, ) ], caption=rip_data["title"], ) os.remove(f_name) os.remove(thumb_image) await v_url.delete() def deEmojify(inputString): """Remove emojis and other non-safe characters from string""" return get_emoji_regexp().sub("", inputString) @register(outgoing=True, pattern="^.rbg(?: |$)(.*)") async def kbg(remob): """For .rbg command, Remove Image Background.""" if REM_BG_API_KEY is None: await remob.edit( "`Error: Remove.BG API key missing! Add it to environment vars or config.env.`" ) return input_str = remob.pattern_match.group(1) message_id = remob.message.id if remob.reply_to_msg_id: message_id = remob.reply_to_msg_id reply_message = await remob.get_reply_message() await remob.edit("`Processing..`") try: if isinstance( reply_message.media, MessageMediaPhoto ) or "image" in reply_message.media.document.mime_type.split("/"): downloaded_file_name = await remob.client.download_media( reply_message, TEMP_DOWNLOAD_DIRECTORY ) await remob.edit("`Removing background from this image..`") output_file_name = await ReTrieveFile(downloaded_file_name) os.remove(downloaded_file_name) else: await remob.edit("`Bagaimana cara menghapus latar belakang ini ?`") except Exception as e: await remob.edit(str(e)) return elif input_str: await remob.edit( f"`Removing background from online image hosted at`\n{input_str}" ) output_file_name = await ReTrieveURL(input_str) else: await remob.edit("`Saya butuh sesuatu untuk menghapus latar belakang.`") return contentType = output_file_name.headers.get("content-type") if "image" in contentType: with io.BytesIO(output_file_name.content) as remove_bg_image: remove_bg_image.name = "removed_bg.png" await remob.client.send_file( remob.chat_id, remove_bg_image, caption="Support @SharingUserbot", force_document=True, reply_to=message_id, ) await remob.delete() else: await remob.edit( "**Error (Invalid API key, I guess ?)**\n`{}`".format( output_file_name.content.decode("UTF-8") ) ) # this method will call the API, and return in the appropriate format # with the name provided. async def ReTrieveFile(input_file_name): headers = { "X-API-Key": REM_BG_API_KEY, } files = { "image_file": (input_file_name, open(input_file_name, "rb")), } return requests.post( "https://api.remove.bg/v1.0/removebg", headers=headers, files=files, allow_redirects=True, stream=True, ) async def ReTrieveURL(input_url): headers = { "X-API-Key": REM_BG_API_KEY, } data = {"image_url": input_url} return requests.post( "https://api.remove.bg/v1.0/removebg", headers=headers, data=data, allow_redirects=True, stream=True, ) @register(pattern=r".ocr (.*)", outgoing=True) async def ocr(event): if not OCR_SPACE_API_KEY: return await event.edit( "`Error: OCR.Space API key is missing! Add it to environment variables or config.env.`" ) await event.edit("`Sedang Membaca...`") if not os.path.isdir(TEMP_DOWNLOAD_DIRECTORY): os.makedirs(TEMP_DOWNLOAD_DIRECTORY) lang_code = event.pattern_match.group(1) downloaded_file_name = await bot.download_media( await event.get_reply_message(), TEMP_DOWNLOAD_DIRECTORY ) test_file = await ocr_space_file(filename=downloaded_file_name, language=lang_code) try: ParsedText = test_file["ParsedResults"][0]["ParsedText"] except BaseException: await event.edit( "`Tidak bisa membacanya.`\n`Saya rasa saya perlu kacamata baru.`" ) else: await event.edit(f"`Inilah yang bisa saya baca darinya:`\n\n{ParsedText}") os.remove(downloaded_file_name) @register(pattern=r"^.decode$", outgoing=True) async def parseqr(qr_e): """For .decode command, get QR Code/BarCode content from the replied photo.""" downloaded_file_name = await qr_e.client.download_media( await qr_e.get_reply_message() ) # parse the Official ZXing webpage to decode the QRCode command_to_exec = [ "curl", "-X", "POST", "-F", "f=@" + downloaded_file_name + "", "https://zxing.org/w/decode", ] process = await asyncio.create_subprocess_exec( *command_to_exec, # stdout must a pipe to be accessible as process.stdout stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) # Wait for the subprocess to finish stdout, stderr = await process.communicate() e_response = stderr.decode().strip() t_response = stdout.decode().strip() os.remove(downloaded_file_name) if not t_response: LOGS.info(e_response) LOGS.info(t_response) return await qr_e.edit("Gagal untuk decode.") soup = BeautifulSoup(t_response, "html.parser") qr_contents = soup.find_all("pre")[0].text await qr_e.edit(qr_contents) @register(pattern=r".barcode(?: |$)([\s\S]*)", outgoing=True) async def bq(event): """For .barcode command, genrate a barcode containing the given content.""" await event.edit("`Processing..`") input_str = event.pattern_match.group(1) message = "SYNTAX: `.barcode <long text to include>`" reply_msg_id = event.message.id if input_str: message = input_str elif event.reply_to_msg_id: previous_message = await event.get_reply_message() reply_msg_id = previous_message.id if previous_message.media: downloaded_file_name = await event.client.download_media(previous_message) m_list = None with open(downloaded_file_name, "rb") as fd: m_list = fd.readlines() message = "".join(m.decode("UTF-8") + "\r\n" for m in m_list) os.remove(downloaded_file_name) else: message = previous_message.message else: return event.edit("SYNTAX: `.barcode <long text to include>`") bar_code_type = "code128" try: bar_code_mode_f = barcode.get(bar_code_type, message, writer=ImageWriter()) filename = bar_code_mode_f.save(bar_code_type) await event.client.send_file(event.chat_id, filename, reply_to=reply_msg_id) os.remove(filename) except Exception as e: return await event.edit(str(e)) await event.delete() @register(pattern=r".makeqr(?: |$)([\s\S]*)", outgoing=True) async def make_qr(makeqr): """For .makeqr command, make a QR Code containing the given content.""" input_str = makeqr.pattern_match.group(1) message = "SYNTAX: `.makeqr <long text to include>`" reply_msg_id = None if input_str: message = input_str elif makeqr.reply_to_msg_id: previous_message = await makeqr.get_reply_message() reply_msg_id = previous_message.id if previous_message.media: downloaded_file_name = await makeqr.client.download_media(previous_message) m_list = None with open(downloaded_file_name, "rb") as file: m_list = file.readlines() message = "".join(media.decode("UTF-8") + "\r\n" for media in m_list) os.remove(downloaded_file_name) else: message = previous_message.message qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4, ) qr.add_data(message) qr.make(fit=True) img = qr.make_image(fill_color="black", back_color="white") img.save("img_file.webp", "PNG") await makeqr.client.send_file( makeqr.chat_id, "img_file.webp", reply_to=reply_msg_id ) os.remove("img_file.webp") await makeqr.delete() @register(outgoing=True, pattern=r"^.direct(?: |$)([\s\S]*)") async def direct_link_generator(request): """direct links generator""" await request.edit("`Processing...`") textx = await request.get_reply_message() message = request.pattern_match.group(1) if message: pass elif textx: message = textx.text else: await request.edit("`Usage: .direct <url>`") return reply = "" links = re.findall(r"\bhttps?://.*\.\S+", message) if not links: reply = "`No links found!`" await request.edit(reply) for link in links: if "drive.google.com" in link: reply += gdrive(link) elif "zippyshare.com" in link: reply += zippy_share(link) elif "yadi.sk" in link: reply += yandex_disk(link) elif "cloud.mail.ru" in link: reply += cm_ru(link) elif "mediafire.com" in link: reply += mediafire(link) elif "sourceforge.net" in link: reply += sourceforge(link) elif "osdn.net" in link: reply += osdn(link) elif "github.com" in link: reply += github(link) elif "androidfilehost.com" in link: reply += androidfilehost(link) else: reply += re.findall(r"\bhttps?://(.*?[^/]+)", link)[0] + "is not supported" await request.edit(reply) def gdrive(url: str) -> str: """GDrive direct links generator""" drive = "https://drive.google.com" try: link = re.findall(r"\bhttps?://drive\.google\.com\S+", url)[0] except IndexError: reply = "`No Google drive links found`\n" return reply file_id = "" reply = "" if link.find("view") != -1: file_id = link.split("/")[-2] elif link.find("open?id=") != -1: file_id = link.split("open?id=")[1].strip() elif link.find("uc?id=") != -1: file_id = link.split("uc?id=")[1].strip() url = f"{drive}/uc?export=download&id={file_id}" download = requests.get(url, stream=True, allow_redirects=False) cookies = download.cookies try: # In case of small file size, Google downloads directly dl_url = download.headers["location"] if "accounts.google.com" in dl_url: # non-public file reply += "`Link is not public!`\n" return reply name = "Direct Download Link" except KeyError: # In case of download warning page page = BeautifulSoup(download.content, "lxml") export = drive + page.find("a", {"id": "uc-download-link"}).get("href") name = page.find("span", {"class": "uc-name-size"}).text response = requests.get( export, stream=True, allow_redirects=False, cookies=cookies ) dl_url = response.headers["location"] if "accounts.google.com" in dl_url: reply += "Link is not public!" return reply reply += f"[{name}]({dl_url})\n" return reply def zippy_share(url: str) -> str: link = re.findall("https:/.(.*?).zippyshare", url)[0] response_content = (requests.get(url)).content bs_obj = BeautifulSoup(response_content, "lxml") try: js_script = bs_obj.find("div", {"class": "center",}).find_all( "script" )[1] except BaseException: js_script = bs_obj.find("div", {"class": "right",}).find_all( "script" )[0] js_content = re.findall(r'\.href.=."/(.*?)";', str(js_script)) js_content = 'var x = "/' + js_content[0] + '"' evaljs = EvalJs() setattr(evaljs, "x", None) evaljs.execute(js_content) js_content = getattr(evaljs, "x") dl_url = f"https://{link}.zippyshare.com{js_content}" file_name = basename(dl_url) return f"[{urllib.parse.unquote_plus(file_name)}]({dl_url})" def yandex_disk(url: str) -> str: """Yandex.Disk direct links generator Based on https://github.com/wldhx/yadisk-direct""" reply = "" try: link = re.findall(r"\bhttps?://.*yadi\.sk\S+", url)[0] except IndexError: reply = "`No Yandex.Disk links found`\n" return reply api = "https://cloud-api.yandex.net/v1/disk/public/resources/download?public_key={}" try: dl_url = requests.get(api.format(link)).json()["href"] name = dl_url.split("filename=")[1].split("&disposition")[0] reply += f"[{name}]({dl_url})\n" except KeyError: reply += "`Error: File not found / Download limit reached`\n" return reply return reply def cm_ru(url: str) -> str: """cloud.mail.ru direct links generator Using https://github.com/JrMasterModelBuilder/cmrudl.py""" reply = "" try: link = re.findall(r"\bhttps?://.*cloud\.mail\.ru\S+", url)[0] except IndexError: reply = "`No cloud.mail.ru links found`\n" return reply command = f"bin/cmrudl -s {link}" result = popen(command).read() result = result.splitlines()[-1] try: data = json.loads(result) except json.decoder.JSONDecodeError: reply += "`Error: Can't extract the link`\n" return reply dl_url = data["download"] name = data["file_name"] size = naturalsize(int(data["file_size"])) reply += f"[{name} ({size})]({dl_url})\n" return reply def mediafire(url: str) -> str: """MediaFire direct links generator""" try: link = re.findall(r"\bhttps?://.*mediafire\.com\S+", url)[0] except IndexError: reply = "`No MediaFire links found`\n" return reply reply = "" page = BeautifulSoup(requests.get(link).content, "lxml") info = page.find("a", {"aria-label": "Download file"}) dl_url = info.get("href") size = re.findall(r"\(.*\)", info.text)[0] name = page.find("div", {"class": "filename"}).text reply += f"[{name} {size}]({dl_url})\n" return reply def sourceforge(url: str) -> str: """SourceForge direct links generator""" try: link = re.findall(r"\bhttps?://.*sourceforge\.net\S+", url)[0] except IndexError: reply = "`No SourceForge links found`\n" return reply file_path = re.findall(r"files(.*)/download", link)[0] reply = f"Mirrors for __{file_path.split('/')[-1]}__\n" project = re.findall(r"projects?/(.*?)/files", link)[0] mirrors = ( f"https://sourceforge.net/settings/mirror_choices?" f"projectname={project}&filename={file_path}" ) page = BeautifulSoup(requests.get(mirrors).content, "html.parser") info = page.find("ul", {"id": "mirrorList"}).findAll("li") for mirror in info[1:]: name = re.findall(r"\((.*)\)", mirror.text.strip())[0] dl_url = ( f'https://{mirror["id"]}.dl.sourceforge.net/project/{project}/{file_path}' ) reply += f"[{name}]({dl_url}) " return reply def osdn(url: str) -> str: """OSDN direct links generator""" osdn_link = "https://osdn.net" try: link = re.findall(r"\bhttps?://.*osdn\.net\S+", url)[0] except IndexError: reply = "`No OSDN links found`\n" return reply page = BeautifulSoup(requests.get(link, allow_redirects=True).content, "lxml") info = page.find("a", {"class": "mirror_link"}) link = urllib.parse.unquote(osdn_link + info["href"]) reply = f"Mirrors for __{link.split('/')[-1]}__\n" mirrors = page.find("form", {"id": "mirror-select-form"}).findAll("tr") for data in mirrors[1:]: mirror = data.find("input")["value"] name = re.findall(r"\((.*)\)", data.findAll("td")[-1].text.strip())[0] dl_url = re.sub(r"m=(.*)&f", f"m={mirror}&f", link) reply += f"[{name}]({dl_url}) " return reply def github(url: str) -> str: """GitHub direct links generator""" try: link = re.findall(r"\bhttps?://.*github\.com.*releases\S+", url)[0] except IndexError: reply = "`No GitHub Releases links found`\n" return reply reply = "" dl_url = "" download = requests.get(url, stream=True, allow_redirects=False) try: dl_url = download.headers["location"] except KeyError: reply += "`Error: Can't extract the link`\n" name = link.split("/")[-1] reply += f"[{name}]({dl_url}) " return reply def androidfilehost(url: str) -> str: """AFH direct links generator""" try: link = re.findall(r"\bhttps?://.*androidfilehost.*fid.*\S+", url)[0] except IndexError: reply = "`No AFH links found`\n" return reply fid = re.findall(r"\?fid=(.*)", link)[0] session = requests.Session() user_agent = useragent() headers = {"user-agent": user_agent} res = session.get(link, headers=headers, allow_redirects=True) headers = { "origin": "https://androidfilehost.com", "accept-encoding": "gzip, deflate, br", "accept-language": "en-US,en;q=0.9", "user-agent": user_agent, "content-type": "application/x-www-form-urlencoded; charset=UTF-8", "x-mod-sbb-ctype": "xhr", "accept": "*/*", "referer": f"https://androidfilehost.com/?fid={fid}", "authority": "androidfilehost.com", "x-requested-with": "XMLHttpRequest", } data = {"submit": "submit", "action": "getdownloadmirrors", "fid": f"{fid}"} mirrors = None reply = "" error = "`Error: Can't find Mirrors for the link`\n" try: req = session.post( "https://androidfilehost.com/libs/otf/mirrors.otf.php", headers=headers, data=data, cookies=res.cookies, ) mirrors = req.json()["MIRRORS"] except (json.decoder.JSONDecodeError, TypeError): reply += error if not mirrors: reply += error return reply for item in mirrors: name = item["name"] dl_url = item["url"] reply += f"[{name}]({dl_url}) " return reply def useragent(): """ useragent random setter """ useragents = BeautifulSoup( requests.get( "https://developers.whatismybrowser.com/" "useragents/explore/operating_system_name/android/" ).content, "lxml", ).findAll("td", {"class": "useragent"}) user_agent = choice(useragents) return user_agent.text @register(outgoing=True, pattern=r"^\.paste(?: |$)([\s\S]*)") async def paste(pstl): dogbin_final_url = "" match = pstl.pattern_match.group(1).strip() reply_id = pstl.reply_to_msg_id if not match and not reply_id: return await pstl.edit("`Elon Musk said I cannot paste void.`") if match: message = match elif reply_id: message = await pstl.get_reply_message() if message.media: downloaded_file_name = await pstl.client.download_media( message, TEMP_DOWNLOAD_DIRECTORY, ) m_list = None with open(downloaded_file_name, "rb") as fd: m_list = fd.readlines() message = "".join(m.decode("UTF-8") for m in m_list) os.remove(downloaded_file_name) else: message = message.message # Dogbin await pstl.edit("`Pasting text . . .`") resp = post(DOGBIN_URL + "documents", data=message.encode("utf-8")) if resp.status_code == 200: response = resp.json() key = response["key"] dogbin_final_url = DOGBIN_URL + key if response["isUrl"]: reply_text = ( "`Pasted successfully!`\n\n" f"[Shortened URL]({dogbin_final_url})\n\n" "`Original(non-shortened) URLs`\n" f"[Dogbin URL]({DOGBIN_URL}v/{key})\n" f"[View RAW]({DOGBIN_URL}raw/{key})" ) else: reply_text = ( "`Pasted successfully!`\n\n" f"[Dogbin URL]({dogbin_final_url})\n" f"[View RAW]({DOGBIN_URL}raw/{key})" ) else: reply_text = "`Failed to reach Dogbin`" await pstl.edit(reply_text) @register(outgoing=True, pattern=r"^\.getpaste(?: |$)(.*)") async def get_dogbin_content(dog_url): textx = await dog_url.get_reply_message() message = dog_url.pattern_match.group(1) await dog_url.edit("`Getting dogbin content...`") if textx: message = str(textx.message) format_normal = f"{DOGBIN_URL}" format_view = f"{DOGBIN_URL}v/" if message.startswith(format_view): message = message[len(format_view) :] elif message.startswith(format_normal): message = message[len(format_normal) :] elif message.startswith("del.dog/"): message = message[len("del.dog/") :] else: return await dog_url.edit("`Is that even a dogbin url?`") resp = get(f"{DOGBIN_URL}raw/{message}") try: resp.raise_for_status() except exceptions.HTTPError as HTTPErr: await dog_url.edit( "Request returned an unsuccessful status code.\n\n" + str(HTTPErr) ) return except exceptions.Timeout as TimeoutErr: await dog_url.edit("Request timed out." + str(TimeoutErr)) return except exceptions.TooManyRedirects as RedirectsErr: await dog_url.edit( "Request exceeded the configured number of maximum redirections." + str(RedirectsErr) ) return reply_text = ( "`Fetched dogbin URL content successfully!`" "\n\n`Content:` " + resp.text ) await dog_url.edit(reply_text) @register(outgoing=True, pattern=r"^\.neko(?: |$)([\s\S]*)") async def neko(nekobin): """For .paste command, pastes the text directly to dogbin.""" nekobin_final_url = "" match = nekobin.pattern_match.group(1).strip() reply_id = nekobin.reply_to_msg_id if not match and not reply_id: return await pstl.edit("`Cannot paste text.`") if match: message = match elif reply_id: message = await nekobin.get_reply_message() if message.media: downloaded_file_name = await nekobin.client.download_media( message, TEMP_DOWNLOAD_DIRECTORY, ) m_list = None with open(downloaded_file_name, "rb") as fd: m_list = fd.readlines() message = "".join(m.decode("UTF-8") for m in m_list) os.remove(downloaded_file_name) else: message = message.text # Nekobin await nekobin.edit("`Pasting text . . .`") resp = post(NEKOBIN_URL + "api/documents", json={"content": message}) if resp.status_code == 201: response = resp.json() key = response["result"]["key"] nekobin_final_url = NEKOBIN_URL + key reply_text = ( "`Pasted successfully!`\n\n" f"[Nekobin URL]({nekobin_final_url})\n" f"[View RAW]({NEKOBIN_URL}raw/{key})" ) else: reply_text = "`Gagal menjangkau Nekobin`" await nekobin.edit(reply_text) @register(pattern=r"^\.ss (.*)", outgoing=True) async def capture(url): """For .ss command, capture a website's screenshot and send the photo.""" await url.edit("`Processing...`") chrome_options = await options() chrome_options.add_argument("--test-type") chrome_options.add_argument("--ignore-certificate-errors") chrome_options.arguments.remove("--window-size=1920x1080") driver = await chrome(chrome_options=chrome_options) input_str = url.pattern_match.group(1) link_match = match(r"\bhttps?://.*\.\S+", input_str) if link_match: link = link_match.group() else: return await url.edit("`I need a valid link to take screenshots from.`") driver.get(link) height = driver.execute_script( "return Math.max(document.body.scrollHeight, document.body.offsetHeight, " "document.documentElement.clientHeight, document.documentElement.scrollHeight, " "document.documentElement.offsetHeight);" ) width = driver.execute_script( "return Math.max(document.body.scrollWidth, document.body.offsetWidth, " "document.documentElement.clientWidth, document.documentElement.scrollWidth, " "document.documentElement.offsetWidth);" ) driver.set_window_size(width + 125, height + 125) wait_for = height / 1000 await url.edit( "`Generating screenshot of the page...`" f"\n`Height of page = {height}px`" f"\n`Width of page = {width}px`" f"\n`Waiting ({int(wait_for)}s) for the page to load.`" ) await sleep(int(wait_for)) im_png = driver.get_screenshot_as_png() # saves screenshot of entire page driver.quit() message_id = url.message.id if url.reply_to_msg_id: message_id = url.reply_to_msg_id with io.BytesIO(im_png) as out_file: out_file.name = "screencapture.png" await url.edit("`Uploading screenshot as file..`") await url.client.send_file( url.chat_id, out_file, caption=input_str, force_document=True, reply_to=message_id, ) await url.delete() CMD_HELP.update( { "tts": "**Plugin : **`tts`\ \n\n • **Syntax :** `.tts` <text/reply>\ \n • **Function : **Menerjemahkan teks ke ucapan untuk bahasa yang disetel. \ \n\n • **NOTE :** Gunakan .lang tts <kode bahasa> untuk menyetel bahasa untuk tr **(Bahasa Default adalah bahasa Indonesia)**\ " } ) CMD_HELP.update( { "translate": "**Plugin : **`Terjemahan`\ \n\n • **Syntax :** `.tr` <text/reply>\ \n • **Function : **Menerjemahkan teks ke bahasa yang disetel.\ \n\n • **NOTE :** Gunakan .lang tr <kode bahasa> untuk menyetel bahasa untuk tr **(Bahasa Default adalah bahasa Indonesia)**\ " } ) CMD_HELP.update( { "paste": "**Plugin : **`paste`\ \n\n • **Syntax :** `.paste` <text/reply>\ \n • **Function : **Buat paste atau url yang dipersingkat menggunakan dog in.\ \n\n • **Syntax :** `.getpaste` <text/reply>\ \n • **Function : **Buat paste atau url yang dipersingkat menggunakan dog in.\ \n\n • **Syntax :** `.neko` <text/reply>\ \n • **Function : **Buat paste atau url yang dipersingkat menggunakan dog in.\ " } ) CMD_HELP.update( { "carbon": "**Plugin : **`carbon`\ \n\n • **Syntax :** `.carbon` <text/reply>\ \n • **Function : **Percantik kode Anda menggunakan carbon.now.sh\ \n\n • **NOTE :** Gunakan .crblang <text> untuk menyetel bahasa kode Anda.\ " } ) CMD_HELP.update( { "removebg": "**Plugin : **`removebg`\ \n\n • **Syntax :** `.rbg` <Tautan ke Gambar> atau balas gambar apa pun (Peringatan: tidak berfungsi pada stiker.)\ \n • **Function : **Menghapus latar belakang gambar, menggunakan API remove.bg\ " } ) CMD_HELP.update( { "ocr": "**Plugin : **`ocr`\ \n\n • **Syntax :** `.ocr` <kode bahasa>\ \n • **Function : **Balas gambar atau stiker untuk mengekstrak teks media tersebut.\ " } ) CMD_HELP.update( { "youtube": "**Plugin : **`youtube`\ \n\n • **Syntax :** `.yt` <jumlah> <query>\ \n • **Function : **Melakukan Pencarian YouTube. Dapat menentukan jumlah hasil yang dibutuhkan (default adalah 5)\ " } ) CMD_HELP.update( { "google": "**Plugin : **`google`\ \n\n • **Syntax :** `.google` <query>\ \n • **Function : **Melakukan pencarian di google.\ " } ) CMD_HELP.update( { "wiki": "**Plugin : **`wiki`\ \n\n • **Syntax :** `.wiki` <query>\ \n • **Function : **Melakukan pencarian di Wikipedia.\ " } ) CMD_HELP.update( { "direct": "**Plugin : **`direct`\ \n\n • **Syntax :** `.direct` <url>\ \n • **Function : **Balas tautan atau tempel URL untuk membuat tautan unduhan langsung.\ \n\n • **Supported URL :** `Google Drive` - `Cloud Mail` - `Yandex.Disk` - `AFH` - `ZippyShare` - `MediaFire` - `SourceForge` - `OSDN` - `GitHub`\ " } ) CMD_HELP.update( { "barcode": "**Plugin : **`barcode`\ \n\n • **Syntax :** `.barcode` <content>\ \n • **Function :** Buat Kode Batang dari konten yang diberikan.\ \n\n • **Example :** `.barcode www.google.com`\ \n\n • **Syntax :** `.makeqr` <content>\ \n • **Function :** Buat Kode QR dari konten yang diberikan.\ \n\n • **Example :** `.makeqr www.google.com`\ \n\n • **NOTE :** Gunakan .decode <reply to barcode / qrcode> untuk mendapatkan konten yang didekodekan.\ " } ) CMD_HELP.update( { "image_search": "**Plugin : **`image_search`\ \n\n • **Syntax :** `.img` <search_query>\ \n • **Function : **Melakukan pencarian gambar di Google dan menampilkan 15 gambar.\ " } ) CMD_HELP.update( { "ytdl": "**Plugin : **`ytdl`\ \n\n • **Syntax :** `.ytaudio` <url>\ \n • **Function : **Untuk Mendownload lagu dari YouTube.\ \n\n • **Syntax :** `.ytvideo` <url>\ \n • **Function : **Untuk Mendownload video dari YouTube.\ " } ) CMD_HELP.update( { "screenshot": "**Plugin : **`screenshot`\ \n\n • **Syntax :** `.ss` <url>\ \n • **Function : **Mengambil tangkapan layar dari situs web dan mengirimkan tangkapan layar.\ \n • **Example : .ss http://www.google.com\ " } ) CMD_HELP.update( { "currency": "**Plugin : **`currency`\ \n\n • **Syntax :** `.currency` <amount> <from> <to>\ \n • **Function : **Mengonversi berbagai mata uang untuk Anda.\ " } ) CMD_HELP.update( { "ud": "**Plugin : **`Urban Dictionary`\ \n\n • **Syntax :** `.ud` <query>\ \n • **Function : **Melakukan pencarian di Urban Dictionary.\ " } )
import psutil import platform from datetime import datetime class SysInfo(object): def __init__(self): self.units = ["", "K", "M", "G", "T", "P"] self.factor = 1024 self.func_dict = { 'system': self.get_system, 'uptime': self.get_uptime, 'cpu': self.get_cpu_data, 'ram': self.get_ram_data, 'disk': self.get_disk_data } self.sys_args = ['system', 'uptime', 'cpu', 'ram', 'disk'] def get_size(self, bytes: int, suffix="B") -> str: for unit in self.units: if bytes < self.factor: return f"{bytes:.2f}{unit}{suffix}" bytes /= self.factor def percentage(self, part, whole, precision = 1) -> str: return f"{float(part)/float(whole):.{int(precision)}%}" def get_system(self) -> str: distro = platform.linux_distribution() return f"{platform.system()} {" ".join(distro)}" def get_uptime(self) -> str: bt = datetime.fromtimestamp(psutil.boot_time()) return f"{bt.day} days {bt.hour}h {bt.minute}m {bt.second}s" def get_cpu_data(self) -> str: usage = f"{psutil.cpu_percent()}%" frequency = f"{psutil.cpu_freq().current:.2f}Mhz" return f"CPU usage: {usage}\nCPU Frequency: {frequency}" def get_ram_data(self) -> str: ram = psutil.virtual_memory() total = self.get_size(ram.total) used = self.get_size(ram.used) used_percent = self.percentage(ram.used, ram.total) return f"{used} of {total} ( {used_percent} ) of RAM is used." def get_disk_data(self, show_partitions : bool = False) -> str: partitions = psutil.disk_partitions() if show_partitions: partition_info = [] for partition in partitions: try: partition_usage = psutil.disk_usage(partition.mountpoint) except PermissionError: continue total = self.get_size(partition_usage.total) used = self.get_size(partition_usage.used) used_percentage = self.get_size(partition_usage.percent) partition_info.append(f"{used} of {total} ( {used_percentage} ) of disk space is used.") return "\n".join(partition_info) else: sum_total = 0 sum_used = 0 for partition in partitions: try: partition_usage = psutil.disk_usage(partition.mountpoint) except PermissionError: continue sum_total += partition_usage.total sum_used += partition_usage.used sum_used_percent = self.percentage(sum_used, sum_total) sum_total = self.get_size(sum_total) sum_used = self.get_size(sum_used) return f"{sum_used} of {sum_total} ( {sum_used_percent} ) of disk space is used." # ---------------------------------------------------- def data(self) -> str: system = self.get_system() uptime = self.get_uptime() cpu_data = self.get_cpu_data() ram_data = self.get_ram_data() disk_data = self.get_disk_data() return f"{system}\n\nUptime: {uptime}\n\n{cpu_data}\n\nRAM data:\n{ram_data}\n\nDisk data:\n{disk_data}" def get_data(self, sys_arg: str) -> str: if sys_arg == "help": available_args = [] for key in self.func_dict: available_args.append(key) return "Available arguments:\n{}".format('\n'.join(available_args)) elif sys_arg in self.sys_args: return self.func_dict[sys_arg]() else: return self.data()
import psutil import platform from datetime import datetime class SysInfo(object): def __init__(self): self.units = ["", "K", "M", "G", "T", "P"] self.factor = 1024 self.func_dict = { 'system': self.get_system, 'uptime': self.get_uptime, 'cpu': self.get_cpu_data, 'ram': self.get_ram_data, 'disk': self.get_disk_data } self.sys_args = ['system', 'uptime', 'cpu', 'ram', 'disk'] def get_size(self, bytes: int, suffix="B") -> str: for unit in self.units: if bytes < self.factor: return f"{bytes:.2f}{unit}{suffix}" bytes /= self.factor def percentage(self, part, whole, precision = 1) -> str: return f"{float(part)/float(whole):.{int(precision)}%}" def get_system(self) -> str: distro = platform.linux_distribution() return f"{platform.system()} {' '.join(distro)}" def get_uptime(self) -> str: bt = datetime.fromtimestamp(psutil.boot_time()) return f"{bt.day} days {bt.hour}h {bt.minute}m {bt.second}s" def get_cpu_data(self) -> str: usage = f"{psutil.cpu_percent()}%" frequency = f"{psutil.cpu_freq().current:.2f}Mhz" return f"CPU usage: {usage}\nCPU Frequency: {frequency}" def get_ram_data(self) -> str: ram = psutil.virtual_memory() total = self.get_size(ram.total) used = self.get_size(ram.used) used_percent = self.percentage(ram.used, ram.total) return f"{used} of {total} ( {used_percent} ) of RAM is used." def get_disk_data(self, show_partitions : bool = False) -> str: partitions = psutil.disk_partitions() if show_partitions: partition_info = [] for partition in partitions: try: partition_usage = psutil.disk_usage(partition.mountpoint) except PermissionError: continue total = self.get_size(partition_usage.total) used = self.get_size(partition_usage.used) used_percentage = self.get_size(partition_usage.percent) partition_info.append(f"{used} of {total} ( {used_percentage} ) of disk space is used.") return "\n".join(partition_info) else: sum_total = 0 sum_used = 0 for partition in partitions: try: partition_usage = psutil.disk_usage(partition.mountpoint) except PermissionError: continue sum_total += partition_usage.total sum_used += partition_usage.used sum_used_percent = self.percentage(sum_used, sum_total) sum_total = self.get_size(sum_total) sum_used = self.get_size(sum_used) return f"{sum_used} of {sum_total} ( {sum_used_percent} ) of disk space is used." # ---------------------------------------------------- def data(self) -> str: system = self.get_system() uptime = self.get_uptime() cpu_data = self.get_cpu_data() ram_data = self.get_ram_data() disk_data = self.get_disk_data() return f"{system}\n\nUptime: {uptime}\n\n{cpu_data}\n\nRAM data:\n{ram_data}\n\nDisk data:\n{disk_data}" def get_data(self, sys_arg: str) -> str: if sys_arg == "help": available_args = [] for key in self.func_dict: available_args.append(key) return "Available arguments:\n{}".format('\n'.join(available_args)) elif sys_arg in self.sys_args: return self.func_dict[sys_arg]() else: return self.data()
import io import json import pathlib import sys import threading as th import time from base64 import b64decode, b64encode from io import open from os import path import serial import serial.tools.list_ports as stl from modi_firmware_updater.util.connection_util import list_modi_ports from modi_firmware_updater.util.message_util import (decode_message, parse_message, unpack_data) from modi_firmware_updater.util.module_util import (Module, get_module_type_from_uuid) def retry(exception_to_catch): def decorator(func): def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except exception_to_catch: return wrapper(*args, **kwargs) return wrapper return decorator class ESP32FirmwareUpdater(serial.Serial): DEVICE_READY = 0x2B DEVICE_SYNC = 0x08 SPI_ATTACH_REQ = 0xD SPI_FLASH_SET = 0xB ESP_FLASH_BEGIN = 0x02 ESP_FLASH_DATA = 0x03 ESP_FLASH_END = 0x04 ESP_FLASH_BLOCK = 0x200 ESP_FLASH_CHUNK = 0x4000 ESP_CHECKSUM_MAGIC = 0xEF def __init__(self, device=None): self.print = True if device != None: super().__init__( device, timeout = 0.1, baudrate = 921600 ) else: modi_ports = list_modi_ports() if not modi_ports: raise serial.SerialException("No MODI port is connected") for modi_port in modi_ports: try: super().__init__( modi_port.device, timeout=0.1, baudrate=921600 ) except Exception: self.__print('Next network module') continue else: break self.__print(f"Connecting to MODI network module at {modi_port.device}") self.__address = [0x1000, 0x8000, 0xD000, 0x10000, 0xD0000] self.file_path = [ "bootloader.bin", "partitions.bin", "ota_data_initial.bin", "modi_ota_factory.bin", "esp32.bin", ] self.version = None self.__version_to_update = None self.update_in_progress = False self.ui = None self.current_sequence = 0 self.total_sequence = 0 self.raise_error_message = True self.update_error = 0 self.update_error_message = "" self.network_uuid = None def set_ui(self, ui): self.ui = ui def set_print(self, print): self.print = print def set_raise_error(self, raise_error_message): self.raise_error_message = raise_error_message def update_firmware(self, update_interpreter=False, force=False): if update_interpreter: self.current_sequence = 0 self.total_sequence = 1 self.__print("get network uuid") self.network_uuid = self.get_network_uuid() self.__print("Reset interpreter...") self.update_in_progress = True self.write(b'{"c":160,"s":0,"d":18,"b":"AAMAAAAA","l":6}') self.__print("ESP interpreter reset is complete!!") self.current_sequence = 1 self.total_sequence = 1 time.sleep(1) self.update_in_progress = False self.flushInput() self.flushOutput() self.close() self.update_error = 1 if self.ui: self.ui.update_stm32_modules.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_stm32_modules.setEnabled(True) self.ui.update_network_stm32.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_network_stm32.setEnabled(True) self.ui.update_network_esp32.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_network_esp32.setEnabled(True) self.ui.update_network_stm32_bootloader.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_network_stm32_bootloader.setEnabled(True) if self.ui.is_english: self.ui.update_network_esp32_interpreter.setText("Update Network ESP32 Interpreter") else: self.ui.update_network_esp32_interpreter.setText("네트워크 모듈 인터프리터 초기화") else: self.__print("get network uuid") self.network_uuid = self.get_network_uuid() self.__print("Turning interpreter off...") self.write(b'{"c":160,"s":0,"d":18,"b":"AAMAAAAA","l":6}') self.update_in_progress = True self.__boot_to_app() self.__version_to_update = self.__get_latest_version() self.version = self.__get_esp_version() if self.version and self.version == self.__version_to_update: if not force and not self.ui: response = input(f"ESP version already up to date (v{self.version}). Do you still want to proceed? [y/n]: ") if "y" not in response: return self.__print(f"Updating v{self.version} to v{self.__version_to_update}") firmware_buffer = self.__compose_binary_firmware() self.__device_ready() self.__device_sync() self.__flash_attach() self.__set_flash_param() manager = None self.__write_binary_firmware(firmware_buffer, manager) self.__print("Booting to application...") self.__wait_for_json() self.__boot_to_app() time.sleep(1) self.__set_esp_version(self.__version_to_update) self.__print("ESP firmware update is complete!!") self.current_sequence = 100 self.total_sequence = 100 if self.ui: if self.ui.is_english: self.ui.update_network_esp32.setText("Network ESP32 update is in progress. (100%)") else: self.ui.update_network_esp32.setText("네트워크 모듈 업데이트가 진행중입니다. (100%)") time.sleep(1.5) self.flushInput() self.flushOutput() self.close() self.update_in_progress = False self.update_error = 1 if self.ui: self.ui.update_stm32_modules.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_stm32_modules.setEnabled(True) self.ui.update_network_stm32.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_network_stm32.setEnabled(True) self.ui.update_network_esp32_interpreter.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_network_esp32_interpreter.setEnabled(True) self.ui.update_network_stm32_bootloader.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_network_stm32_bootloader.setEnabled(True) if self.ui.is_english: self.ui.update_network_esp32.setText("Update Network ESP32") else: self.ui.update_network_esp32.setText("네트워크 모듈 업데이트") def get_network_uuid(self): init_time = time.time() while True: get_uuid_pkt = b'{"c":40,"s":4095,"d":4095,"b":"//8AAAAAAAA=","l":8}' self.write(get_uuid_pkt) try: json_msg = json.loads(self.__wait_for_json()) if json_msg["c"] == 0x05 or json_msg["c"] == 0x0A: module_uuid = unpack_data(json_msg["b"], (6, 2))[0] module_type = get_module_type_from_uuid(module_uuid) if module_type == "network": return module_uuid except json.decoder.JSONDecodeError as jde: self.__print("json parse error: " + str(jde)) if time.time() - init_time > 5: return None time.sleep(0.2) def __device_ready(self): self.__print("Redirecting connection to esp device...") self.write(b'{"c":43,"s":0,"d":4095,"b":"AA==","l":1}') def __device_sync(self): self.__print("Syncing the esp device...") sync_pkt = self.__parse_pkt( [0x0, self.DEVICE_SYNC, 0x24, 0, 0, 0, 0, 0, 0x7, 0x7, 0x12, 0x20] + 32 * [0x55] ) self.__send_pkt(sync_pkt, timeout=10, continuous=True) self.__print("Sync Complete") def __flash_attach(self): self.__print("Attaching flash to esp device..") attach_pkt = self.__parse_pkt( [0x0, self.SPI_ATTACH_REQ, 0x8] + 13 * [0] ) self.__send_pkt(attach_pkt, timeout=10) self.__print("Flash attach Complete") def __set_flash_param(self): self.__print("Setting esp flash parameter...") param_data = [0] * 32 fl_id, total_size, block_size, sector_size, page_size, status_mask = ( 0, 2 * 1024 * 1024, 64 * 1024, 4 * 1024, 256, 0xFFFF, ) param_data[1] = self.SPI_FLASH_SET param_data[2] = 0x18 param_data[8:12] = int.to_bytes(fl_id, length=4, byteorder="little") param_data[12:16] = int.to_bytes(total_size, length=4, byteorder="little") param_data[16:20] = int.to_bytes(block_size, length=4, byteorder="little") param_data[20:24] = int.to_bytes(sector_size, length=4, byteorder="little") param_data[24:28] = int.to_bytes(page_size, length=4, byteorder="little") param_data[28:32] = int.to_bytes(status_mask, length=4, byteorder="little") param_pkt = self.__parse_pkt(param_data) self.__send_pkt(param_pkt, timeout=10) self.__print("Parameter set complete") @staticmethod def __parse_pkt(data): pkt = bytes(data) pkt = pkt.replace(b"\xdb", b"\xdb\xdd").replace(b"\xc0", b"\xdb\xdc") pkt = b"\xc0" + pkt + b"\xc0" return pkt @retry(Exception) def __send_pkt(self, pkt, wait=True, timeout=None, continuous=False): self.write(pkt) self.reset_input_buffer() if wait: cmd = bytearray(pkt)[2] init_time = time.time() while not timeout or time.time() - init_time < timeout: if continuous: time.sleep(0.1) else: time.sleep(0.01) recv_pkt = self.__read_slip() if not recv_pkt: if continuous: self.__send_pkt(pkt, wait=False) continue recv_cmd = bytearray(recv_pkt)[2] if cmd == recv_cmd: if bytearray(recv_pkt)[1] != 0x01: self.update_error_message = "Packet error" if self.raise_error_message: raise Exception(self.update_error_message) else: self.update_error = -1 return True elif continuous: self.__send_pkt(pkt, wait=False) self.__print("Sending Again...") self.update_error_message = "Timeout Expired!" if self.raise_error_message: raise Exception(self.update_error_message) else: self.update_error = -1 def __read_slip(self): slip_pkt = b"" while slip_pkt != b"\xc0": slip_pkt = self.read() if slip_pkt == b"": return b"" slip_pkt += self.read_until(b"\xc0") return slip_pkt def __read_json(self): json_pkt = b"" while json_pkt != b"{": json_pkt = self.read() if json_pkt == b"": return "" time.sleep(0.1) json_pkt += self.read_until(b"}") return json_pkt def __wait_for_json(self): json_msg = self.__read_json() while not json_msg: json_msg = self.__read_json() time.sleep(0.1) return json_msg def __get_esp_version(self): init_time = time.time() while True: get_version_pkt = b'{"c":160,"s":25,"d":4095,"b":"AAAAAAAAAA==","l":8}' self.write(get_version_pkt) try: json_msg = json.loads(self.__wait_for_json()) if json_msg["c"] == 0xA1: break except json.decoder.JSONDecodeError as jde: self.__print("json parse error: " + str(jde)) if time.time() - init_time > 1: return None ver = b64decode(json_msg["b"]).lstrip(b"\x00") return ver.decode("ascii") def __set_esp_version(self, version_text: str): self.__print(f"Writing version info (v{version_text})") version_byte = version_text.encode("ascii") version_byte = b"\x00" * (8 - len(version_byte)) + version_byte version_text = b64encode(version_byte).decode("utf8") version_msg = ( "{" + f'"c":160,"s":24,"d":4095,' f'"b":"{version_text}","l":8' + "}" ) version_msg_enc = version_msg.encode("utf8") while True: self.write(version_msg_enc) try: json_msg = json.loads(self.__wait_for_json()) if json_msg["c"] == 0xA1: break self.__boot_to_app() except json.decoder.JSONDecodeError as jde: self.__print("json parse error: " + str(jde)) time.sleep(0.5) self.__print("The version info has been set!!") def __compose_binary_firmware(self): binary_firmware = b"" for i, bin_path in enumerate(self.file_path): if self.ui: if sys.platform.startswith("win"): root_path = pathlib.PurePosixPath(pathlib.PurePath(__file__),"..", "..", "assets", "firmware", "latest", "esp32") else: root_path = path.join(path.dirname(__file__), "..", "assets", "firmware", "latest", "esp32") if sys.platform.startswith("win"): firmware_path = pathlib.PurePosixPath(root_path, bin_path) else: firmware_path = path.join(root_path, bin_path) with open(firmware_path, "rb") as bin_file: bin_data = bin_file.read() else: root_path = path.join(path.dirname(__file__), "..", "assets", "firmware", "latest", "esp32") firmware_path = path.join(root_path, bin_path) with open(firmware_path, "rb") as bin_file: bin_data = bin_file.read() binary_firmware += bin_data if i < len(self.__address) - 1: binary_firmware += b"\xFF" * (self.__address[i + 1] - self.__address[i] - len(bin_data)) return binary_firmware def __get_latest_version(self): root_path = path.join(path.dirname(__file__), "..", "assets", "firmware", "latest", "esp32") version_path = path.join(root_path, "esp_version.txt") with open(version_path, "r") as version_file: version_info = version_file.readline().lstrip("v").rstrip("\n") return version_info def __erase_chunk(self, size, offset): num_blocks = size // self.ESP_FLASH_BLOCK + 1 erase_data = [0] * 24 erase_data[1] = self.ESP_FLASH_BEGIN erase_data[2] = 0x10 erase_data[8:12] = int.to_bytes(size, length=4, byteorder="little") erase_data[12:16] = int.to_bytes(num_blocks, length=4, byteorder="little") erase_data[16:20] = int.to_bytes(self.ESP_FLASH_BLOCK, length=4, byteorder="little") erase_data[20:24] = int.to_bytes(offset, length=4, byteorder="little") erase_pkt = self.__parse_pkt(erase_data) self.__send_pkt(erase_pkt, timeout=10) def __write_flash_block(self, data, seq_block): size = len(data) block_data = [0] * (size + 24) checksum = self.ESP_CHECKSUM_MAGIC block_data[1] = self.ESP_FLASH_DATA block_data[2:4] = int.to_bytes(size + 16, length=2, byteorder="little") block_data[8:12] = int.to_bytes(size, length=4, byteorder="little") block_data[12:16] = int.to_bytes(seq_block, length=4, byteorder="little") for i in range(size): block_data[24 + i] = data[i] checksum ^= 0xFF & data[i] block_data[4:8] = int.to_bytes(checksum, length=4, byteorder="little") block_pkt = self.__parse_pkt(block_data) self.__send_pkt(block_pkt) def __write_binary_firmware(self, binary_firmware: bytes, manager): chunk_queue = [] self.total_sequence = len(binary_firmware) // self.ESP_FLASH_BLOCK + 1 while binary_firmware: if self.ESP_FLASH_CHUNK < len(binary_firmware): chunk_queue.append(binary_firmware[: self.ESP_FLASH_CHUNK]) binary_firmware = binary_firmware[self.ESP_FLASH_CHUNK :] else: chunk_queue.append(binary_firmware[:]) binary_firmware = b"" blocks_downloaded = 0 self.current_sequence = blocks_downloaded self.__print("Start uploading firmware data...") for seq, chunk in enumerate(chunk_queue): self.__erase_chunk(len(chunk), self.__address[0] + seq * self.ESP_FLASH_CHUNK) blocks_downloaded += self.__write_chunk(chunk, blocks_downloaded, self.total_sequence, manager) if manager: manager.quit() if self.ui: if self.ui.is_english: self.ui.update_network_esp32.setText("Network ESP32 update is in progress. (99%)") else: self.ui.update_network_esp32.setText("네트워크 모듈 업데이트가 진행중입니다. (99%)") self.current_sequence = 99 self.total_sequence = 100 self.__print(f"\r{self.__progress_bar(99, 100)}") self.__print("Firmware Upload Complete") def __write_chunk(self, chunk, curr_seq, total_seq, manager): block_queue = [] while chunk: if self.ESP_FLASH_BLOCK < len(chunk): block_queue.append(chunk[: self.ESP_FLASH_BLOCK]) chunk = chunk[self.ESP_FLASH_BLOCK :] else: block_queue.append(chunk[:]) chunk = b"" for seq, block in enumerate(block_queue): self.current_sequence = curr_seq + seq if manager: manager.status = self.__progress_bar(curr_seq + seq, total_seq) if self.ui: if self.ui.is_english: self.ui.update_network_esp32.setText(f"Network ESP32 update is in progress. ({int((curr_seq+seq)/total_seq*100)}%)") else: self.ui.update_network_esp32.setText(f"네트워크 모듈 업데이트가 진행중입니다. ({int((curr_seq+seq)/total_seq*100)}%)") self.__print( f"\r{self.__progress_bar(curr_seq + seq, total_seq)}", end="" ) self.__write_flash_block(block, seq) return len(block_queue) def __boot_to_app(self): self.write(b'{"c":160,"s":0,"d":174,"b":"AAAAAAAAAA==","l":8}') def __print(self, data, end="\n"): if self.print: print(data, end) @staticmethod def __progress_bar(current: int, total: int) -> str: curr_bar = 50 * current // total rest_bar = 50 - curr_bar return ( f"Firmware Upload: [{"=" * curr_bar}>{"." * rest_bar}] " f"{100 * current / total:3.1f}%" ) class ESP32FirmwareMultiUpdater(): def __init__(self): self.update_in_progress = False self.ui = None self.list_ui = None def set_ui(self, ui, list_ui): self.ui = ui self.list_ui = list_ui def update_firmware(self, modi_ports, update_interpreter=False, force=True): self.esp32_updaters = [] self.network_uuid = [] self.state = [] for i, modi_port in enumerate(modi_ports): if i > 9: break try: esp32_updater = ESP32FirmwareUpdater(modi_port.device) esp32_updater.set_print(False) esp32_updater.set_raise_error(False) except Exception as e: print(e) else: self.esp32_updaters.append(esp32_updater) self.state.append(0) self.network_uuid.append('') if self.list_ui: self.list_ui.set_device_num(len(self.esp32_updaters)) self.list_ui.ui.close_button.setEnabled(False) self.update_in_progress = True for index, esp32_updater in enumerate(self.esp32_updaters): th.Thread( target=esp32_updater.update_firmware, args=(update_interpreter, force), daemon=True ).start() delay = 0.1 while True: is_done = True current_sequence = 0 total_sequence = 0 for index, esp32_updater in enumerate(self.esp32_updaters): if self.state[index] == 0: # wait for network uuid is_done = False if esp32_updater.update_in_progress: if esp32_updater.network_uuid: self.network_uuid[index] = f'0x{esp32_updater.network_uuid:X}' self.state[index] = 1 if self.list_ui: self.list_ui.network_uuid_signal.emit(index, self.network_uuid[index]) else: self.state[index] = 2 esp32_updater.update_error = -1 esp32_updater.update_error_message = "Not response network uuid" elif self.state[index] == 1: # update modules if esp32_updater.update_error == 0: is_done = is_done & False current = esp32_updater.current_sequence total = esp32_updater.total_sequence value = 0 if total == 0 else current / total * 100.0 current_sequence += current total_sequence += total if self.list_ui: self.list_ui.progress_signal.emit(index, value) else: self.state[index] = 2 elif self.state[index] == 2: # end current_sequence += esp32_updater.total_sequence total_sequence += esp32_updater.total_sequence if esp32_updater.update_error == 1: if self.list_ui: self.list_ui.network_state_signal.emit(index, 0) self.list_ui.progress_signal.emit(index, 100) else: if self.list_ui: self.list_ui.network_state_signal.emit(index, -1) self.list_ui.error_message_signal.emit(index, esp32_updater.update_error_message) self.state[index] = 3 elif self.state[index] == 3: total_sequence += 100 if total_sequence != 0: if self.ui: if update_interpreter: if self.ui.is_english: self.ui.update_network_esp32_interpreter.setText( f"Network ESP32 Interpreter reset is in progress. " f"({int(current_sequence/total_sequence*100)}%)" ) else: self.ui.update_network_esp32_interpreter.setText( f"네트워크 모듈 인터프리터 초기화가 진행중입니다. " f"({int(current_sequence/total_sequence*100)}%)" ) else: if self.ui.is_english: self.ui.update_network_esp32.setText( f"Network ESP32 update is in progress. " f"({int(current_sequence/total_sequence*100)}%)" ) else: self.ui.update_network_esp32.setText( f"네트워크 모듈 업데이트가 진행중입니다. " f"({int(current_sequence/total_sequence*100)}%)" ) if self.list_ui: self.list_ui.total_progress_signal.emit(current_sequence / total_sequence * 100.0) self.list_ui.total_status_signal.emit("Uploading...") print(f"\r{self.__progress_bar(current_sequence, total_sequence)}", end="") if is_done: break time.sleep(delay) self.update_in_progress = False if self.list_ui: self.list_ui.ui.close_button.setEnabled(True) self.list_ui.total_status_signal.emit("Complete") if update_interpreter: if self.ui: self.ui.update_stm32_modules.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_stm32_modules.setEnabled(True) self.ui.update_network_stm32.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_network_stm32.setEnabled(True) self.ui.update_network_stm32_bootloader.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_network_stm32_bootloader.setEnabled(True) self.ui.update_network_esp32.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_network_esp32.setEnabled(True) if self.ui.is_english: self.ui.update_network_esp32_interpreter.setText("Update Network ESP32 Interpreter") else: self.ui.update_network_esp32_interpreter.setText("네트워크 모듈 인터프리터 초기화") else: if self.ui: self.ui.update_stm32_modules.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_stm32_modules.setEnabled(True) self.ui.update_network_stm32.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_network_stm32.setEnabled(True) self.ui.update_network_stm32_bootloader.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_network_stm32_bootloader.setEnabled(True) self.ui.update_network_esp32_interpreter.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_network_esp32_interpreter.setEnabled(True) if self.ui.is_english: self.ui.update_network_esp32.setText("Update Network ESP32") else: self.ui.update_network_esp32.setText("네트워크 모듈 업데이트") print("\nESP firmware update is complete!!") @staticmethod def __progress_bar(current: int, total: int) -> str: curr_bar = int(50 * current // total) rest_bar = int(50 - curr_bar) return ( f"Firmware Upload: [{"=" * curr_bar}>{"." * rest_bar}] " f"{100 * current / total:3.1f}%" )
import io import json import pathlib import sys import threading as th import time from base64 import b64decode, b64encode from io import open from os import path import serial import serial.tools.list_ports as stl from modi_firmware_updater.util.connection_util import list_modi_ports from modi_firmware_updater.util.message_util import (decode_message, parse_message, unpack_data) from modi_firmware_updater.util.module_util import (Module, get_module_type_from_uuid) def retry(exception_to_catch): def decorator(func): def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except exception_to_catch: return wrapper(*args, **kwargs) return wrapper return decorator class ESP32FirmwareUpdater(serial.Serial): DEVICE_READY = 0x2B DEVICE_SYNC = 0x08 SPI_ATTACH_REQ = 0xD SPI_FLASH_SET = 0xB ESP_FLASH_BEGIN = 0x02 ESP_FLASH_DATA = 0x03 ESP_FLASH_END = 0x04 ESP_FLASH_BLOCK = 0x200 ESP_FLASH_CHUNK = 0x4000 ESP_CHECKSUM_MAGIC = 0xEF def __init__(self, device=None): self.print = True if device != None: super().__init__( device, timeout = 0.1, baudrate = 921600 ) else: modi_ports = list_modi_ports() if not modi_ports: raise serial.SerialException("No MODI port is connected") for modi_port in modi_ports: try: super().__init__( modi_port.device, timeout=0.1, baudrate=921600 ) except Exception: self.__print('Next network module') continue else: break self.__print(f"Connecting to MODI network module at {modi_port.device}") self.__address = [0x1000, 0x8000, 0xD000, 0x10000, 0xD0000] self.file_path = [ "bootloader.bin", "partitions.bin", "ota_data_initial.bin", "modi_ota_factory.bin", "esp32.bin", ] self.version = None self.__version_to_update = None self.update_in_progress = False self.ui = None self.current_sequence = 0 self.total_sequence = 0 self.raise_error_message = True self.update_error = 0 self.update_error_message = "" self.network_uuid = None def set_ui(self, ui): self.ui = ui def set_print(self, print): self.print = print def set_raise_error(self, raise_error_message): self.raise_error_message = raise_error_message def update_firmware(self, update_interpreter=False, force=False): if update_interpreter: self.current_sequence = 0 self.total_sequence = 1 self.__print("get network uuid") self.network_uuid = self.get_network_uuid() self.__print("Reset interpreter...") self.update_in_progress = True self.write(b'{"c":160,"s":0,"d":18,"b":"AAMAAAAA","l":6}') self.__print("ESP interpreter reset is complete!!") self.current_sequence = 1 self.total_sequence = 1 time.sleep(1) self.update_in_progress = False self.flushInput() self.flushOutput() self.close() self.update_error = 1 if self.ui: self.ui.update_stm32_modules.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_stm32_modules.setEnabled(True) self.ui.update_network_stm32.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_network_stm32.setEnabled(True) self.ui.update_network_esp32.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_network_esp32.setEnabled(True) self.ui.update_network_stm32_bootloader.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_network_stm32_bootloader.setEnabled(True) if self.ui.is_english: self.ui.update_network_esp32_interpreter.setText("Update Network ESP32 Interpreter") else: self.ui.update_network_esp32_interpreter.setText("네트워크 모듈 인터프리터 초기화") else: self.__print("get network uuid") self.network_uuid = self.get_network_uuid() self.__print("Turning interpreter off...") self.write(b'{"c":160,"s":0,"d":18,"b":"AAMAAAAA","l":6}') self.update_in_progress = True self.__boot_to_app() self.__version_to_update = self.__get_latest_version() self.version = self.__get_esp_version() if self.version and self.version == self.__version_to_update: if not force and not self.ui: response = input(f"ESP version already up to date (v{self.version}). Do you still want to proceed? [y/n]: ") if "y" not in response: return self.__print(f"Updating v{self.version} to v{self.__version_to_update}") firmware_buffer = self.__compose_binary_firmware() self.__device_ready() self.__device_sync() self.__flash_attach() self.__set_flash_param() manager = None self.__write_binary_firmware(firmware_buffer, manager) self.__print("Booting to application...") self.__wait_for_json() self.__boot_to_app() time.sleep(1) self.__set_esp_version(self.__version_to_update) self.__print("ESP firmware update is complete!!") self.current_sequence = 100 self.total_sequence = 100 if self.ui: if self.ui.is_english: self.ui.update_network_esp32.setText("Network ESP32 update is in progress. (100%)") else: self.ui.update_network_esp32.setText("네트워크 모듈 업데이트가 진행중입니다. (100%)") time.sleep(1.5) self.flushInput() self.flushOutput() self.close() self.update_in_progress = False self.update_error = 1 if self.ui: self.ui.update_stm32_modules.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_stm32_modules.setEnabled(True) self.ui.update_network_stm32.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_network_stm32.setEnabled(True) self.ui.update_network_esp32_interpreter.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_network_esp32_interpreter.setEnabled(True) self.ui.update_network_stm32_bootloader.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_network_stm32_bootloader.setEnabled(True) if self.ui.is_english: self.ui.update_network_esp32.setText("Update Network ESP32") else: self.ui.update_network_esp32.setText("네트워크 모듈 업데이트") def get_network_uuid(self): init_time = time.time() while True: get_uuid_pkt = b'{"c":40,"s":4095,"d":4095,"b":"//8AAAAAAAA=","l":8}' self.write(get_uuid_pkt) try: json_msg = json.loads(self.__wait_for_json()) if json_msg["c"] == 0x05 or json_msg["c"] == 0x0A: module_uuid = unpack_data(json_msg["b"], (6, 2))[0] module_type = get_module_type_from_uuid(module_uuid) if module_type == "network": return module_uuid except json.decoder.JSONDecodeError as jde: self.__print("json parse error: " + str(jde)) if time.time() - init_time > 5: return None time.sleep(0.2) def __device_ready(self): self.__print("Redirecting connection to esp device...") self.write(b'{"c":43,"s":0,"d":4095,"b":"AA==","l":1}') def __device_sync(self): self.__print("Syncing the esp device...") sync_pkt = self.__parse_pkt( [0x0, self.DEVICE_SYNC, 0x24, 0, 0, 0, 0, 0, 0x7, 0x7, 0x12, 0x20] + 32 * [0x55] ) self.__send_pkt(sync_pkt, timeout=10, continuous=True) self.__print("Sync Complete") def __flash_attach(self): self.__print("Attaching flash to esp device..") attach_pkt = self.__parse_pkt( [0x0, self.SPI_ATTACH_REQ, 0x8] + 13 * [0] ) self.__send_pkt(attach_pkt, timeout=10) self.__print("Flash attach Complete") def __set_flash_param(self): self.__print("Setting esp flash parameter...") param_data = [0] * 32 fl_id, total_size, block_size, sector_size, page_size, status_mask = ( 0, 2 * 1024 * 1024, 64 * 1024, 4 * 1024, 256, 0xFFFF, ) param_data[1] = self.SPI_FLASH_SET param_data[2] = 0x18 param_data[8:12] = int.to_bytes(fl_id, length=4, byteorder="little") param_data[12:16] = int.to_bytes(total_size, length=4, byteorder="little") param_data[16:20] = int.to_bytes(block_size, length=4, byteorder="little") param_data[20:24] = int.to_bytes(sector_size, length=4, byteorder="little") param_data[24:28] = int.to_bytes(page_size, length=4, byteorder="little") param_data[28:32] = int.to_bytes(status_mask, length=4, byteorder="little") param_pkt = self.__parse_pkt(param_data) self.__send_pkt(param_pkt, timeout=10) self.__print("Parameter set complete") @staticmethod def __parse_pkt(data): pkt = bytes(data) pkt = pkt.replace(b"\xdb", b"\xdb\xdd").replace(b"\xc0", b"\xdb\xdc") pkt = b"\xc0" + pkt + b"\xc0" return pkt @retry(Exception) def __send_pkt(self, pkt, wait=True, timeout=None, continuous=False): self.write(pkt) self.reset_input_buffer() if wait: cmd = bytearray(pkt)[2] init_time = time.time() while not timeout or time.time() - init_time < timeout: if continuous: time.sleep(0.1) else: time.sleep(0.01) recv_pkt = self.__read_slip() if not recv_pkt: if continuous: self.__send_pkt(pkt, wait=False) continue recv_cmd = bytearray(recv_pkt)[2] if cmd == recv_cmd: if bytearray(recv_pkt)[1] != 0x01: self.update_error_message = "Packet error" if self.raise_error_message: raise Exception(self.update_error_message) else: self.update_error = -1 return True elif continuous: self.__send_pkt(pkt, wait=False) self.__print("Sending Again...") self.update_error_message = "Timeout Expired!" if self.raise_error_message: raise Exception(self.update_error_message) else: self.update_error = -1 def __read_slip(self): slip_pkt = b"" while slip_pkt != b"\xc0": slip_pkt = self.read() if slip_pkt == b"": return b"" slip_pkt += self.read_until(b"\xc0") return slip_pkt def __read_json(self): json_pkt = b"" while json_pkt != b"{": json_pkt = self.read() if json_pkt == b"": return "" time.sleep(0.1) json_pkt += self.read_until(b"}") return json_pkt def __wait_for_json(self): json_msg = self.__read_json() while not json_msg: json_msg = self.__read_json() time.sleep(0.1) return json_msg def __get_esp_version(self): init_time = time.time() while True: get_version_pkt = b'{"c":160,"s":25,"d":4095,"b":"AAAAAAAAAA==","l":8}' self.write(get_version_pkt) try: json_msg = json.loads(self.__wait_for_json()) if json_msg["c"] == 0xA1: break except json.decoder.JSONDecodeError as jde: self.__print("json parse error: " + str(jde)) if time.time() - init_time > 1: return None ver = b64decode(json_msg["b"]).lstrip(b"\x00") return ver.decode("ascii") def __set_esp_version(self, version_text: str): self.__print(f"Writing version info (v{version_text})") version_byte = version_text.encode("ascii") version_byte = b"\x00" * (8 - len(version_byte)) + version_byte version_text = b64encode(version_byte).decode("utf8") version_msg = ( "{" + f'"c":160,"s":24,"d":4095,' f'"b":"{version_text}","l":8' + "}" ) version_msg_enc = version_msg.encode("utf8") while True: self.write(version_msg_enc) try: json_msg = json.loads(self.__wait_for_json()) if json_msg["c"] == 0xA1: break self.__boot_to_app() except json.decoder.JSONDecodeError as jde: self.__print("json parse error: " + str(jde)) time.sleep(0.5) self.__print("The version info has been set!!") def __compose_binary_firmware(self): binary_firmware = b"" for i, bin_path in enumerate(self.file_path): if self.ui: if sys.platform.startswith("win"): root_path = pathlib.PurePosixPath(pathlib.PurePath(__file__),"..", "..", "assets", "firmware", "latest", "esp32") else: root_path = path.join(path.dirname(__file__), "..", "assets", "firmware", "latest", "esp32") if sys.platform.startswith("win"): firmware_path = pathlib.PurePosixPath(root_path, bin_path) else: firmware_path = path.join(root_path, bin_path) with open(firmware_path, "rb") as bin_file: bin_data = bin_file.read() else: root_path = path.join(path.dirname(__file__), "..", "assets", "firmware", "latest", "esp32") firmware_path = path.join(root_path, bin_path) with open(firmware_path, "rb") as bin_file: bin_data = bin_file.read() binary_firmware += bin_data if i < len(self.__address) - 1: binary_firmware += b"\xFF" * (self.__address[i + 1] - self.__address[i] - len(bin_data)) return binary_firmware def __get_latest_version(self): root_path = path.join(path.dirname(__file__), "..", "assets", "firmware", "latest", "esp32") version_path = path.join(root_path, "esp_version.txt") with open(version_path, "r") as version_file: version_info = version_file.readline().lstrip("v").rstrip("\n") return version_info def __erase_chunk(self, size, offset): num_blocks = size // self.ESP_FLASH_BLOCK + 1 erase_data = [0] * 24 erase_data[1] = self.ESP_FLASH_BEGIN erase_data[2] = 0x10 erase_data[8:12] = int.to_bytes(size, length=4, byteorder="little") erase_data[12:16] = int.to_bytes(num_blocks, length=4, byteorder="little") erase_data[16:20] = int.to_bytes(self.ESP_FLASH_BLOCK, length=4, byteorder="little") erase_data[20:24] = int.to_bytes(offset, length=4, byteorder="little") erase_pkt = self.__parse_pkt(erase_data) self.__send_pkt(erase_pkt, timeout=10) def __write_flash_block(self, data, seq_block): size = len(data) block_data = [0] * (size + 24) checksum = self.ESP_CHECKSUM_MAGIC block_data[1] = self.ESP_FLASH_DATA block_data[2:4] = int.to_bytes(size + 16, length=2, byteorder="little") block_data[8:12] = int.to_bytes(size, length=4, byteorder="little") block_data[12:16] = int.to_bytes(seq_block, length=4, byteorder="little") for i in range(size): block_data[24 + i] = data[i] checksum ^= 0xFF & data[i] block_data[4:8] = int.to_bytes(checksum, length=4, byteorder="little") block_pkt = self.__parse_pkt(block_data) self.__send_pkt(block_pkt) def __write_binary_firmware(self, binary_firmware: bytes, manager): chunk_queue = [] self.total_sequence = len(binary_firmware) // self.ESP_FLASH_BLOCK + 1 while binary_firmware: if self.ESP_FLASH_CHUNK < len(binary_firmware): chunk_queue.append(binary_firmware[: self.ESP_FLASH_CHUNK]) binary_firmware = binary_firmware[self.ESP_FLASH_CHUNK :] else: chunk_queue.append(binary_firmware[:]) binary_firmware = b"" blocks_downloaded = 0 self.current_sequence = blocks_downloaded self.__print("Start uploading firmware data...") for seq, chunk in enumerate(chunk_queue): self.__erase_chunk(len(chunk), self.__address[0] + seq * self.ESP_FLASH_CHUNK) blocks_downloaded += self.__write_chunk(chunk, blocks_downloaded, self.total_sequence, manager) if manager: manager.quit() if self.ui: if self.ui.is_english: self.ui.update_network_esp32.setText("Network ESP32 update is in progress. (99%)") else: self.ui.update_network_esp32.setText("네트워크 모듈 업데이트가 진행중입니다. (99%)") self.current_sequence = 99 self.total_sequence = 100 self.__print(f"\r{self.__progress_bar(99, 100)}") self.__print("Firmware Upload Complete") def __write_chunk(self, chunk, curr_seq, total_seq, manager): block_queue = [] while chunk: if self.ESP_FLASH_BLOCK < len(chunk): block_queue.append(chunk[: self.ESP_FLASH_BLOCK]) chunk = chunk[self.ESP_FLASH_BLOCK :] else: block_queue.append(chunk[:]) chunk = b"" for seq, block in enumerate(block_queue): self.current_sequence = curr_seq + seq if manager: manager.status = self.__progress_bar(curr_seq + seq, total_seq) if self.ui: if self.ui.is_english: self.ui.update_network_esp32.setText(f"Network ESP32 update is in progress. ({int((curr_seq+seq)/total_seq*100)}%)") else: self.ui.update_network_esp32.setText(f"네트워크 모듈 업데이트가 진행중입니다. ({int((curr_seq+seq)/total_seq*100)}%)") self.__print( f"\r{self.__progress_bar(curr_seq + seq, total_seq)}", end="" ) self.__write_flash_block(block, seq) return len(block_queue) def __boot_to_app(self): self.write(b'{"c":160,"s":0,"d":174,"b":"AAAAAAAAAA==","l":8}') def __print(self, data, end="\n"): if self.print: print(data, end) @staticmethod def __progress_bar(current: int, total: int) -> str: curr_bar = 50 * current // total rest_bar = 50 - curr_bar return ( f"Firmware Upload: [{'=' * curr_bar}>{'.' * rest_bar}] " f"{100 * current / total:3.1f}%" ) class ESP32FirmwareMultiUpdater(): def __init__(self): self.update_in_progress = False self.ui = None self.list_ui = None def set_ui(self, ui, list_ui): self.ui = ui self.list_ui = list_ui def update_firmware(self, modi_ports, update_interpreter=False, force=True): self.esp32_updaters = [] self.network_uuid = [] self.state = [] for i, modi_port in enumerate(modi_ports): if i > 9: break try: esp32_updater = ESP32FirmwareUpdater(modi_port.device) esp32_updater.set_print(False) esp32_updater.set_raise_error(False) except Exception as e: print(e) else: self.esp32_updaters.append(esp32_updater) self.state.append(0) self.network_uuid.append('') if self.list_ui: self.list_ui.set_device_num(len(self.esp32_updaters)) self.list_ui.ui.close_button.setEnabled(False) self.update_in_progress = True for index, esp32_updater in enumerate(self.esp32_updaters): th.Thread( target=esp32_updater.update_firmware, args=(update_interpreter, force), daemon=True ).start() delay = 0.1 while True: is_done = True current_sequence = 0 total_sequence = 0 for index, esp32_updater in enumerate(self.esp32_updaters): if self.state[index] == 0: # wait for network uuid is_done = False if esp32_updater.update_in_progress: if esp32_updater.network_uuid: self.network_uuid[index] = f'0x{esp32_updater.network_uuid:X}' self.state[index] = 1 if self.list_ui: self.list_ui.network_uuid_signal.emit(index, self.network_uuid[index]) else: self.state[index] = 2 esp32_updater.update_error = -1 esp32_updater.update_error_message = "Not response network uuid" elif self.state[index] == 1: # update modules if esp32_updater.update_error == 0: is_done = is_done & False current = esp32_updater.current_sequence total = esp32_updater.total_sequence value = 0 if total == 0 else current / total * 100.0 current_sequence += current total_sequence += total if self.list_ui: self.list_ui.progress_signal.emit(index, value) else: self.state[index] = 2 elif self.state[index] == 2: # end current_sequence += esp32_updater.total_sequence total_sequence += esp32_updater.total_sequence if esp32_updater.update_error == 1: if self.list_ui: self.list_ui.network_state_signal.emit(index, 0) self.list_ui.progress_signal.emit(index, 100) else: if self.list_ui: self.list_ui.network_state_signal.emit(index, -1) self.list_ui.error_message_signal.emit(index, esp32_updater.update_error_message) self.state[index] = 3 elif self.state[index] == 3: total_sequence += 100 if total_sequence != 0: if self.ui: if update_interpreter: if self.ui.is_english: self.ui.update_network_esp32_interpreter.setText( f"Network ESP32 Interpreter reset is in progress. " f"({int(current_sequence/total_sequence*100)}%)" ) else: self.ui.update_network_esp32_interpreter.setText( f"네트워크 모듈 인터프리터 초기화가 진행중입니다. " f"({int(current_sequence/total_sequence*100)}%)" ) else: if self.ui.is_english: self.ui.update_network_esp32.setText( f"Network ESP32 update is in progress. " f"({int(current_sequence/total_sequence*100)}%)" ) else: self.ui.update_network_esp32.setText( f"네트워크 모듈 업데이트가 진행중입니다. " f"({int(current_sequence/total_sequence*100)}%)" ) if self.list_ui: self.list_ui.total_progress_signal.emit(current_sequence / total_sequence * 100.0) self.list_ui.total_status_signal.emit("Uploading...") print(f"\r{self.__progress_bar(current_sequence, total_sequence)}", end="") if is_done: break time.sleep(delay) self.update_in_progress = False if self.list_ui: self.list_ui.ui.close_button.setEnabled(True) self.list_ui.total_status_signal.emit("Complete") if update_interpreter: if self.ui: self.ui.update_stm32_modules.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_stm32_modules.setEnabled(True) self.ui.update_network_stm32.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_network_stm32.setEnabled(True) self.ui.update_network_stm32_bootloader.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_network_stm32_bootloader.setEnabled(True) self.ui.update_network_esp32.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_network_esp32.setEnabled(True) if self.ui.is_english: self.ui.update_network_esp32_interpreter.setText("Update Network ESP32 Interpreter") else: self.ui.update_network_esp32_interpreter.setText("네트워크 모듈 인터프리터 초기화") else: if self.ui: self.ui.update_stm32_modules.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_stm32_modules.setEnabled(True) self.ui.update_network_stm32.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_network_stm32.setEnabled(True) self.ui.update_network_stm32_bootloader.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_network_stm32_bootloader.setEnabled(True) self.ui.update_network_esp32_interpreter.setStyleSheet(f"border-image: url({self.ui.active_path}); font-size: 16px") self.ui.update_network_esp32_interpreter.setEnabled(True) if self.ui.is_english: self.ui.update_network_esp32.setText("Update Network ESP32") else: self.ui.update_network_esp32.setText("네트워크 모듈 업데이트") print("\nESP firmware update is complete!!") @staticmethod def __progress_bar(current: int, total: int) -> str: curr_bar = int(50 * current // total) rest_bar = int(50 - curr_bar) return ( f"Firmware Upload: [{'=' * curr_bar}>{'.' * rest_bar}] " f"{100 * current / total:3.1f}%" )
import os import re from datetime import ( datetime as dt, timedelta ) import requests from requests.auth import HTTPDigestAuth from requests.exceptions import ConnectionError from typing import ( Optional, List, Dict, Union ) import amcrest from loguru import logger from reolink_api import Camera from kavalkilu import Keys # TODO: # - add get_dimensions (sub or main stream) methods to both classes # - add means of drawing motion on captured frames inside each class # - include an option to clip only frames that have motion with a bit of buffer class Reolink(Camera): """Wrapper for Reolink's Camera class""" def __init__(self, ip: str, parent_log: logger = None): self.ip = ip self.logg = parent_log.bind(child_name=self.__class__.__name__) creds = Keys().get_key('webcam') super().__init__(self.ip, username=creds['un'], password=creds['pw']) def snapshot(self, filepath: str) -> bool: """Takes a snapshot - mirrors the similar method in Amcrest, though these POE cameras seem to be more stable with regards to connectivity""" self.logg.debug('Taking snapshot...') img = self.get_snap() img.save(filepath) return True def get_dimensions(self, stream: str = 'sub') -> List[int]: """Gets the video dimensions of the camera's stream""" dims = self.get_recording_encoding()[0]['initial']['Enc'][f'{stream.lower()}Stream']['size'] # Split by '*', convert to int dims = [int(x) for x in dims.split('*')] return dims class Amcrest: """Amcrest camera-related methods""" camera_types = { 'DB': 'doorbell', 'IPC': 'ip_cam' } def __init__(self, ip: str, port: int = 80, parent_log: logger = None): self.ip = ip self.logg = parent_log.bind(child_name=self.__class__.__name__) self.creds = Keys().get_key('webcam') self.base_url = f'http://{ip}/cgi-bin' self.base_url_with_cred = f'http://{self.creds['un']}:{self.creds['pw']}@{ip}/cgi-bin' self.config_url = f'{self.base_url}/configManager.cgi?action=setConfig' try: self.camera = amcrest.AmcrestCamera(ip, port, self.creds['un'], self.creds['pw']).camera self.is_connected = True name = re.search(r'(?<=Name=).*(?=\r)', self.camera.video_channel_title).group() model = re.search(r'(?<=type=).*(?=\r)', self.camera.device_type).group() camera_type = re.search(r'(?<=class=).*(?=\r)', self.camera.device_class).group() except (ConnectionError, amcrest.exceptions.CommError) as e: self.camera = None self.is_connected = False name = model = camera_type = 'unknown' if self.camera is not None: if camera_type in self.camera_types.keys(): self.camera_type = self.camera_types[camera_type] else: self.camera_type = 'other' self.is_armed = self.camera.is_motion_detector_on() self.is_ptz_enabled = self._check_for_ptz() else: self.camera_type = 'other' self.name = name.lower() self.model = model.lower() def _check_for_ptz(self) -> bool: """Checks if camera is capable of ptz actions""" try: return True if self.camera.ptz_presets_list() != '' else False except amcrest.exceptions.CommError: return False def _send_request(self, req_str: str): """Sends an HTTP request""" result = requests.get(req_str, auth=HTTPDigestAuth(self.creds['un'], self.creds['pw'])) if result.status_code != 200: raise Exception('Error in HTTP GET response. Status code: ' f'{result.status_code}, Message: {result.text}') def toggle_motion(self, set_motion: bool = True): """Sets motion detection""" if self.camera is None or not self.is_connected: return None if self.is_armed == set_motion: # State is already where we wanted it to be; no need to change return None motion_val = 'true' if set_motion else 'false' motion_url = f'{self.config_url}&MotionDetect[0].Enable={motion_val}' self._send_request(motion_url) def set_ptz_flag(self, armed: bool): """Orients PTZ-enabled cameras either to armed position (1) or disarmed (2)""" if self.is_ptz_enabled: # This is likely PTZ-enabled # Set to target flag preset_pt = 1 if armed else 2 resp = self.camera.go_to_preset(action='start', preset_point_number=preset_pt) if resp[:2] != 'OK': # Something went wrong. Raise exception so it gets logged raise Exception(f'Camera "{self.name}" PTZ call ' f'saw unexpected response: "{resp}"') def get_current_ptz_coordinates(self) -> Optional[str]: """Gets the current xyz coordinates for a PTZ-enabled camera""" if self.is_ptz_enabled: ptz_list = self.camera.ptz_status().split('\r\n')[2:5] return ','.join([x.split('=')[1] for x in ptz_list]) def arm_camera(self, armed: bool = True): """Wrapper method that both arms the motion detection setting as well as orients a PTZ enabled camera to the ARMED position""" if self.camera is None: return None self.toggle_motion(armed) if self.is_ptz_enabled: self.set_ptz_flag(armed) def snapshot(self, filepath: str) -> bool: """Takes a snapshot using the main stream (0)""" self.logg.debug('Getting snapshot...') res = self.camera.snapshot(0, filepath) self.logg.debug(f'Response from snapshot: {res.status}') if res.status != 200: return False return True @staticmethod def _consolidate_events(events: List[Dict[str, Union[str, dt]]], limit_s: int = 60, default_s: int = 60) -> Optional[List[Dict[str, dt]]]: """Takes in a list of motion events and consolidates them if they're within range of each other Args: limit_s: limit in seconds, after which two events are actually considered separate default_s: if no start/end time provided, the end with be this amount of seconds added to the missing start/end time """ # First step is to pair event starts and ends new_event = {} new_events = [] for event in events: if all([x in new_event.keys() for x in ['start', 'end']]): # All keys have been added. Append to the list new_events.append(new_event) new_event = {} if len(new_event.keys()) == 0: # New dict if event['type'] == 'Event End': # Event end before begin; this likely means a motion event started # before our time range. Use default lookbehind to estimate the event start new_event['start'] = event['time'] - timedelta(seconds=default_s) start_or_end = 'start' if 'Begin' in event['type'] else 'end' # Populate common parts of event info new_event.update({ start_or_end: event['time'], 'region': event['detail.region-name'].lower(), 'channel': int(event['detail.channel-no.']), 'event-type': event['detail.event-type'].lower() }) if len(new_event) != 0: # Make sure we also have an end to this last event if 'end' not in new_event.keys(): new_event['end'] = new_event['start'] + timedelta(seconds=default_s) new_events.append(new_event) # Now combine individual events if they occur within {limit_s} to each other combi_event = {'event-list': []} combi_events = [] prev_event_end = None if len(new_events) == 0: return [] for event in new_events: # Calculate the diff if prev_event_end is not None: diff = (event['start'] - prev_event_end).seconds else: # First event diff = 0 # Compare diff; determine whether to combine if diff <= limit_s: # Combine current start and previous end combi_event['event-list'].append(event) else: # diff exceeds limit; split into another combi event combi_event.update({ 'start': min([x['start'] for x in combi_event['event-list']]), 'end': max([x['end'] for x in combi_event['event-list']]) }) combi_events.append(combi_event) # Reset dict combi_event = { 'event-list': [event] } prev_event_end = event['end'] if len(combi_event['event-list']) > 0: # Info remaining in combi_event combi_event.update({ 'start': min([x['start'] for x in combi_event['event-list']]), 'end': max([x['end'] for x in combi_event['event-list']]) }) combi_events.append(combi_event) return combi_events def get_motion_log(self, start_dt: dt, end_dt: dt) -> List[dict]: """Returns log of motion detection events between two timestamps""" # Get logs for given range # Amcrest does a kind of tokenization that allows us to grab # logs in batches of 100. Tokens seem to be just sequential ints # and are not page numbers! Once the end of the log is reached, # the 'found' variable will be 0. raw_token = self.camera.log_find_start(start_dt, end_dt) token = re.search(r'(?!token=)\d+', raw_token).group(0) events = [] item_dict = {} cur_item_no = 0 while True: log_batch = self.camera.log_find_next(token, count=100) raw_logs = log_batch.split('\r\n') batch_size = int(re.search(r'(?!found=)\d+', log_batch).group(0)) if batch_size == 0: break # Sift through logs, build out events for logstr in raw_logs: # Make sure we're getting an item and not any other info if re.search(r'(?<=items\[)\d+', logstr): # Get item number item_no = int(re.search(r'(?<=items)\[(\d+)]', logstr).group(1)) # Get & clean the name of the item item_name = re.search(r'(?<=]\.).*(?==)', logstr).group(0).lower().replace(' ', '-') item_name = re.sub(r'\[\d+]', '', item_name) # The value after the item name item_value = re.search(r'(?<==).*', logstr).group(0) if item_name == 'time': # Convert to datetime item_value = dt.strptime(item_value, '%Y-%m-%d %H:%M:%S') if item_no != cur_item_no: # New item - move item dict to events and initiate new one events.append(item_dict) item_dict = {item_name: item_value} cur_item_no = item_no else: # Same item - add to existing dict item_dict[item_name] = item_value # Of the events that are motion related mevents = [x for x in events if x.get('detail.event-type', '') == 'Motion Detect'] # Reverse the order of events so they're chronological mevents.reverse() return self._consolidate_events(mevents) @staticmethod def extract_timestamp(fpath: str) -> str: """Extracts a timestamp from the filepath""" final = [] regex = [ r'(?<=\/sd\/)\d{4}(-\d{2}){2}', r'(?<=\/dav\/\d{2}\/)\d{2}(\.\d{2}){2}-\d{2}(\.\d{2}){2}' ] for rgx in regex: match = re.search(rgx, fpath) if match is not None: final.append(match.group()) return '_'.join(final).replace('.', ':') def download_files_from_range(self, start_dt: dt, end_dt: dt, temp_dir: str) -> List[dict]: """Downloads mp4 files from a set datetime range""" file_dicts = [] for text in self.camera.find_files(start_dt, end_dt): for line in text.split('\r\n'): key, value = list(line.split('=', 1) + [None])[:2] if key.endswith('.FilePath'): if value.endswith('.mp4'): ts = self.extract_timestamp(value) dt_objs = [] date_dt = dt.strptime(ts.split('_')[0], '%Y-%m-%d') for t in ts.split('_')[1].split('-'): dt_objs.append(dt.combine(date_dt, dt.strptime(t, '%H:%M:%S').time())) new_filename = f'{ts}.mp4' fpath = os.path.join(temp_dir, new_filename) file_dicts.append({ 'start': dt_objs[0], 'end': dt_objs[1], 'path': fpath }) with open(fpath, 'wb') as f: f.write(self.camera.download_file(value)) return file_dicts def get_video_stream(self, channel: int = 0, subtype: int = 1) -> str: """ Outputs the video stream url Args: channel: int, which channel to use. default = 0 subtype: int, stream type to use. 0 = main, 1 = extra_1, etc default = 1 Returns: str, the url to the stream """ return f'{self.base_url_with_cred}/mjpg/video.cgi?channel={channel}&subtype={subtype}'
import os import re from datetime import ( datetime as dt, timedelta ) import requests from requests.auth import HTTPDigestAuth from requests.exceptions import ConnectionError from typing import ( Optional, List, Dict, Union ) import amcrest from loguru import logger from reolink_api import Camera from kavalkilu import Keys # TODO: # - add get_dimensions (sub or main stream) methods to both classes # - add means of drawing motion on captured frames inside each class # - include an option to clip only frames that have motion with a bit of buffer class Reolink(Camera): """Wrapper for Reolink's Camera class""" def __init__(self, ip: str, parent_log: logger = None): self.ip = ip self.logg = parent_log.bind(child_name=self.__class__.__name__) creds = Keys().get_key('webcam') super().__init__(self.ip, username=creds['un'], password=creds['pw']) def snapshot(self, filepath: str) -> bool: """Takes a snapshot - mirrors the similar method in Amcrest, though these POE cameras seem to be more stable with regards to connectivity""" self.logg.debug('Taking snapshot...') img = self.get_snap() img.save(filepath) return True def get_dimensions(self, stream: str = 'sub') -> List[int]: """Gets the video dimensions of the camera's stream""" dims = self.get_recording_encoding()[0]['initial']['Enc'][f'{stream.lower()}Stream']['size'] # Split by '*', convert to int dims = [int(x) for x in dims.split('*')] return dims class Amcrest: """Amcrest camera-related methods""" camera_types = { 'DB': 'doorbell', 'IPC': 'ip_cam' } def __init__(self, ip: str, port: int = 80, parent_log: logger = None): self.ip = ip self.logg = parent_log.bind(child_name=self.__class__.__name__) self.creds = Keys().get_key('webcam') self.base_url = f'http://{ip}/cgi-bin' self.base_url_with_cred = f'http://{self.creds["un"]}:{self.creds["pw"]}@{ip}/cgi-bin' self.config_url = f'{self.base_url}/configManager.cgi?action=setConfig' try: self.camera = amcrest.AmcrestCamera(ip, port, self.creds['un'], self.creds['pw']).camera self.is_connected = True name = re.search(r'(?<=Name=).*(?=\r)', self.camera.video_channel_title).group() model = re.search(r'(?<=type=).*(?=\r)', self.camera.device_type).group() camera_type = re.search(r'(?<=class=).*(?=\r)', self.camera.device_class).group() except (ConnectionError, amcrest.exceptions.CommError) as e: self.camera = None self.is_connected = False name = model = camera_type = 'unknown' if self.camera is not None: if camera_type in self.camera_types.keys(): self.camera_type = self.camera_types[camera_type] else: self.camera_type = 'other' self.is_armed = self.camera.is_motion_detector_on() self.is_ptz_enabled = self._check_for_ptz() else: self.camera_type = 'other' self.name = name.lower() self.model = model.lower() def _check_for_ptz(self) -> bool: """Checks if camera is capable of ptz actions""" try: return True if self.camera.ptz_presets_list() != '' else False except amcrest.exceptions.CommError: return False def _send_request(self, req_str: str): """Sends an HTTP request""" result = requests.get(req_str, auth=HTTPDigestAuth(self.creds['un'], self.creds['pw'])) if result.status_code != 200: raise Exception('Error in HTTP GET response. Status code: ' f'{result.status_code}, Message: {result.text}') def toggle_motion(self, set_motion: bool = True): """Sets motion detection""" if self.camera is None or not self.is_connected: return None if self.is_armed == set_motion: # State is already where we wanted it to be; no need to change return None motion_val = 'true' if set_motion else 'false' motion_url = f'{self.config_url}&MotionDetect[0].Enable={motion_val}' self._send_request(motion_url) def set_ptz_flag(self, armed: bool): """Orients PTZ-enabled cameras either to armed position (1) or disarmed (2)""" if self.is_ptz_enabled: # This is likely PTZ-enabled # Set to target flag preset_pt = 1 if armed else 2 resp = self.camera.go_to_preset(action='start', preset_point_number=preset_pt) if resp[:2] != 'OK': # Something went wrong. Raise exception so it gets logged raise Exception(f'Camera "{self.name}" PTZ call ' f'saw unexpected response: "{resp}"') def get_current_ptz_coordinates(self) -> Optional[str]: """Gets the current xyz coordinates for a PTZ-enabled camera""" if self.is_ptz_enabled: ptz_list = self.camera.ptz_status().split('\r\n')[2:5] return ','.join([x.split('=')[1] for x in ptz_list]) def arm_camera(self, armed: bool = True): """Wrapper method that both arms the motion detection setting as well as orients a PTZ enabled camera to the ARMED position""" if self.camera is None: return None self.toggle_motion(armed) if self.is_ptz_enabled: self.set_ptz_flag(armed) def snapshot(self, filepath: str) -> bool: """Takes a snapshot using the main stream (0)""" self.logg.debug('Getting snapshot...') res = self.camera.snapshot(0, filepath) self.logg.debug(f'Response from snapshot: {res.status}') if res.status != 200: return False return True @staticmethod def _consolidate_events(events: List[Dict[str, Union[str, dt]]], limit_s: int = 60, default_s: int = 60) -> Optional[List[Dict[str, dt]]]: """Takes in a list of motion events and consolidates them if they're within range of each other Args: limit_s: limit in seconds, after which two events are actually considered separate default_s: if no start/end time provided, the end with be this amount of seconds added to the missing start/end time """ # First step is to pair event starts and ends new_event = {} new_events = [] for event in events: if all([x in new_event.keys() for x in ['start', 'end']]): # All keys have been added. Append to the list new_events.append(new_event) new_event = {} if len(new_event.keys()) == 0: # New dict if event['type'] == 'Event End': # Event end before begin; this likely means a motion event started # before our time range. Use default lookbehind to estimate the event start new_event['start'] = event['time'] - timedelta(seconds=default_s) start_or_end = 'start' if 'Begin' in event['type'] else 'end' # Populate common parts of event info new_event.update({ start_or_end: event['time'], 'region': event['detail.region-name'].lower(), 'channel': int(event['detail.channel-no.']), 'event-type': event['detail.event-type'].lower() }) if len(new_event) != 0: # Make sure we also have an end to this last event if 'end' not in new_event.keys(): new_event['end'] = new_event['start'] + timedelta(seconds=default_s) new_events.append(new_event) # Now combine individual events if they occur within {limit_s} to each other combi_event = {'event-list': []} combi_events = [] prev_event_end = None if len(new_events) == 0: return [] for event in new_events: # Calculate the diff if prev_event_end is not None: diff = (event['start'] - prev_event_end).seconds else: # First event diff = 0 # Compare diff; determine whether to combine if diff <= limit_s: # Combine current start and previous end combi_event['event-list'].append(event) else: # diff exceeds limit; split into another combi event combi_event.update({ 'start': min([x['start'] for x in combi_event['event-list']]), 'end': max([x['end'] for x in combi_event['event-list']]) }) combi_events.append(combi_event) # Reset dict combi_event = { 'event-list': [event] } prev_event_end = event['end'] if len(combi_event['event-list']) > 0: # Info remaining in combi_event combi_event.update({ 'start': min([x['start'] for x in combi_event['event-list']]), 'end': max([x['end'] for x in combi_event['event-list']]) }) combi_events.append(combi_event) return combi_events def get_motion_log(self, start_dt: dt, end_dt: dt) -> List[dict]: """Returns log of motion detection events between two timestamps""" # Get logs for given range # Amcrest does a kind of tokenization that allows us to grab # logs in batches of 100. Tokens seem to be just sequential ints # and are not page numbers! Once the end of the log is reached, # the 'found' variable will be 0. raw_token = self.camera.log_find_start(start_dt, end_dt) token = re.search(r'(?!token=)\d+', raw_token).group(0) events = [] item_dict = {} cur_item_no = 0 while True: log_batch = self.camera.log_find_next(token, count=100) raw_logs = log_batch.split('\r\n') batch_size = int(re.search(r'(?!found=)\d+', log_batch).group(0)) if batch_size == 0: break # Sift through logs, build out events for logstr in raw_logs: # Make sure we're getting an item and not any other info if re.search(r'(?<=items\[)\d+', logstr): # Get item number item_no = int(re.search(r'(?<=items)\[(\d+)]', logstr).group(1)) # Get & clean the name of the item item_name = re.search(r'(?<=]\.).*(?==)', logstr).group(0).lower().replace(' ', '-') item_name = re.sub(r'\[\d+]', '', item_name) # The value after the item name item_value = re.search(r'(?<==).*', logstr).group(0) if item_name == 'time': # Convert to datetime item_value = dt.strptime(item_value, '%Y-%m-%d %H:%M:%S') if item_no != cur_item_no: # New item - move item dict to events and initiate new one events.append(item_dict) item_dict = {item_name: item_value} cur_item_no = item_no else: # Same item - add to existing dict item_dict[item_name] = item_value # Of the events that are motion related mevents = [x for x in events if x.get('detail.event-type', '') == 'Motion Detect'] # Reverse the order of events so they're chronological mevents.reverse() return self._consolidate_events(mevents) @staticmethod def extract_timestamp(fpath: str) -> str: """Extracts a timestamp from the filepath""" final = [] regex = [ r'(?<=\/sd\/)\d{4}(-\d{2}){2}', r'(?<=\/dav\/\d{2}\/)\d{2}(\.\d{2}){2}-\d{2}(\.\d{2}){2}' ] for rgx in regex: match = re.search(rgx, fpath) if match is not None: final.append(match.group()) return '_'.join(final).replace('.', ':') def download_files_from_range(self, start_dt: dt, end_dt: dt, temp_dir: str) -> List[dict]: """Downloads mp4 files from a set datetime range""" file_dicts = [] for text in self.camera.find_files(start_dt, end_dt): for line in text.split('\r\n'): key, value = list(line.split('=', 1) + [None])[:2] if key.endswith('.FilePath'): if value.endswith('.mp4'): ts = self.extract_timestamp(value) dt_objs = [] date_dt = dt.strptime(ts.split('_')[0], '%Y-%m-%d') for t in ts.split('_')[1].split('-'): dt_objs.append(dt.combine(date_dt, dt.strptime(t, '%H:%M:%S').time())) new_filename = f'{ts}.mp4' fpath = os.path.join(temp_dir, new_filename) file_dicts.append({ 'start': dt_objs[0], 'end': dt_objs[1], 'path': fpath }) with open(fpath, 'wb') as f: f.write(self.camera.download_file(value)) return file_dicts def get_video_stream(self, channel: int = 0, subtype: int = 1) -> str: """ Outputs the video stream url Args: channel: int, which channel to use. default = 0 subtype: int, stream type to use. 0 = main, 1 = extra_1, etc default = 1 Returns: str, the url to the stream """ return f'{self.base_url_with_cred}/mjpg/video.cgi?channel={channel}&subtype={subtype}'
""" Examines scaffold hypothesis on a particular user. Uses data from the MySQL Database. """ import csv import json import numpy as np import matplotlib.pyplot as plt import igraph PATH = "D:\\network_games\\" SAVE_PATH = "D:\\network_games\\scaffold\\" FILENAME = "scaffold_data_mysql.csv" # Specify the name of the user whose data is needed to be processed USER = "darigan17" def parse_data(filename): """ Parses data from a tab delimited CSV file, assembles user graph :param filename: Input file name :return: The user and its edge usage graph """ with open(filename, 'r', encoding='utf-8') as csvfile: csv_reader = csv.reader(csvfile, delimiter='\t') print(f"Parsed file: {FILENAME}") line_count = 0 user_count = 0 user_last_clicks = {} user_graph = igraph.Graph() for row in csv_reader: # Ignoring header row if line_count == 0: print(f'Columns: {', '.join(row)}') line_count += 1 # Ignoring data from other users elif row[2] == USER: line_count += 1 user = row[2] article = row[3] game = row[4] # Add edge to the user graph try: user_graph.vs.find(article) except ValueError: user_graph.add_vertex(name=article) if user_last_clicks.get('game', "") == game: if user_last_clicks['article'] != article: # Either add edge or increase its weight if it already exists try: e = user_graph.es.find(_source=user_last_clicks['article'], _target=article) e['weight'] += 1 except ValueError: user_graph.add_edge(source=user_last_clicks['article'], target=article, weight=1) user_last_clicks = {"article": article, "game": game} else: continue print(f"{user_count} users created") return user_graph, user def analyse_graph(user_graph, user): """ Analyses the scaffold graph of the current user. """ print("Analysing user graph...") # Plotting degree distributions degree_dist = np.bincount(user_graph.degree()) x = range(degree_dist.size) fig = plt.figure() fig.suptitle("Degree distribution") plt.plot(x, degree_dist, c="blue") plt.xlabel("Number of connections") plt.ylabel("Number of nodes") plt.xscale("log") plt.yscale("log") # plt.show() fig.savefig(SAVE_PATH + f"mysql_{user}_dd.png") plt.close(fig) # Creating edge weight distribution edge_weights = user_graph.es['weight'] counts = np.bincount(edge_weights) x = range(counts.size) fig, ax = plt.subplots() ax.plot(x, counts, 'bo') ax.set_xlabel("Weights (Number of uses)") ax.set_ylabel("Occurrences (Number of edges with particular weight)") ax.set_title("Edge weight distribution") plt.yscale("log") plt.xscale("log") plt.grid() fig.savefig(SAVE_PATH + f"mysql_{user}_ew.png") # plt.show() plt.close(fig) # Creating subgraph by betweenness centrality btwn = user_graph.betweenness(directed=True, weights=None) ntile = np.percentile(btwn, 90) sub_vs = user_graph.vs.select([v for v, b in enumerate(btwn) if b >= ntile]) sub_graph = user_graph.subgraph(sub_vs) print(f'Generated subgraph with {sub_graph.vcount()} vertices and {sub_graph.ecount()} edges.') # Plotting subgraph # Coloring edges colors = ["orange", "darkorange", "red", "blue"] for e in sub_graph.es: weight = e['weight'] if weight >= 15: e['color'] = colors[3] elif 8 <= weight < 15: e['color'] = colors[2] elif 3 <= weight < 8: e['color'] = colors[1] else: e['color'] = colors[0] # Clipping edge widths edge_widths = np.clip(a=sub_graph.es['weight'], a_min=4, a_max=15) # Styling graph visual_style = {"bbox": (3000, 3000), "margin": 17, "vertex_color": 'grey', "vertex_size": 15, "vertex_label_size": 4, "edge_curved": False, "edge_width": edge_widths} # Set the layout try: layout = sub_graph.layout("fr") visual_style["layout"] = layout save_name = f'mysql_{user}_reduced.png' igraph.plot(sub_graph, SAVE_PATH + save_name, **visual_style) print(f"Graph from {user} analysed and plotted to {save_name}") except MemoryError: print(f"Memory error. Skipping to plot {user}'s graph.") def load_graph(filename): """Loads graph from file""" return igraph.load(filename) def save_graph(graph): """Saves scaffold graph in GML format""" igraph.save(graph, filename=SAVE_PATH + f'mysql_{USER}.gml') def main(): # Complete analysis of the user user_graph, user = parse_data(PATH + FILENAME) analyse_graph(user_graph, user) save_graph(user_graph) # Load and analyse graph # user_graph = load_graph(SAVE_PATH + f'mysql_{USER}.gml') # analyse_graph(user_graph, USER) if __name__ == '__main__': main()
""" Examines scaffold hypothesis on a particular user. Uses data from the MySQL Database. """ import csv import json import numpy as np import matplotlib.pyplot as plt import igraph PATH = "D:\\network_games\\" SAVE_PATH = "D:\\network_games\\scaffold\\" FILENAME = "scaffold_data_mysql.csv" # Specify the name of the user whose data is needed to be processed USER = "darigan17" def parse_data(filename): """ Parses data from a tab delimited CSV file, assembles user graph :param filename: Input file name :return: The user and its edge usage graph """ with open(filename, 'r', encoding='utf-8') as csvfile: csv_reader = csv.reader(csvfile, delimiter='\t') print(f"Parsed file: {FILENAME}") line_count = 0 user_count = 0 user_last_clicks = {} user_graph = igraph.Graph() for row in csv_reader: # Ignoring header row if line_count == 0: print(f'Columns: {", ".join(row)}') line_count += 1 # Ignoring data from other users elif row[2] == USER: line_count += 1 user = row[2] article = row[3] game = row[4] # Add edge to the user graph try: user_graph.vs.find(article) except ValueError: user_graph.add_vertex(name=article) if user_last_clicks.get('game', "") == game: if user_last_clicks['article'] != article: # Either add edge or increase its weight if it already exists try: e = user_graph.es.find(_source=user_last_clicks['article'], _target=article) e['weight'] += 1 except ValueError: user_graph.add_edge(source=user_last_clicks['article'], target=article, weight=1) user_last_clicks = {"article": article, "game": game} else: continue print(f"{user_count} users created") return user_graph, user def analyse_graph(user_graph, user): """ Analyses the scaffold graph of the current user. """ print("Analysing user graph...") # Plotting degree distributions degree_dist = np.bincount(user_graph.degree()) x = range(degree_dist.size) fig = plt.figure() fig.suptitle("Degree distribution") plt.plot(x, degree_dist, c="blue") plt.xlabel("Number of connections") plt.ylabel("Number of nodes") plt.xscale("log") plt.yscale("log") # plt.show() fig.savefig(SAVE_PATH + f"mysql_{user}_dd.png") plt.close(fig) # Creating edge weight distribution edge_weights = user_graph.es['weight'] counts = np.bincount(edge_weights) x = range(counts.size) fig, ax = plt.subplots() ax.plot(x, counts, 'bo') ax.set_xlabel("Weights (Number of uses)") ax.set_ylabel("Occurrences (Number of edges with particular weight)") ax.set_title("Edge weight distribution") plt.yscale("log") plt.xscale("log") plt.grid() fig.savefig(SAVE_PATH + f"mysql_{user}_ew.png") # plt.show() plt.close(fig) # Creating subgraph by betweenness centrality btwn = user_graph.betweenness(directed=True, weights=None) ntile = np.percentile(btwn, 90) sub_vs = user_graph.vs.select([v for v, b in enumerate(btwn) if b >= ntile]) sub_graph = user_graph.subgraph(sub_vs) print(f'Generated subgraph with {sub_graph.vcount()} vertices and {sub_graph.ecount()} edges.') # Plotting subgraph # Coloring edges colors = ["orange", "darkorange", "red", "blue"] for e in sub_graph.es: weight = e['weight'] if weight >= 15: e['color'] = colors[3] elif 8 <= weight < 15: e['color'] = colors[2] elif 3 <= weight < 8: e['color'] = colors[1] else: e['color'] = colors[0] # Clipping edge widths edge_widths = np.clip(a=sub_graph.es['weight'], a_min=4, a_max=15) # Styling graph visual_style = {"bbox": (3000, 3000), "margin": 17, "vertex_color": 'grey', "vertex_size": 15, "vertex_label_size": 4, "edge_curved": False, "edge_width": edge_widths} # Set the layout try: layout = sub_graph.layout("fr") visual_style["layout"] = layout save_name = f'mysql_{user}_reduced.png' igraph.plot(sub_graph, SAVE_PATH + save_name, **visual_style) print(f"Graph from {user} analysed and plotted to {save_name}") except MemoryError: print(f"Memory error. Skipping to plot {user}'s graph.") def load_graph(filename): """Loads graph from file""" return igraph.load(filename) def save_graph(graph): """Saves scaffold graph in GML format""" igraph.save(graph, filename=SAVE_PATH + f'mysql_{USER}.gml') def main(): # Complete analysis of the user user_graph, user = parse_data(PATH + FILENAME) analyse_graph(user_graph, user) save_graph(user_graph) # Load and analyse graph # user_graph = load_graph(SAVE_PATH + f'mysql_{USER}.gml') # analyse_graph(user_graph, USER) if __name__ == '__main__': main()
"""Config Flow using OAuth2. This module exists of the following parts: - OAuth2 config flow which supports multiple OAuth2 implementations - OAuth2 implementation that works with local provided client ID/secret """ from __future__ import annotations from abc import ABC, ABCMeta, abstractmethod import asyncio import logging import secrets import time from typing import Any, Awaitable, Callable, Dict, cast from aiohttp import client, web import async_timeout import jwt import voluptuous as vol from yarl import URL from homeassistant import config_entries from homeassistant.components import http from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.network import NoURLAvailableError from .aiohttp_client import async_get_clientsession _LOGGER = logging.getLogger(__name__) DATA_JWT_SECRET = "oauth2_jwt_secret" DATA_VIEW_REGISTERED = "oauth2_view_reg" DATA_IMPLEMENTATIONS = "oauth2_impl" DATA_PROVIDERS = "oauth2_providers" AUTH_CALLBACK_PATH = "/auth/external/callback" HEADER_FRONTEND_BASE = "HA-Frontend-Base" CLOCK_OUT_OF_SYNC_MAX_SEC = 20 class AbstractOAuth2Implementation(ABC): """Base class to abstract OAuth2 authentication.""" @property @abstractmethod def name(self) -> str: """Name of the implementation.""" @property @abstractmethod def domain(self) -> str: """Domain that is providing the implementation.""" @abstractmethod async def async_generate_authorize_url(self, flow_id: str) -> str: """Generate a url for the user to authorize. This step is called when a config flow is initialized. It should redirect the user to the vendor website where they can authorize Home Assistant. The implementation is responsible to get notified when the user is authorized and pass this to the specified config flow. Do as little work as possible once notified. You can do the work inside async_resolve_external_data. This will give the best UX. Pass external data in with: await hass.config_entries.flow.async_configure( flow_id=flow_id, user_input={'code': 'abcd', 'state': { … } ) """ @abstractmethod async def async_resolve_external_data(self, external_data: Any) -> dict: """Resolve external data to tokens. Turn the data that the implementation passed to the config flow as external step data into tokens. These tokens will be stored as 'token' in the config entry data. """ async def async_refresh_token(self, token: dict) -> dict: """Refresh a token and update expires info.""" new_token = await self._async_refresh_token(token) # Force int for non-compliant oauth2 providers new_token["expires_in"] = int(new_token["expires_in"]) new_token["expires_at"] = time.time() + new_token["expires_in"] return new_token @abstractmethod async def _async_refresh_token(self, token: dict) -> dict: """Refresh a token.""" class LocalOAuth2Implementation(AbstractOAuth2Implementation): """Local OAuth2 implementation.""" def __init__( self, hass: HomeAssistant, domain: str, client_id: str, client_secret: str, authorize_url: str, token_url: str, ): """Initialize local auth implementation.""" self.hass = hass self._domain = domain self.client_id = client_id self.client_secret = client_secret self.authorize_url = authorize_url self.token_url = token_url @property def name(self) -> str: """Name of the implementation.""" return "Configuration.yaml" @property def domain(self) -> str: """Domain providing the implementation.""" return self._domain @property def redirect_uri(self) -> str: """Return the redirect uri.""" req = http.current_request.get() if req is None: raise RuntimeError("No current request in context") ha_host = req.headers.get(HEADER_FRONTEND_BASE) if ha_host is None: raise RuntimeError("No header in request") return f"{ha_host}{AUTH_CALLBACK_PATH}" @property def extra_authorize_data(self) -> dict: """Extra data that needs to be appended to the authorize url.""" return {} async def async_generate_authorize_url(self, flow_id: str) -> str: """Generate a url for the user to authorize.""" redirect_uri = self.redirect_uri return str( URL(self.authorize_url) .with_query( { "response_type": "code", "client_id": self.client_id, "redirect_uri": redirect_uri, "state": _encode_jwt( self.hass, {"flow_id": flow_id, "redirect_uri": redirect_uri} ), } ) .update_query(self.extra_authorize_data) ) async def async_resolve_external_data(self, external_data: Any) -> dict: """Resolve the authorization code to tokens.""" return await self._token_request( { "grant_type": "authorization_code", "code": external_data["code"], "redirect_uri": external_data["state"]["redirect_uri"], } ) async def _async_refresh_token(self, token: dict) -> dict: """Refresh tokens.""" new_token = await self._token_request( { "grant_type": "refresh_token", "client_id": self.client_id, "refresh_token": token["refresh_token"], } ) return {**token, **new_token} async def _token_request(self, data: dict) -> dict: """Make a token request.""" session = async_get_clientsession(self.hass) data["client_id"] = self.client_id if self.client_secret is not None: data["client_secret"] = self.client_secret resp = await session.post(self.token_url, data=data) if resp.status >= 400 and _LOGGER.isEnabledFor(logging.DEBUG): body = await resp.text() _LOGGER.debug( "Token request failed with status=%s, body=%s", resp.status, body, ) resp.raise_for_status() return cast(dict, await resp.json()) class AbstractOAuth2FlowHandler(config_entries.ConfigFlow, metaclass=ABCMeta): """Handle a config flow.""" DOMAIN = "" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_UNKNOWN def __init__(self) -> None: """Instantiate config flow.""" if self.DOMAIN == "": raise TypeError( f"Can't instantiate class {self.__class__.__name__} without DOMAIN being set" ) self.external_data: Any = None self.flow_impl: AbstractOAuth2Implementation = None # type: ignore @property @abstractmethod def logger(self) -> logging.Logger: """Return logger.""" @property def extra_authorize_data(self) -> dict: """Extra data that needs to be appended to the authorize url.""" return {} async def async_step_pick_implementation( self, user_input: dict | None = None ) -> dict: """Handle a flow start.""" implementations = await async_get_implementations(self.hass, self.DOMAIN) if user_input is not None: self.flow_impl = implementations[user_input["implementation"]] return await self.async_step_auth() if not implementations: return self.async_abort(reason="missing_configuration") req = http.current_request.get() if len(implementations) == 1 and req is not None: # Pick first implementation if we have only one, but only # if this is triggered by a user interaction (request). self.flow_impl = list(implementations.values())[0] return await self.async_step_auth() return self.async_show_form( step_id="pick_implementation", data_schema=vol.Schema( { vol.Required( "implementation", default=list(implementations)[0] ): vol.In({key: impl.name for key, impl in implementations.items()}) } ), ) async def async_step_auth( self, user_input: dict[str, Any] | None = None ) -> dict[str, Any]: """Create an entry for auth.""" # Flow has been triggered by external data if user_input: self.external_data = user_input return self.async_external_step_done(next_step_id="creation") try: with async_timeout.timeout(10): url = await self.flow_impl.async_generate_authorize_url(self.flow_id) except asyncio.TimeoutError: return self.async_abort(reason="authorize_url_timeout") except NoURLAvailableError: return self.async_abort( reason="no_url_available", description_placeholders={ "docs_url": "https://www.home-assistant.io/more-info/no-url-available" }, ) url = str(URL(url).update_query(self.extra_authorize_data)) return self.async_external_step(step_id="auth", url=url) async def async_step_creation( self, user_input: dict[str, Any] | None = None ) -> dict[str, Any]: """Create config entry from external data.""" token = await self.flow_impl.async_resolve_external_data(self.external_data) # Force int for non-compliant oauth2 providers try: token["expires_in"] = int(token["expires_in"]) except ValueError as err: _LOGGER.warning("Error converting expires_in to int: %s", err) return self.async_abort(reason="oauth_error") token["expires_at"] = time.time() + token["expires_in"] self.logger.info("Successfully authenticated") return await self.async_oauth_create_entry( {"auth_implementation": self.flow_impl.domain, "token": token} ) async def async_oauth_create_entry(self, data: dict) -> dict: """Create an entry for the flow. Ok to override if you want to fetch extra info or even add another step. """ return self.async_create_entry(title=self.flow_impl.name, data=data) async_step_user = async_step_pick_implementation @classmethod def async_register_implementation( cls, hass: HomeAssistant, local_impl: LocalOAuth2Implementation ) -> None: """Register a local implementation.""" async_register_implementation(hass, cls.DOMAIN, local_impl) @callback def async_register_implementation( hass: HomeAssistant, domain: str, implementation: AbstractOAuth2Implementation ) -> None: """Register an OAuth2 flow implementation for an integration.""" if isinstance(implementation, LocalOAuth2Implementation) and not hass.data.get( DATA_VIEW_REGISTERED, False ): hass.http.register_view(OAuth2AuthorizeCallbackView()) # type: ignore hass.data[DATA_VIEW_REGISTERED] = True implementations = hass.data.setdefault(DATA_IMPLEMENTATIONS, {}) implementations.setdefault(domain, {})[implementation.domain] = implementation async def async_get_implementations( hass: HomeAssistant, domain: str ) -> dict[str, AbstractOAuth2Implementation]: """Return OAuth2 implementations for specified domain.""" registered = cast( Dict[str, AbstractOAuth2Implementation], hass.data.setdefault(DATA_IMPLEMENTATIONS, {}).get(domain, {}), ) if DATA_PROVIDERS not in hass.data: return registered registered = dict(registered) for provider_domain, get_impl in hass.data[DATA_PROVIDERS].items(): implementation = await get_impl(hass, domain) if implementation is not None: registered[provider_domain] = implementation return registered async def async_get_config_entry_implementation( hass: HomeAssistant, config_entry: config_entries.ConfigEntry ) -> AbstractOAuth2Implementation: """Return the implementation for this config entry.""" implementations = await async_get_implementations(hass, config_entry.domain) implementation = implementations.get(config_entry.data["auth_implementation"]) if implementation is None: raise ValueError("Implementation not available") return implementation @callback def async_add_implementation_provider( hass: HomeAssistant, provider_domain: str, async_provide_implementation: Callable[ [HomeAssistant, str], Awaitable[AbstractOAuth2Implementation | None] ], ) -> None: """Add an implementation provider. If no implementation found, return None. """ hass.data.setdefault(DATA_PROVIDERS, {})[ provider_domain ] = async_provide_implementation class OAuth2AuthorizeCallbackView(http.HomeAssistantView): """OAuth2 Authorization Callback View.""" requires_auth = False url = AUTH_CALLBACK_PATH name = "auth:external:callback" async def get(self, request: web.Request) -> web.Response: """Receive authorization code.""" if "code" not in request.query or "state" not in request.query: return web.Response( text=f"Missing code or state parameter in {request.url}" ) hass = request.app["hass"] state = _decode_jwt(hass, request.query["state"]) if state is None: return web.Response(text="Invalid state") await hass.config_entries.flow.async_configure( flow_id=state["flow_id"], user_input={"state": state, "code": request.query["code"]}, ) return web.Response( headers={"content-type": "text/html"}, text="<script>window.close()</script>", ) class OAuth2Session: """Session to make requests authenticated with OAuth2.""" def __init__( self, hass: HomeAssistant, config_entry: config_entries.ConfigEntry, implementation: AbstractOAuth2Implementation, ): """Initialize an OAuth2 session.""" self.hass = hass self.config_entry = config_entry self.implementation = implementation @property def token(self) -> dict: """Return the token.""" return cast(dict, self.config_entry.data["token"]) @property def valid_token(self) -> bool: """Return if token is still valid.""" return ( cast(float, self.token["expires_at"]) > time.time() + CLOCK_OUT_OF_SYNC_MAX_SEC ) async def async_ensure_token_valid(self) -> None: """Ensure that the current token is valid.""" if self.valid_token: return new_token = await self.implementation.async_refresh_token(self.token) self.hass.config_entries.async_update_entry( self.config_entry, data={**self.config_entry.data, "token": new_token} ) async def async_request( self, method: str, url: str, **kwargs: Any ) -> client.ClientResponse: """Make a request.""" await self.async_ensure_token_valid() return await async_oauth2_request( self.hass, self.config_entry.data["token"], method, url, **kwargs ) async def async_oauth2_request( hass: HomeAssistant, token: dict, method: str, url: str, **kwargs: Any ) -> client.ClientResponse: """Make an OAuth2 authenticated request. This method will not refresh tokens. Use OAuth2 session for that. """ session = async_get_clientsession(hass) return await session.request( method, url, **kwargs, headers={ **(kwargs.get("headers") or {}), "authorization": f"Bearer {token["access_token"]}", }, ) @callback def _encode_jwt(hass: HomeAssistant, data: dict) -> str: """JWT encode data.""" secret = hass.data.get(DATA_JWT_SECRET) if secret is None: secret = hass.data[DATA_JWT_SECRET] = secrets.token_hex() return jwt.encode(data, secret, algorithm="HS256").decode() @callback def _decode_jwt(hass: HomeAssistant, encoded: str) -> dict | None: """JWT encode data.""" secret = cast(str, hass.data.get(DATA_JWT_SECRET)) try: return jwt.decode(encoded, secret, algorithms=["HS256"]) except jwt.InvalidTokenError: return None
"""Config Flow using OAuth2. This module exists of the following parts: - OAuth2 config flow which supports multiple OAuth2 implementations - OAuth2 implementation that works with local provided client ID/secret """ from __future__ import annotations from abc import ABC, ABCMeta, abstractmethod import asyncio import logging import secrets import time from typing import Any, Awaitable, Callable, Dict, cast from aiohttp import client, web import async_timeout import jwt import voluptuous as vol from yarl import URL from homeassistant import config_entries from homeassistant.components import http from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.network import NoURLAvailableError from .aiohttp_client import async_get_clientsession _LOGGER = logging.getLogger(__name__) DATA_JWT_SECRET = "oauth2_jwt_secret" DATA_VIEW_REGISTERED = "oauth2_view_reg" DATA_IMPLEMENTATIONS = "oauth2_impl" DATA_PROVIDERS = "oauth2_providers" AUTH_CALLBACK_PATH = "/auth/external/callback" HEADER_FRONTEND_BASE = "HA-Frontend-Base" CLOCK_OUT_OF_SYNC_MAX_SEC = 20 class AbstractOAuth2Implementation(ABC): """Base class to abstract OAuth2 authentication.""" @property @abstractmethod def name(self) -> str: """Name of the implementation.""" @property @abstractmethod def domain(self) -> str: """Domain that is providing the implementation.""" @abstractmethod async def async_generate_authorize_url(self, flow_id: str) -> str: """Generate a url for the user to authorize. This step is called when a config flow is initialized. It should redirect the user to the vendor website where they can authorize Home Assistant. The implementation is responsible to get notified when the user is authorized and pass this to the specified config flow. Do as little work as possible once notified. You can do the work inside async_resolve_external_data. This will give the best UX. Pass external data in with: await hass.config_entries.flow.async_configure( flow_id=flow_id, user_input={'code': 'abcd', 'state': { … } ) """ @abstractmethod async def async_resolve_external_data(self, external_data: Any) -> dict: """Resolve external data to tokens. Turn the data that the implementation passed to the config flow as external step data into tokens. These tokens will be stored as 'token' in the config entry data. """ async def async_refresh_token(self, token: dict) -> dict: """Refresh a token and update expires info.""" new_token = await self._async_refresh_token(token) # Force int for non-compliant oauth2 providers new_token["expires_in"] = int(new_token["expires_in"]) new_token["expires_at"] = time.time() + new_token["expires_in"] return new_token @abstractmethod async def _async_refresh_token(self, token: dict) -> dict: """Refresh a token.""" class LocalOAuth2Implementation(AbstractOAuth2Implementation): """Local OAuth2 implementation.""" def __init__( self, hass: HomeAssistant, domain: str, client_id: str, client_secret: str, authorize_url: str, token_url: str, ): """Initialize local auth implementation.""" self.hass = hass self._domain = domain self.client_id = client_id self.client_secret = client_secret self.authorize_url = authorize_url self.token_url = token_url @property def name(self) -> str: """Name of the implementation.""" return "Configuration.yaml" @property def domain(self) -> str: """Domain providing the implementation.""" return self._domain @property def redirect_uri(self) -> str: """Return the redirect uri.""" req = http.current_request.get() if req is None: raise RuntimeError("No current request in context") ha_host = req.headers.get(HEADER_FRONTEND_BASE) if ha_host is None: raise RuntimeError("No header in request") return f"{ha_host}{AUTH_CALLBACK_PATH}" @property def extra_authorize_data(self) -> dict: """Extra data that needs to be appended to the authorize url.""" return {} async def async_generate_authorize_url(self, flow_id: str) -> str: """Generate a url for the user to authorize.""" redirect_uri = self.redirect_uri return str( URL(self.authorize_url) .with_query( { "response_type": "code", "client_id": self.client_id, "redirect_uri": redirect_uri, "state": _encode_jwt( self.hass, {"flow_id": flow_id, "redirect_uri": redirect_uri} ), } ) .update_query(self.extra_authorize_data) ) async def async_resolve_external_data(self, external_data: Any) -> dict: """Resolve the authorization code to tokens.""" return await self._token_request( { "grant_type": "authorization_code", "code": external_data["code"], "redirect_uri": external_data["state"]["redirect_uri"], } ) async def _async_refresh_token(self, token: dict) -> dict: """Refresh tokens.""" new_token = await self._token_request( { "grant_type": "refresh_token", "client_id": self.client_id, "refresh_token": token["refresh_token"], } ) return {**token, **new_token} async def _token_request(self, data: dict) -> dict: """Make a token request.""" session = async_get_clientsession(self.hass) data["client_id"] = self.client_id if self.client_secret is not None: data["client_secret"] = self.client_secret resp = await session.post(self.token_url, data=data) if resp.status >= 400 and _LOGGER.isEnabledFor(logging.DEBUG): body = await resp.text() _LOGGER.debug( "Token request failed with status=%s, body=%s", resp.status, body, ) resp.raise_for_status() return cast(dict, await resp.json()) class AbstractOAuth2FlowHandler(config_entries.ConfigFlow, metaclass=ABCMeta): """Handle a config flow.""" DOMAIN = "" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_UNKNOWN def __init__(self) -> None: """Instantiate config flow.""" if self.DOMAIN == "": raise TypeError( f"Can't instantiate class {self.__class__.__name__} without DOMAIN being set" ) self.external_data: Any = None self.flow_impl: AbstractOAuth2Implementation = None # type: ignore @property @abstractmethod def logger(self) -> logging.Logger: """Return logger.""" @property def extra_authorize_data(self) -> dict: """Extra data that needs to be appended to the authorize url.""" return {} async def async_step_pick_implementation( self, user_input: dict | None = None ) -> dict: """Handle a flow start.""" implementations = await async_get_implementations(self.hass, self.DOMAIN) if user_input is not None: self.flow_impl = implementations[user_input["implementation"]] return await self.async_step_auth() if not implementations: return self.async_abort(reason="missing_configuration") req = http.current_request.get() if len(implementations) == 1 and req is not None: # Pick first implementation if we have only one, but only # if this is triggered by a user interaction (request). self.flow_impl = list(implementations.values())[0] return await self.async_step_auth() return self.async_show_form( step_id="pick_implementation", data_schema=vol.Schema( { vol.Required( "implementation", default=list(implementations)[0] ): vol.In({key: impl.name for key, impl in implementations.items()}) } ), ) async def async_step_auth( self, user_input: dict[str, Any] | None = None ) -> dict[str, Any]: """Create an entry for auth.""" # Flow has been triggered by external data if user_input: self.external_data = user_input return self.async_external_step_done(next_step_id="creation") try: with async_timeout.timeout(10): url = await self.flow_impl.async_generate_authorize_url(self.flow_id) except asyncio.TimeoutError: return self.async_abort(reason="authorize_url_timeout") except NoURLAvailableError: return self.async_abort( reason="no_url_available", description_placeholders={ "docs_url": "https://www.home-assistant.io/more-info/no-url-available" }, ) url = str(URL(url).update_query(self.extra_authorize_data)) return self.async_external_step(step_id="auth", url=url) async def async_step_creation( self, user_input: dict[str, Any] | None = None ) -> dict[str, Any]: """Create config entry from external data.""" token = await self.flow_impl.async_resolve_external_data(self.external_data) # Force int for non-compliant oauth2 providers try: token["expires_in"] = int(token["expires_in"]) except ValueError as err: _LOGGER.warning("Error converting expires_in to int: %s", err) return self.async_abort(reason="oauth_error") token["expires_at"] = time.time() + token["expires_in"] self.logger.info("Successfully authenticated") return await self.async_oauth_create_entry( {"auth_implementation": self.flow_impl.domain, "token": token} ) async def async_oauth_create_entry(self, data: dict) -> dict: """Create an entry for the flow. Ok to override if you want to fetch extra info or even add another step. """ return self.async_create_entry(title=self.flow_impl.name, data=data) async_step_user = async_step_pick_implementation @classmethod def async_register_implementation( cls, hass: HomeAssistant, local_impl: LocalOAuth2Implementation ) -> None: """Register a local implementation.""" async_register_implementation(hass, cls.DOMAIN, local_impl) @callback def async_register_implementation( hass: HomeAssistant, domain: str, implementation: AbstractOAuth2Implementation ) -> None: """Register an OAuth2 flow implementation for an integration.""" if isinstance(implementation, LocalOAuth2Implementation) and not hass.data.get( DATA_VIEW_REGISTERED, False ): hass.http.register_view(OAuth2AuthorizeCallbackView()) # type: ignore hass.data[DATA_VIEW_REGISTERED] = True implementations = hass.data.setdefault(DATA_IMPLEMENTATIONS, {}) implementations.setdefault(domain, {})[implementation.domain] = implementation async def async_get_implementations( hass: HomeAssistant, domain: str ) -> dict[str, AbstractOAuth2Implementation]: """Return OAuth2 implementations for specified domain.""" registered = cast( Dict[str, AbstractOAuth2Implementation], hass.data.setdefault(DATA_IMPLEMENTATIONS, {}).get(domain, {}), ) if DATA_PROVIDERS not in hass.data: return registered registered = dict(registered) for provider_domain, get_impl in hass.data[DATA_PROVIDERS].items(): implementation = await get_impl(hass, domain) if implementation is not None: registered[provider_domain] = implementation return registered async def async_get_config_entry_implementation( hass: HomeAssistant, config_entry: config_entries.ConfigEntry ) -> AbstractOAuth2Implementation: """Return the implementation for this config entry.""" implementations = await async_get_implementations(hass, config_entry.domain) implementation = implementations.get(config_entry.data["auth_implementation"]) if implementation is None: raise ValueError("Implementation not available") return implementation @callback def async_add_implementation_provider( hass: HomeAssistant, provider_domain: str, async_provide_implementation: Callable[ [HomeAssistant, str], Awaitable[AbstractOAuth2Implementation | None] ], ) -> None: """Add an implementation provider. If no implementation found, return None. """ hass.data.setdefault(DATA_PROVIDERS, {})[ provider_domain ] = async_provide_implementation class OAuth2AuthorizeCallbackView(http.HomeAssistantView): """OAuth2 Authorization Callback View.""" requires_auth = False url = AUTH_CALLBACK_PATH name = "auth:external:callback" async def get(self, request: web.Request) -> web.Response: """Receive authorization code.""" if "code" not in request.query or "state" not in request.query: return web.Response( text=f"Missing code or state parameter in {request.url}" ) hass = request.app["hass"] state = _decode_jwt(hass, request.query["state"]) if state is None: return web.Response(text="Invalid state") await hass.config_entries.flow.async_configure( flow_id=state["flow_id"], user_input={"state": state, "code": request.query["code"]}, ) return web.Response( headers={"content-type": "text/html"}, text="<script>window.close()</script>", ) class OAuth2Session: """Session to make requests authenticated with OAuth2.""" def __init__( self, hass: HomeAssistant, config_entry: config_entries.ConfigEntry, implementation: AbstractOAuth2Implementation, ): """Initialize an OAuth2 session.""" self.hass = hass self.config_entry = config_entry self.implementation = implementation @property def token(self) -> dict: """Return the token.""" return cast(dict, self.config_entry.data["token"]) @property def valid_token(self) -> bool: """Return if token is still valid.""" return ( cast(float, self.token["expires_at"]) > time.time() + CLOCK_OUT_OF_SYNC_MAX_SEC ) async def async_ensure_token_valid(self) -> None: """Ensure that the current token is valid.""" if self.valid_token: return new_token = await self.implementation.async_refresh_token(self.token) self.hass.config_entries.async_update_entry( self.config_entry, data={**self.config_entry.data, "token": new_token} ) async def async_request( self, method: str, url: str, **kwargs: Any ) -> client.ClientResponse: """Make a request.""" await self.async_ensure_token_valid() return await async_oauth2_request( self.hass, self.config_entry.data["token"], method, url, **kwargs ) async def async_oauth2_request( hass: HomeAssistant, token: dict, method: str, url: str, **kwargs: Any ) -> client.ClientResponse: """Make an OAuth2 authenticated request. This method will not refresh tokens. Use OAuth2 session for that. """ session = async_get_clientsession(hass) return await session.request( method, url, **kwargs, headers={ **(kwargs.get("headers") or {}), "authorization": f"Bearer {token['access_token']}", }, ) @callback def _encode_jwt(hass: HomeAssistant, data: dict) -> str: """JWT encode data.""" secret = hass.data.get(DATA_JWT_SECRET) if secret is None: secret = hass.data[DATA_JWT_SECRET] = secrets.token_hex() return jwt.encode(data, secret, algorithm="HS256").decode() @callback def _decode_jwt(hass: HomeAssistant, encoded: str) -> dict | None: """JWT encode data.""" secret = cast(str, hass.data.get(DATA_JWT_SECRET)) try: return jwt.decode(encoded, secret, algorithms=["HS256"]) except jwt.InvalidTokenError: return None
import builtins import threading import time import traceback from typing import TypeVar, List, Optional, Match from Chainmail import Wrapper from Chainmail.Events import CommandSentEvent, PlayerConnectedEvent, Events from Chainmail.MessageBuilder import MessageBuilder, Colours from Chainmail.Player import Player from Chainmail.Plugin import ChainmailPlugin from plugins.ChainmailRCON import ChainmailRCON, RCONClientHandler t = TypeVar("t") class PendingTPA(object): def __init__(self, creator: Player, recipient: Player): self.created_at = time.time() self.creator = creator # type: Player self.recipient = recipient # type: Player self.responded = False self.notify_creation() def notify_creation(self): message = MessageBuilder() message.add_field("You have been sent a teleport request by ", Colours.gold) message.add_field(f"{self.creator.username}.\n", Colours.blue) message.add_field("Use ", Colours.gold) message.add_field("!tpaccept ", Colours.blue) message.add_field("to accept the request, or ", Colours.gold) message.add_field("!tpdeny ", Colours.blue) message.add_field("to decline it.", Colours.gold) self.recipient.send_message(message) message = MessageBuilder() message.add_field("Your request to ", Colours.gold) message.add_field(f"{self.recipient.username} ", Colours.blue) message.add_field("has been sent.", Colours.gold) self.creator.send_message(message) def do_teleport(self): message = MessageBuilder() message.add_field("Teleporting you to ", Colours.gold) message.add_field(f"{self.recipient.username}.", Colours.blue) self.creator.send_message(message) message = MessageBuilder() message.add_field("You are being teleported to by ", Colours.gold) message.add_field(f"{self.creator.username}.", Colours.blue) self.recipient.send_message(message) self.creator.teleport_to(self.recipient) def notify_expired(self): if not self.responded: message = MessageBuilder() message.add_field("Your TPA to ", Colours.gold) message.add_field(f"{self.recipient.username} ", Colours.blue) message.add_field("has expired.", Colours.gold) self.creator.send_message(message) message = MessageBuilder() message.add_field("Your TPA from ", Colours.gold) message.add_field(f"{self.creator.username} ", Colours.blue) message.add_field("has expired.", Colours.gold) self.recipient.send_message(message) def notify_denied(self): message = MessageBuilder() message.add_field(f"{self.recipient.username} ", Colours.blue) message.add_field("has declined your teleport request.", Colours.gold) self.creator.send_message(message) message = MessageBuilder() message.add_field("Request denied.", Colours.red) self.recipient.send_message(message) @property def expired(self) -> bool: return (time.time() - self.created_at) >= 60 or self.responded class ChainmailEssentials(ChainmailPlugin): def __init__(self, manifest: dict, wrapper: "Wrapper.Wrapper") -> None: super().__init__(manifest, wrapper) self.rcon = getattr(builtins, "RCON") # type: ChainmailRCON self.needs_update = self.new_version_available self.pending_tpas = [] # type: List[PendingTPA] self.eval_usage_message = MessageBuilder() self.eval_usage_message.add_field("Usage: ", colour=Colours.red, bold=True) self.eval_usage_message.add_field("!exec <code>", colour=Colours.gold) self.update_message = MessageBuilder() self.update_message.add_field("A new version of ", Colours.gold) self.update_message.add_field("Chainmail Essentials ", Colours.blue) self.update_message.add_field("is available.", Colours.gold) self.eval = self.wrapper.CommandRegistry.register_command("!eval", "^!eval (.+)$", "Evaluates Python expressions.", self.command_eval, True) self.eval_usage = self.wrapper.CommandRegistry.register_command("!eval", "^!eval$", "Displays the usage message.", self.command_eval_usage, True) self.commands = self.wrapper.CommandRegistry.register_command("!commands", "^!commands$", "Lists commands accessible to a user.", self.command_commands) self.plugins = self.wrapper.CommandRegistry.register_command("!plugins", "^!plugins$", "Lists all loaded plugins.", self.command_plugins) self.reload = self.wrapper.CommandRegistry.register_command("!reload", "^!reload$", "Reloads all plugins.", self.command_reload, True) self.tpa = self.wrapper.CommandRegistry.register_command("!tpa", "^!tpa ([\\w\\d_]+)$", "Requests to teleport to another user.", self.command_tpa) self.tpaccept = self.wrapper.CommandRegistry.register_command("!tpaccept", "^!tpaccept$", "Accepts a teleport request.", self.command_tpaccept) self.tpdeny = self.wrapper.CommandRegistry.register_command("!tpdeny", "^!tpdeny$", "Denies a teleport request.", self.command_tpdeny) self.info = self.wrapper.CommandRegistry.register_command("!info", "^!info$", "Gets various info about the server.", self.command_info, True) self.rcon.register_command("/commands", "^/commands$", "Lists the commands you have access to.", self.rconcommand_commands) self.wrapper.EventManager.register_handler(Events.PLAYER_CONNECTED, self.handle_connection) def remove_expired_tpas_thread(self): while self.wrapper.wrapper_running and self.enabled: for tpa in self.pending_tpas: if tpa.expired: tpa.notify_expired() self.pending_tpas.remove(tpa) time.sleep(5) def get_tpa(self, creator: Player=None, recipient: Player=None) -> Optional[PendingTPA]: """ Gets a pending tpa for a specified creator or recipient :param creator: The creator of the tpa :param recipient: The recipient of the tpa :return: The tpa """ if creator is not None: for tpa in self.pending_tpas: if tpa.creator == creator: return tpa if recipient is not None: for tpa in self.pending_tpas: if tpa.recipient == recipient: return tpa return None # noinspection PyMethodMayBeStatic def command_eval(self, event: CommandSentEvent): code = event.args[0] # noinspection PyBroadException try: result = str(eval(code)) error = False except: result = traceback.format_exc(1) error = True builder = MessageBuilder() colour = Colours.green if not error else Colours.red builder.add_field("Result: ", colour=Colours.gold) builder.add_field(result, colour=colour) event.player.send_message(builder) def command_eval_usage(self, event: CommandSentEvent): event.player.send_message(self.eval_usage_message) def command_commands(self, event: CommandSentEvent): commands = self.wrapper.CommandRegistry.get_accessible_commands(event.player) builder = MessageBuilder() seen_commands = [] for command in commands: if command.name not in seen_commands: seen_commands.append(command.name) builder.add_field(f"{command.name}: ", Colours.red) suffix = "\n" if command != commands[-1] and command.name != commands[-1].name else "" builder.add_field(f"{command.description}{suffix}", Colours.gold) event.player.send_message(builder) def rconcommand_commands(self, matches: List[Match[str]], client: RCONClientHandler): components = [] seen = [] for command in self.rcon.commands: if command["name"] not in seen and (client.authed or not command["requires_auth"]): seen.append(command["name"]) components.append(f"{command["name"]}: {command["description"]}") client.writeline("\n".join(components)) def command_plugins(self, event: CommandSentEvent): plugins = self.wrapper.PluginManager.get_all_plugins() builder = MessageBuilder() for plugin in plugins: if self.wrapper.PluginManager.get_plugin_loaded(plugin["manifest"]["name"]): builder.add_field(f"{plugin["manifest"]["name"]}\n", Colours.blue) builder.add_field(" Developer: ", Colours.red) builder.add_field(f"{plugin["manifest"]["developer"]}\n", Colours.blue) suffix = "\n" if plugin != plugins[-1] else "" builder.add_field(" Version: ", Colours.red) builder.add_field(f"{plugin["manifest"]["version"]}{suffix}", Colours.blue) event.player.send_message(builder) def command_reload(self, event: CommandSentEvent): builder = MessageBuilder() builder.add_field("Reloading all plugins...", Colours.blue) event.player.send_message(builder) self.wrapper.reload() builder = MessageBuilder() builder.add_field("Plugins reloaded.", Colours.green) event.player.send_message(builder) def command_tpa(self, event: CommandSentEvent): recipient = self.wrapper.PlayerManager.get_player(event.args[0]) if recipient is None: builder = MessageBuilder() builder.add_field("A player with that username was not found.", Colours.red) event.player.send_message(builder) return if self.get_tpa(creator=event.player) is not None: builder = MessageBuilder() builder.add_field("You already have an active outgoing TPA request.", Colours.red) event.player.send_message(builder) return if self.get_tpa(recipient=recipient) is not None: builder = MessageBuilder() builder.add_field("The other player already has a pending TPA request.", Colours.red) event.player.send_message(builder) return self.pending_tpas.append(PendingTPA(event.player, recipient)) def command_tpaccept(self, event: CommandSentEvent): tpa = self.get_tpa(recipient=event.player) if tpa is None: builder = MessageBuilder() builder.add_field("You do not have a pending TPA.", Colours.red) event.player.send_message(builder) return tpa.responded = True tpa.do_teleport() def command_tpdeny(self, event: CommandSentEvent): tpa = self.get_tpa(recipient=event.player) if tpa is None: builder = MessageBuilder() builder.add_field("You do not have a pending TPA.", Colours.red) event.player.send_message(builder) return tpa.responded = True tpa.notify_denied() def command_info(self, event: CommandSentEvent): builder = MessageBuilder() builder.add_field("Server version: ", Colours.gold) builder.add_field(f"{self.wrapper.version}\n", Colours.blue) builder.add_field("OPs: ", Colours.gold) builder.add_field(f"{len(self.wrapper.ops)}", Colours.blue) event.player.send_message(builder) def handle_connection(self, event: PlayerConnectedEvent): if event.player.is_op and self.needs_update: event.player.send_message(self.update_message) def enable(self) -> None: super().enable() threading.Thread(target=self.remove_expired_tpas_thread).start()
import builtins import threading import time import traceback from typing import TypeVar, List, Optional, Match from Chainmail import Wrapper from Chainmail.Events import CommandSentEvent, PlayerConnectedEvent, Events from Chainmail.MessageBuilder import MessageBuilder, Colours from Chainmail.Player import Player from Chainmail.Plugin import ChainmailPlugin from plugins.ChainmailRCON import ChainmailRCON, RCONClientHandler t = TypeVar("t") class PendingTPA(object): def __init__(self, creator: Player, recipient: Player): self.created_at = time.time() self.creator = creator # type: Player self.recipient = recipient # type: Player self.responded = False self.notify_creation() def notify_creation(self): message = MessageBuilder() message.add_field("You have been sent a teleport request by ", Colours.gold) message.add_field(f"{self.creator.username}.\n", Colours.blue) message.add_field("Use ", Colours.gold) message.add_field("!tpaccept ", Colours.blue) message.add_field("to accept the request, or ", Colours.gold) message.add_field("!tpdeny ", Colours.blue) message.add_field("to decline it.", Colours.gold) self.recipient.send_message(message) message = MessageBuilder() message.add_field("Your request to ", Colours.gold) message.add_field(f"{self.recipient.username} ", Colours.blue) message.add_field("has been sent.", Colours.gold) self.creator.send_message(message) def do_teleport(self): message = MessageBuilder() message.add_field("Teleporting you to ", Colours.gold) message.add_field(f"{self.recipient.username}.", Colours.blue) self.creator.send_message(message) message = MessageBuilder() message.add_field("You are being teleported to by ", Colours.gold) message.add_field(f"{self.creator.username}.", Colours.blue) self.recipient.send_message(message) self.creator.teleport_to(self.recipient) def notify_expired(self): if not self.responded: message = MessageBuilder() message.add_field("Your TPA to ", Colours.gold) message.add_field(f"{self.recipient.username} ", Colours.blue) message.add_field("has expired.", Colours.gold) self.creator.send_message(message) message = MessageBuilder() message.add_field("Your TPA from ", Colours.gold) message.add_field(f"{self.creator.username} ", Colours.blue) message.add_field("has expired.", Colours.gold) self.recipient.send_message(message) def notify_denied(self): message = MessageBuilder() message.add_field(f"{self.recipient.username} ", Colours.blue) message.add_field("has declined your teleport request.", Colours.gold) self.creator.send_message(message) message = MessageBuilder() message.add_field("Request denied.", Colours.red) self.recipient.send_message(message) @property def expired(self) -> bool: return (time.time() - self.created_at) >= 60 or self.responded class ChainmailEssentials(ChainmailPlugin): def __init__(self, manifest: dict, wrapper: "Wrapper.Wrapper") -> None: super().__init__(manifest, wrapper) self.rcon = getattr(builtins, "RCON") # type: ChainmailRCON self.needs_update = self.new_version_available self.pending_tpas = [] # type: List[PendingTPA] self.eval_usage_message = MessageBuilder() self.eval_usage_message.add_field("Usage: ", colour=Colours.red, bold=True) self.eval_usage_message.add_field("!exec <code>", colour=Colours.gold) self.update_message = MessageBuilder() self.update_message.add_field("A new version of ", Colours.gold) self.update_message.add_field("Chainmail Essentials ", Colours.blue) self.update_message.add_field("is available.", Colours.gold) self.eval = self.wrapper.CommandRegistry.register_command("!eval", "^!eval (.+)$", "Evaluates Python expressions.", self.command_eval, True) self.eval_usage = self.wrapper.CommandRegistry.register_command("!eval", "^!eval$", "Displays the usage message.", self.command_eval_usage, True) self.commands = self.wrapper.CommandRegistry.register_command("!commands", "^!commands$", "Lists commands accessible to a user.", self.command_commands) self.plugins = self.wrapper.CommandRegistry.register_command("!plugins", "^!plugins$", "Lists all loaded plugins.", self.command_plugins) self.reload = self.wrapper.CommandRegistry.register_command("!reload", "^!reload$", "Reloads all plugins.", self.command_reload, True) self.tpa = self.wrapper.CommandRegistry.register_command("!tpa", "^!tpa ([\\w\\d_]+)$", "Requests to teleport to another user.", self.command_tpa) self.tpaccept = self.wrapper.CommandRegistry.register_command("!tpaccept", "^!tpaccept$", "Accepts a teleport request.", self.command_tpaccept) self.tpdeny = self.wrapper.CommandRegistry.register_command("!tpdeny", "^!tpdeny$", "Denies a teleport request.", self.command_tpdeny) self.info = self.wrapper.CommandRegistry.register_command("!info", "^!info$", "Gets various info about the server.", self.command_info, True) self.rcon.register_command("/commands", "^/commands$", "Lists the commands you have access to.", self.rconcommand_commands) self.wrapper.EventManager.register_handler(Events.PLAYER_CONNECTED, self.handle_connection) def remove_expired_tpas_thread(self): while self.wrapper.wrapper_running and self.enabled: for tpa in self.pending_tpas: if tpa.expired: tpa.notify_expired() self.pending_tpas.remove(tpa) time.sleep(5) def get_tpa(self, creator: Player=None, recipient: Player=None) -> Optional[PendingTPA]: """ Gets a pending tpa for a specified creator or recipient :param creator: The creator of the tpa :param recipient: The recipient of the tpa :return: The tpa """ if creator is not None: for tpa in self.pending_tpas: if tpa.creator == creator: return tpa if recipient is not None: for tpa in self.pending_tpas: if tpa.recipient == recipient: return tpa return None # noinspection PyMethodMayBeStatic def command_eval(self, event: CommandSentEvent): code = event.args[0] # noinspection PyBroadException try: result = str(eval(code)) error = False except: result = traceback.format_exc(1) error = True builder = MessageBuilder() colour = Colours.green if not error else Colours.red builder.add_field("Result: ", colour=Colours.gold) builder.add_field(result, colour=colour) event.player.send_message(builder) def command_eval_usage(self, event: CommandSentEvent): event.player.send_message(self.eval_usage_message) def command_commands(self, event: CommandSentEvent): commands = self.wrapper.CommandRegistry.get_accessible_commands(event.player) builder = MessageBuilder() seen_commands = [] for command in commands: if command.name not in seen_commands: seen_commands.append(command.name) builder.add_field(f"{command.name}: ", Colours.red) suffix = "\n" if command != commands[-1] and command.name != commands[-1].name else "" builder.add_field(f"{command.description}{suffix}", Colours.gold) event.player.send_message(builder) def rconcommand_commands(self, matches: List[Match[str]], client: RCONClientHandler): components = [] seen = [] for command in self.rcon.commands: if command["name"] not in seen and (client.authed or not command["requires_auth"]): seen.append(command["name"]) components.append(f"{command['name']}: {command['description']}") client.writeline("\n".join(components)) def command_plugins(self, event: CommandSentEvent): plugins = self.wrapper.PluginManager.get_all_plugins() builder = MessageBuilder() for plugin in plugins: if self.wrapper.PluginManager.get_plugin_loaded(plugin["manifest"]["name"]): builder.add_field(f"{plugin['manifest']['name']}\n", Colours.blue) builder.add_field(" Developer: ", Colours.red) builder.add_field(f"{plugin['manifest']['developer']}\n", Colours.blue) suffix = "\n" if plugin != plugins[-1] else "" builder.add_field(" Version: ", Colours.red) builder.add_field(f"{plugin['manifest']['version']}{suffix}", Colours.blue) event.player.send_message(builder) def command_reload(self, event: CommandSentEvent): builder = MessageBuilder() builder.add_field("Reloading all plugins...", Colours.blue) event.player.send_message(builder) self.wrapper.reload() builder = MessageBuilder() builder.add_field("Plugins reloaded.", Colours.green) event.player.send_message(builder) def command_tpa(self, event: CommandSentEvent): recipient = self.wrapper.PlayerManager.get_player(event.args[0]) if recipient is None: builder = MessageBuilder() builder.add_field("A player with that username was not found.", Colours.red) event.player.send_message(builder) return if self.get_tpa(creator=event.player) is not None: builder = MessageBuilder() builder.add_field("You already have an active outgoing TPA request.", Colours.red) event.player.send_message(builder) return if self.get_tpa(recipient=recipient) is not None: builder = MessageBuilder() builder.add_field("The other player already has a pending TPA request.", Colours.red) event.player.send_message(builder) return self.pending_tpas.append(PendingTPA(event.player, recipient)) def command_tpaccept(self, event: CommandSentEvent): tpa = self.get_tpa(recipient=event.player) if tpa is None: builder = MessageBuilder() builder.add_field("You do not have a pending TPA.", Colours.red) event.player.send_message(builder) return tpa.responded = True tpa.do_teleport() def command_tpdeny(self, event: CommandSentEvent): tpa = self.get_tpa(recipient=event.player) if tpa is None: builder = MessageBuilder() builder.add_field("You do not have a pending TPA.", Colours.red) event.player.send_message(builder) return tpa.responded = True tpa.notify_denied() def command_info(self, event: CommandSentEvent): builder = MessageBuilder() builder.add_field("Server version: ", Colours.gold) builder.add_field(f"{self.wrapper.version}\n", Colours.blue) builder.add_field("OPs: ", Colours.gold) builder.add_field(f"{len(self.wrapper.ops)}", Colours.blue) event.player.send_message(builder) def handle_connection(self, event: PlayerConnectedEvent): if event.player.is_op and self.needs_update: event.player.send_message(self.update_message) def enable(self) -> None: super().enable() threading.Thread(target=self.remove_expired_tpas_thread).start()
import argparse import itertools import json import os import re from collections import Counter import pandas as pd from spacy.tokens import Doc import spacy from tqdm import tqdm from pig.data import SPLIT_SPEC DATA_DIR = "data/out/180x100/" REALIGNED_DATA_DIR = "data/out/realign/" DATA_EVAL_DIR = "data/eval/" FRAGMENTS = ["narration"] POS_TAGS = ["ADJ", "VERB", "NOUN"] WORDS_NAMES = [ "chloe", "danny", "george", "pedro", "peppa", "rebecca", "richard", "susie", "suzy", ] SYNONYMS_REPLACE = {"granddad": "grandpa", "mommy": "mummy", "grandma": "granny"} # Ignore some words that have been mistagged by the POS-tagger (partly because of poor pre-tokenization): WORDS_IGNORE = { "VERB": ["they're", "we're", "what's", "can't"], "NOUN": ["peppa's", "george's", "let's", "pig's", "i'll", "rabbit's", "daddy's", "chloe's", "can't", "doesn't", "suzy's", "zebra's", "zoe's", "it's", "dog's", "dinosaur's", "they're", "grandpa's", "rebecca's", "we've", "there's", "you'll", "i'm", "we'll", "i've", "what's", "i'll", "that's", "you're", "we'd", "we're", "bit", "lot", "be", "dear", "love"], # ("love" and "dear" are not used as nouns in the dataset) "ADJ": ["it's", "that's"], } TOKEN_MASK = "<MASK>" def clean_lemma(lemma): lemma = lemma.lower() # Remove punctuation if lemma[-1] in [".", ",", "'", "?", "!"]: lemma = lemma[:-1] if lemma in SYNONYMS_REPLACE: lemma = SYNONYMS_REPLACE[lemma] return lemma def load_realigned_data(): nlp = spacy.load("en_core_web_sm") # Use lookup-based lemmatizer nlp.remove_pipe("lemmatizer") nlp.add_pipe("lemmatizer", config={"mode": "lookup"}).initialize() data_sentences = [] data_tokens = [] for root, dirs, files in os.walk(REALIGNED_DATA_DIR): for file in files: if file.endswith(".json"): path = os.path.join(root, file) item = json.load(open(path, "r")) fragment = "narration" if "narration" in root else "dialog" episode = int(path.split("/")[-3].split("_")[1]) # Remove punctuation item["transcript"] = re.sub(r"\s*[\.!]+\s*$", "", item["transcript"]) item["transcript"] = re.sub(r"\s*[-:\.♪]+\s*", " ", item["transcript"]) # Remove whitespace item["transcript"] = re.sub(r"\s+$", "", item["transcript"]) item["transcript"] = re.sub(r"^\s+", "", item["transcript"]) item["transcript"] = re.sub(r"\s\s", " ", item["transcript"]) tokenized = re.split(" ", item["transcript"]) if len(tokenized) != len(item["words"]): raise RuntimeError( f"Not aligned: {tokenized} and {[w["word"] for w in item["words"]]}" ) item["tokenized"] = [w.lower() for w in tokenized] doc = Doc(nlp.vocab, words=tokenized) for name, proc in nlp.pipeline: doc = proc(doc) # Treat proper nouns the same way as nouns item["pos"] = [t.pos_ if t.pos_ != "PROPN" else "NOUN" for t in doc] item["lemmatized"] = [clean_lemma(t.lemma_) for t in doc] for i in range(len(item["words"])): item["words"][i]["fragment"] = fragment item["words"][i]["path"] = path item["words"][i]["episode"] = episode item["words"][i]["pos"] = item["pos"][i] item["words"][i]["lemma"] = item["lemmatized"][i] data_tokens.extend(item["words"]) item_sentence = item.copy() keep_keys = ["case", "start", "end", "word"] item_sentence["words"] = [{k: w[k] for k in w.keys() if k in keep_keys} for w in item_sentence["words"]] item_sentence["fragment"] = fragment item_sentence["episode"] = episode data_sentences.append(item_sentence) data_tokens = pd.DataFrame(data_tokens) data_sentences = pd.DataFrame(data_sentences) return data_sentences, data_tokens def load_data(): nlp = spacy.load("en_core_web_sm") nlp.remove_pipe("lemmatizer") nlp.add_pipe("lemmatizer", config={"mode": "lookup"}).initialize() data_sentences = [] data_tokens = [] for root, dirs, files in os.walk(DATA_DIR): for file in files: if file.endswith(".json"): path = os.path.join(root, file) data_file = json.load(open(path, "r")) fragment = "narration" if "narration" in root else "dialog" episode = int(path.split("/")[-2]) for subtitle in data_file["subtitles"]: item = {"transcript": subtitle["text"]} # Remove punctuation item["transcript"] = re.sub( r"\s*[\.!]+\s*$", "", item["transcript"] ) item["transcript"] = re.sub( r"\s*[-:\.♪]+\s*", " ", item["transcript"] ) # Remove whitespace item["transcript"] = re.sub(r"\s+$", "", item["transcript"]) item["transcript"] = re.sub(r"^\s+", "", item["transcript"]) item["transcript"] = re.sub(r"\s\s", " ", item["transcript"]) tokenized = re.split(" ", item["transcript"]) item["tokenized"] = [w.lower() for w in tokenized] doc = Doc(nlp.vocab, words=tokenized) for name, proc in nlp.pipeline: doc = proc(doc) # Treat proper nouns the same way as nouns item["pos"] = [t.pos_ if t.pos_ != "PROPN" else "NOUN" for t in doc] item["lemmatized"] = [clean_lemma(t.lemma_) for t in doc] item["words"] = [{"word": w} for w in item["tokenized"]] for i in range(len(item["words"])): item["words"][i]["fragment"] = fragment item["words"][i]["path"] = path item["words"][i]["episode"] = episode item["words"][i]["pos"] = item["pos"][i] item["words"][i]["lemma"] = item["lemmatized"][i] data_tokens.extend(item["words"]) item_sentence = item.copy() keep_keys = ["case", "start", "end", "word"] item_sentence["words"] = [{k: w[k] for k in w.keys() if k in keep_keys} for w in item_sentence["words"]] item_sentence["fragment"] = fragment item_sentence["episode"] = episode data_sentences.append(item_sentence) data_tokens = pd.DataFrame(data_tokens) data_sentences = pd.DataFrame(data_sentences) return data_sentences, data_tokens def is_sublist(list_1, list_2): def get_all_in(one, another): for element in one: if element in another: yield element for x1, x2 in zip(get_all_in(list_1, list_2), get_all_in(list_2, list_1)): if x1 != x2: return False return True def longest_intersection(tokens_1, tokens_2): longest_sublist = [] mask_index = tokens_1.index(TOKEN_MASK) for i in range(len(tokens_1)): for j in range(i, len(tokens_1)): if i - 1 < mask_index < j + 1: sublist = tokens_1[i : j + 1] for k in range(len(tokens_2)): for l in range(k, len(tokens_2)): sublist_2 = tokens_2[k : l + 1] if sublist == sublist_2: if len(sublist) > len(longest_sublist): longest_sublist = sublist return longest_sublist def get_start_and_end_of_sublist(sentence, sublist): for i in range(len(sentence)): if sentence[i] == sublist[0]: start = i for j in range(len(sublist)): if sentence[i + j] != sublist[j]: break if j == len(sublist) - 1: end = i + j return start, end raise RuntimeError(f"Could not find {sublist} in {sentence}") def crop_and_create_example(example, start, end, target_word, distractor_word): example["tokenized"] = example["tokenized"][start : end + 1] example["words"] = example["words"][start : end + 1] example["start_token_idx"] = start example["end_token_idx"] = end # Update clip start and end time example["clipOffset"] = example["clipStart"] example["clipStart"] += example["words"][0]["start"] example["clipEnd"] = example["clipOffset"] + example["words"][-1]["end"] assert example["clipStart"] < example["clipEnd"] example["target_word"] = target_word example["distractor_word"] = distractor_word return example def find_minimal_pairs_for_tuple(tuple, data, args): results = [] lemma_1, lemma_2 = tuple used_counterexamples = [] print(f"\nLooking for: {(lemma_1, lemma_2)}") for _, s1 in tqdm(data.iterrows(), total=len(data)): best_example, best_counterexample, best_counterex_row = None, None, None len_longest_intersection = 0 # Only continue if the target lemma (lemma_1) is in the sentence, and the distractor is not there. if lemma_1 not in s1["lemmatized"] or lemma_2 in s1["lemmatized"]: continue example_candidate = s1.copy() s1_masked = [ w if lemma != lemma_1 else TOKEN_MASK for w, lemma in zip( example_candidate["tokenized"], example_candidate["lemmatized"] ) ] for row_counterexample, s2 in data.iterrows(): if row_counterexample in used_counterexamples: continue # Only continue if the target lemma (lemma_2) is in the sentence, and the distractor is not there. if lemma_2 not in s2["lemmatized"] or lemma_1 in s2["lemmatized"]: continue counterexample_candidate = s2.copy() s2_masked = [ w if lemma != lemma_2 else TOKEN_MASK for w, lemma in zip( counterexample_candidate["tokenized"], counterexample_candidate["lemmatized"], ) ] intersection = longest_intersection(s1_masked, s2_masked) if not intersection: continue start, end = get_start_and_end_of_sublist(s1_masked, intersection) first_word = example_candidate["words"][start] last_word = example_candidate["words"][end] if ( first_word["case"] != "success" or last_word["case"] != "success" or "end" not in last_word or "start" not in first_word or last_word["end"] - first_word["start"] < args.min_phrase_duration ): continue (counterex_start, counterex_end,) = get_start_and_end_of_sublist( s2_masked, intersection ) first_word = counterexample_candidate["words"][counterex_start] last_word = counterexample_candidate["words"][counterex_end] if ( first_word["case"] != "success" or last_word["case"] != "success" or "end" not in last_word or "start" not in first_word or last_word["end"] - first_word["start"] < args.min_phrase_duration ): continue if len(intersection) > len_longest_intersection: example = crop_and_create_example( example_candidate.copy(), start, end, lemma_1, lemma_2, ) counterexample = crop_and_create_example( counterexample_candidate.copy(), counterex_start, counterex_end, lemma_2, lemma_1, ) len_longest_intersection = len(intersection) best_example = example best_counterexample = counterexample best_counterex_row = row_counterexample if best_example is not None: results.append(best_example) results.append(best_counterexample) # print(best_example["tokenized"]) # print(best_counterexample["tokenized"], end="\n\n") used_counterexamples.append(best_counterex_row) return results def find_minimal_pairs(tuples, data, args): process_args = [ (tuple, data, args) for tuple in tuples ] results = [find_minimal_pairs_for_tuple(*args) for args in process_args] eval_set = pd.DataFrame(list(itertools.chain(*results))) if len(eval_set) > 0: eval_set.reset_index(drop=True, inplace=True) eval_set["id"] = eval_set.index eval_set["id_counterexample"] = eval_set.id.apply(lambda x: x + 1 if x % 2 == 0 else x - 1) eval_set.set_index("id", inplace=True) return eval_set def get_lemmatized_words(data_tokens, data_split, fragments=FRAGMENTS, pos=None): all_words = [] for fragment in fragments: words = data_tokens[ (data_tokens.fragment == fragment) & data_tokens.episode.isin(SPLIT_SPEC[fragment][data_split]) ] if pos: words = words[words.pos == pos] lemmas = [w.lemma for _, w in words.iterrows()] all_words.extend(lemmas) return all_words def get_args(): parser = argparse.ArgumentParser() parser.add_argument( "--min-occurrences", type=int, default=10, help="Minimum number of occurrences in val data of a word to be included", ) parser.add_argument( "--min-phrase-duration", type=float, default=0.3, help="Minimum duration of a phrase (in seconds)", ) return parser.parse_args() if __name__ == "__main__": args = get_args() os.makedirs(DATA_EVAL_DIR, exist_ok=True) data_sentences, data_tokens = load_realigned_data() for pos_name in POS_TAGS: print(f"Looking for {pos_name}s:") # Find most common words words = get_lemmatized_words(data_tokens, "val", fragments=FRAGMENTS, pos=pos_name) counter = Counter(words) words = [ w for w, occ in counter.items() if occ > args.min_occurrences and w not in WORDS_IGNORE[pos_name] ] print("Considered words: ", words) tuples = list(itertools.combinations(words, 2)) for fragment in FRAGMENTS: data_fragment = data_sentences[data_sentences.fragment == fragment] data_fragment_val = data_fragment[ data_fragment.episode.isin(SPLIT_SPEC[fragment]["val"]) ] eval_set = find_minimal_pairs(tuples, data_fragment_val, args) eval_set["fragment"] = fragment # Sort by duration eval_set["clipDuration"] = eval_set["clipEnd"] - eval_set["clipStart"] eval_set = eval_set.sort_values(by=['clipDuration']) file_name = f"eval_set_{fragment}_{pos_name}.csv" os.makedirs(DATA_EVAL_DIR, exist_ok=True) eval_set.to_csv(os.path.join(DATA_EVAL_DIR, file_name))
import argparse import itertools import json import os import re from collections import Counter import pandas as pd from spacy.tokens import Doc import spacy from tqdm import tqdm from pig.data import SPLIT_SPEC DATA_DIR = "data/out/180x100/" REALIGNED_DATA_DIR = "data/out/realign/" DATA_EVAL_DIR = "data/eval/" FRAGMENTS = ["narration"] POS_TAGS = ["ADJ", "VERB", "NOUN"] WORDS_NAMES = [ "chloe", "danny", "george", "pedro", "peppa", "rebecca", "richard", "susie", "suzy", ] SYNONYMS_REPLACE = {"granddad": "grandpa", "mommy": "mummy", "grandma": "granny"} # Ignore some words that have been mistagged by the POS-tagger (partly because of poor pre-tokenization): WORDS_IGNORE = { "VERB": ["they're", "we're", "what's", "can't"], "NOUN": ["peppa's", "george's", "let's", "pig's", "i'll", "rabbit's", "daddy's", "chloe's", "can't", "doesn't", "suzy's", "zebra's", "zoe's", "it's", "dog's", "dinosaur's", "they're", "grandpa's", "rebecca's", "we've", "there's", "you'll", "i'm", "we'll", "i've", "what's", "i'll", "that's", "you're", "we'd", "we're", "bit", "lot", "be", "dear", "love"], # ("love" and "dear" are not used as nouns in the dataset) "ADJ": ["it's", "that's"], } TOKEN_MASK = "<MASK>" def clean_lemma(lemma): lemma = lemma.lower() # Remove punctuation if lemma[-1] in [".", ",", "'", "?", "!"]: lemma = lemma[:-1] if lemma in SYNONYMS_REPLACE: lemma = SYNONYMS_REPLACE[lemma] return lemma def load_realigned_data(): nlp = spacy.load("en_core_web_sm") # Use lookup-based lemmatizer nlp.remove_pipe("lemmatizer") nlp.add_pipe("lemmatizer", config={"mode": "lookup"}).initialize() data_sentences = [] data_tokens = [] for root, dirs, files in os.walk(REALIGNED_DATA_DIR): for file in files: if file.endswith(".json"): path = os.path.join(root, file) item = json.load(open(path, "r")) fragment = "narration" if "narration" in root else "dialog" episode = int(path.split("/")[-3].split("_")[1]) # Remove punctuation item["transcript"] = re.sub(r"\s*[\.!]+\s*$", "", item["transcript"]) item["transcript"] = re.sub(r"\s*[-:\.♪]+\s*", " ", item["transcript"]) # Remove whitespace item["transcript"] = re.sub(r"\s+$", "", item["transcript"]) item["transcript"] = re.sub(r"^\s+", "", item["transcript"]) item["transcript"] = re.sub(r"\s\s", " ", item["transcript"]) tokenized = re.split(" ", item["transcript"]) if len(tokenized) != len(item["words"]): raise RuntimeError( f"Not aligned: {tokenized} and {[w['word'] for w in item['words']]}" ) item["tokenized"] = [w.lower() for w in tokenized] doc = Doc(nlp.vocab, words=tokenized) for name, proc in nlp.pipeline: doc = proc(doc) # Treat proper nouns the same way as nouns item["pos"] = [t.pos_ if t.pos_ != "PROPN" else "NOUN" for t in doc] item["lemmatized"] = [clean_lemma(t.lemma_) for t in doc] for i in range(len(item["words"])): item["words"][i]["fragment"] = fragment item["words"][i]["path"] = path item["words"][i]["episode"] = episode item["words"][i]["pos"] = item["pos"][i] item["words"][i]["lemma"] = item["lemmatized"][i] data_tokens.extend(item["words"]) item_sentence = item.copy() keep_keys = ["case", "start", "end", "word"] item_sentence["words"] = [{k: w[k] for k in w.keys() if k in keep_keys} for w in item_sentence["words"]] item_sentence["fragment"] = fragment item_sentence["episode"] = episode data_sentences.append(item_sentence) data_tokens = pd.DataFrame(data_tokens) data_sentences = pd.DataFrame(data_sentences) return data_sentences, data_tokens def load_data(): nlp = spacy.load("en_core_web_sm") nlp.remove_pipe("lemmatizer") nlp.add_pipe("lemmatizer", config={"mode": "lookup"}).initialize() data_sentences = [] data_tokens = [] for root, dirs, files in os.walk(DATA_DIR): for file in files: if file.endswith(".json"): path = os.path.join(root, file) data_file = json.load(open(path, "r")) fragment = "narration" if "narration" in root else "dialog" episode = int(path.split("/")[-2]) for subtitle in data_file["subtitles"]: item = {"transcript": subtitle["text"]} # Remove punctuation item["transcript"] = re.sub( r"\s*[\.!]+\s*$", "", item["transcript"] ) item["transcript"] = re.sub( r"\s*[-:\.♪]+\s*", " ", item["transcript"] ) # Remove whitespace item["transcript"] = re.sub(r"\s+$", "", item["transcript"]) item["transcript"] = re.sub(r"^\s+", "", item["transcript"]) item["transcript"] = re.sub(r"\s\s", " ", item["transcript"]) tokenized = re.split(" ", item["transcript"]) item["tokenized"] = [w.lower() for w in tokenized] doc = Doc(nlp.vocab, words=tokenized) for name, proc in nlp.pipeline: doc = proc(doc) # Treat proper nouns the same way as nouns item["pos"] = [t.pos_ if t.pos_ != "PROPN" else "NOUN" for t in doc] item["lemmatized"] = [clean_lemma(t.lemma_) for t in doc] item["words"] = [{"word": w} for w in item["tokenized"]] for i in range(len(item["words"])): item["words"][i]["fragment"] = fragment item["words"][i]["path"] = path item["words"][i]["episode"] = episode item["words"][i]["pos"] = item["pos"][i] item["words"][i]["lemma"] = item["lemmatized"][i] data_tokens.extend(item["words"]) item_sentence = item.copy() keep_keys = ["case", "start", "end", "word"] item_sentence["words"] = [{k: w[k] for k in w.keys() if k in keep_keys} for w in item_sentence["words"]] item_sentence["fragment"] = fragment item_sentence["episode"] = episode data_sentences.append(item_sentence) data_tokens = pd.DataFrame(data_tokens) data_sentences = pd.DataFrame(data_sentences) return data_sentences, data_tokens def is_sublist(list_1, list_2): def get_all_in(one, another): for element in one: if element in another: yield element for x1, x2 in zip(get_all_in(list_1, list_2), get_all_in(list_2, list_1)): if x1 != x2: return False return True def longest_intersection(tokens_1, tokens_2): longest_sublist = [] mask_index = tokens_1.index(TOKEN_MASK) for i in range(len(tokens_1)): for j in range(i, len(tokens_1)): if i - 1 < mask_index < j + 1: sublist = tokens_1[i : j + 1] for k in range(len(tokens_2)): for l in range(k, len(tokens_2)): sublist_2 = tokens_2[k : l + 1] if sublist == sublist_2: if len(sublist) > len(longest_sublist): longest_sublist = sublist return longest_sublist def get_start_and_end_of_sublist(sentence, sublist): for i in range(len(sentence)): if sentence[i] == sublist[0]: start = i for j in range(len(sublist)): if sentence[i + j] != sublist[j]: break if j == len(sublist) - 1: end = i + j return start, end raise RuntimeError(f"Could not find {sublist} in {sentence}") def crop_and_create_example(example, start, end, target_word, distractor_word): example["tokenized"] = example["tokenized"][start : end + 1] example["words"] = example["words"][start : end + 1] example["start_token_idx"] = start example["end_token_idx"] = end # Update clip start and end time example["clipOffset"] = example["clipStart"] example["clipStart"] += example["words"][0]["start"] example["clipEnd"] = example["clipOffset"] + example["words"][-1]["end"] assert example["clipStart"] < example["clipEnd"] example["target_word"] = target_word example["distractor_word"] = distractor_word return example def find_minimal_pairs_for_tuple(tuple, data, args): results = [] lemma_1, lemma_2 = tuple used_counterexamples = [] print(f"\nLooking for: {(lemma_1, lemma_2)}") for _, s1 in tqdm(data.iterrows(), total=len(data)): best_example, best_counterexample, best_counterex_row = None, None, None len_longest_intersection = 0 # Only continue if the target lemma (lemma_1) is in the sentence, and the distractor is not there. if lemma_1 not in s1["lemmatized"] or lemma_2 in s1["lemmatized"]: continue example_candidate = s1.copy() s1_masked = [ w if lemma != lemma_1 else TOKEN_MASK for w, lemma in zip( example_candidate["tokenized"], example_candidate["lemmatized"] ) ] for row_counterexample, s2 in data.iterrows(): if row_counterexample in used_counterexamples: continue # Only continue if the target lemma (lemma_2) is in the sentence, and the distractor is not there. if lemma_2 not in s2["lemmatized"] or lemma_1 in s2["lemmatized"]: continue counterexample_candidate = s2.copy() s2_masked = [ w if lemma != lemma_2 else TOKEN_MASK for w, lemma in zip( counterexample_candidate["tokenized"], counterexample_candidate["lemmatized"], ) ] intersection = longest_intersection(s1_masked, s2_masked) if not intersection: continue start, end = get_start_and_end_of_sublist(s1_masked, intersection) first_word = example_candidate["words"][start] last_word = example_candidate["words"][end] if ( first_word["case"] != "success" or last_word["case"] != "success" or "end" not in last_word or "start" not in first_word or last_word["end"] - first_word["start"] < args.min_phrase_duration ): continue (counterex_start, counterex_end,) = get_start_and_end_of_sublist( s2_masked, intersection ) first_word = counterexample_candidate["words"][counterex_start] last_word = counterexample_candidate["words"][counterex_end] if ( first_word["case"] != "success" or last_word["case"] != "success" or "end" not in last_word or "start" not in first_word or last_word["end"] - first_word["start"] < args.min_phrase_duration ): continue if len(intersection) > len_longest_intersection: example = crop_and_create_example( example_candidate.copy(), start, end, lemma_1, lemma_2, ) counterexample = crop_and_create_example( counterexample_candidate.copy(), counterex_start, counterex_end, lemma_2, lemma_1, ) len_longest_intersection = len(intersection) best_example = example best_counterexample = counterexample best_counterex_row = row_counterexample if best_example is not None: results.append(best_example) results.append(best_counterexample) # print(best_example["tokenized"]) # print(best_counterexample["tokenized"], end="\n\n") used_counterexamples.append(best_counterex_row) return results def find_minimal_pairs(tuples, data, args): process_args = [ (tuple, data, args) for tuple in tuples ] results = [find_minimal_pairs_for_tuple(*args) for args in process_args] eval_set = pd.DataFrame(list(itertools.chain(*results))) if len(eval_set) > 0: eval_set.reset_index(drop=True, inplace=True) eval_set["id"] = eval_set.index eval_set["id_counterexample"] = eval_set.id.apply(lambda x: x + 1 if x % 2 == 0 else x - 1) eval_set.set_index("id", inplace=True) return eval_set def get_lemmatized_words(data_tokens, data_split, fragments=FRAGMENTS, pos=None): all_words = [] for fragment in fragments: words = data_tokens[ (data_tokens.fragment == fragment) & data_tokens.episode.isin(SPLIT_SPEC[fragment][data_split]) ] if pos: words = words[words.pos == pos] lemmas = [w.lemma for _, w in words.iterrows()] all_words.extend(lemmas) return all_words def get_args(): parser = argparse.ArgumentParser() parser.add_argument( "--min-occurrences", type=int, default=10, help="Minimum number of occurrences in val data of a word to be included", ) parser.add_argument( "--min-phrase-duration", type=float, default=0.3, help="Minimum duration of a phrase (in seconds)", ) return parser.parse_args() if __name__ == "__main__": args = get_args() os.makedirs(DATA_EVAL_DIR, exist_ok=True) data_sentences, data_tokens = load_realigned_data() for pos_name in POS_TAGS: print(f"Looking for {pos_name}s:") # Find most common words words = get_lemmatized_words(data_tokens, "val", fragments=FRAGMENTS, pos=pos_name) counter = Counter(words) words = [ w for w, occ in counter.items() if occ > args.min_occurrences and w not in WORDS_IGNORE[pos_name] ] print("Considered words: ", words) tuples = list(itertools.combinations(words, 2)) for fragment in FRAGMENTS: data_fragment = data_sentences[data_sentences.fragment == fragment] data_fragment_val = data_fragment[ data_fragment.episode.isin(SPLIT_SPEC[fragment]["val"]) ] eval_set = find_minimal_pairs(tuples, data_fragment_val, args) eval_set["fragment"] = fragment # Sort by duration eval_set["clipDuration"] = eval_set["clipEnd"] - eval_set["clipStart"] eval_set = eval_set.sort_values(by=['clipDuration']) file_name = f"eval_set_{fragment}_{pos_name}.csv" os.makedirs(DATA_EVAL_DIR, exist_ok=True) eval_set.to_csv(os.path.join(DATA_EVAL_DIR, file_name))
#!/usr/bin/env python3 ''' # # Duplicator function - receives events from the Ingest function (via SQS) and copies objects into the Cheyenne Vault. # # Project Cheyenne # # @author Damian Bushong <dbushong@uncomn.com> # @copyright (c) 2021 UNCOMN LLC. # @license MIT License # ''' from datetime import datetime, timezone import json import logging from os import environ import boto3 from pythonjsonlogger import jsonlogger logger = logging.getLogger() logger.setLevel(logging.DEBUG if environ.get('DEBUG_MODE', 'false').lower() == 'true' else logging.INFO) # disable verbose logging for botocore, urllib3 to abate debug spam when # we're more focused on debug output from this Lambda function itself. if environ.get('SUPER_DEBUG_MODE', 'false').lower() != 'true': logging.getLogger('botocore').setLevel(logging.WARNING) logging.getLogger('urllib3').setLevel(logging.WARNING) class CustomJsonFormatter(jsonlogger.JsonFormatter): ''' Customizations for JSON formatting. ''' def add_fields(self, log_record, record, message_dict): ''' Add some additional fields for our use. ''' super().add_fields(log_record, record, message_dict) if log_record.get('level'): log_record['level'] = log_record['level'].upper() else: log_record['level'] = record.levelname if log_record.get('exc_info'): log_record['exc_info'] = log_record['exc_info'].split('\n') # forcing the json formatter into logger to override the stock formatter Lambda configured by default for handler in logger.handlers: handler.setFormatter(CustomJsonFormatter(timestamp=True)) sqs = boto3.client('sqs') s3 = boto3.client('s3') # pylint: disable=invalid-name AWS_REGION = environ.get('AWS_REGION') VAULT_BUCKET = environ.get('VAULT_BUCKET') def build_queue_url_from_arn(queue_arn): ''' Build an AWS SQS Queue URL from the AWS SQS Queue's ARN. ''' split_arn = queue_arn.split(':') queue_region = split_arn[3] queue_account_id = split_arn[4] queue_name = split_arn[5] return f'https://sqs.{queue_region}.amazonaws.com/{queue_account_id}/{queue_name}' def tag_set_to_dict(tags): ''' Reshapes returned AWS tag structures into a much easier to use Python dict. ''' return { t['Key']:t['Value'] for t in tags } def dict_to_tag_set(tags): ''' Used to convert a python dictionary into the usual AWS TagSet format. ''' return [{ 'Key': k, 'Value': v } for k,v in tags.items()] def lambda_handler(event, _context): # pylint: disable=too-many-locals ''' Lambda handler. ''' accepted_records = [] failed_records = [] for record in event['Records']: try: logger.debug('raw record', extra={ 'record': record }) s3_event = json.loads(record['body']) queue_name = record['eventSourceARN'].split(':')[5] vault_event_uuid = s3_event['vault_event_uuid'] record['vault_event_uuid'] = vault_event_uuid origin_object = { 'Bucket': s3_event['s3']['bucket']['name'], 'Key': s3_event['s3']['object']['key'] } if 'versionId' in s3_event['s3']['object']: origin_object['VersionId'] = s3_event['s3']['object']['versionId'] logger.debug('event received', extra={ 'vault_event_uuid': vault_event_uuid, 'queue': queue_name, 'event': s3_event }) object_tag_response = s3.get_object_tagging(**origin_object) origin_tags = tag_set_to_dict(object_tag_response['TagSet']) logger.debug('fetched object tags', extra={ 'vault_event_uuid': vault_event_uuid, 'object': origin_object, 'tags': origin_tags }) storage_class = 'GLACIER' if origin_tags.get('uncomn:cheyenne:VaultStorage', '').lower() == 'glacier' else 'STANDARD_IA' record_processed_time = datetime.utcnow().replace(tzinfo=timezone.utc).isoformat(timespec='milliseconds') dest_key = f'{origin_object['Bucket']}/{origin_object['Key']}' vault_tags = { 'uncomn:cheyenne:VaultEventUUID': vault_event_uuid, 'uncomn:cheyenne:VaultEventProcessedTime': record_processed_time, 'uncomn:cheyenne:VaultProcessing': 'COMPLETED' } logger.debug('about to copy object', extra={ 'vault_event_uuid': vault_event_uuid, 'from': origin_object, 'to': { 'Bucket': VAULT_BUCKET, 'Key': dest_key, 'Tags': vault_tags }, 'storage_class': storage_class }) copy_response = s3.copy_object( Bucket=VAULT_BUCKET, Key=dest_key, CopySource=origin_object, StorageClass=storage_class, TaggingDirective='REPLACE', Tagging='&'.join([f'{k}={v}' for k,v in vault_tags.items()]) ) logger.info('successfully copied object', extra={ 'vault_event_uuid': vault_event_uuid, 'from': origin_object, 'to': { 'Bucket': VAULT_BUCKET, 'Key': dest_key, 'VersionId': copy_response['VersionId'], 'KMSKeyId': copy_response['SSEKMSKeyId'] }, 'storage_class': storage_class }) # tagging the original file for traceability and completion feedback target_tag_set = { **origin_object, 'Tagging': { 'TagSet': dict_to_tag_set({ **origin_tags, **vault_tags }) } } s3.put_object_tagging(**target_tag_set) logger.debug('tagged source object', extra={ 'vault_event_uuid': vault_event_uuid, 'processed_time': record_processed_time, 'object': origin_object }) accepted_records.append(record) except Exception: # pylint: disable=broad-except logger.exception('Failed to process record', extra={ 'message_id': record['messageId'] if 'messageId' in record else 'UNKNOWN', 'vault_event_uuid': vault_event_uuid }) failed_records.append(record) if len(failed_records) > 0: # # SQS + Lambda is...weird. # In the event of a partial failure, you need to delete the messages successfully # processed yourself, and then throw within the lambda to indicate that the messages # remaining that were to be processed need to be tossed back into the queue and retried. # logger.info(f'Directly deleting {len(accepted_records)} messages from upstream queue', extra={ 'vault_event_uuids': [record['vault_event_uuid'] for record in accepted_records] }) delete_message_entries = {} for record in accepted_records: queue_arn = record['eventSourceARN'] if queue_arn not in delete_message_entries: delete_message_entries[queue_arn] = [] delete_message_entries[queue_arn].append({ 'Id': record['messageId'], 'ReceiptHandle': record['receiptHandle'] }) for queue_arn, entries in delete_message_entries.items(): logger.info('Accepted one or more records', extra={ 'queue_arn': queue_arn, 'message_ids': [entry['messageId'] for entry in entries] }) sqs.delete_message_batch( QueueURL=build_queue_url_from_arn(queue_arn), Entries=entries ) logger.debug('failed records', extra={ 'records': failed_records }) logger.error('Failed to process one or more records', extra={ 'message_ids': [record['messageId'] for record in failed_records] }) raise Exception('Failed to process one or more records')
#!/usr/bin/env python3 ''' # # Duplicator function - receives events from the Ingest function (via SQS) and copies objects into the Cheyenne Vault. # # Project Cheyenne # # @author Damian Bushong <dbushong@uncomn.com> # @copyright (c) 2021 UNCOMN LLC. # @license MIT License # ''' from datetime import datetime, timezone import json import logging from os import environ import boto3 from pythonjsonlogger import jsonlogger logger = logging.getLogger() logger.setLevel(logging.DEBUG if environ.get('DEBUG_MODE', 'false').lower() == 'true' else logging.INFO) # disable verbose logging for botocore, urllib3 to abate debug spam when # we're more focused on debug output from this Lambda function itself. if environ.get('SUPER_DEBUG_MODE', 'false').lower() != 'true': logging.getLogger('botocore').setLevel(logging.WARNING) logging.getLogger('urllib3').setLevel(logging.WARNING) class CustomJsonFormatter(jsonlogger.JsonFormatter): ''' Customizations for JSON formatting. ''' def add_fields(self, log_record, record, message_dict): ''' Add some additional fields for our use. ''' super().add_fields(log_record, record, message_dict) if log_record.get('level'): log_record['level'] = log_record['level'].upper() else: log_record['level'] = record.levelname if log_record.get('exc_info'): log_record['exc_info'] = log_record['exc_info'].split('\n') # forcing the json formatter into logger to override the stock formatter Lambda configured by default for handler in logger.handlers: handler.setFormatter(CustomJsonFormatter(timestamp=True)) sqs = boto3.client('sqs') s3 = boto3.client('s3') # pylint: disable=invalid-name AWS_REGION = environ.get('AWS_REGION') VAULT_BUCKET = environ.get('VAULT_BUCKET') def build_queue_url_from_arn(queue_arn): ''' Build an AWS SQS Queue URL from the AWS SQS Queue's ARN. ''' split_arn = queue_arn.split(':') queue_region = split_arn[3] queue_account_id = split_arn[4] queue_name = split_arn[5] return f'https://sqs.{queue_region}.amazonaws.com/{queue_account_id}/{queue_name}' def tag_set_to_dict(tags): ''' Reshapes returned AWS tag structures into a much easier to use Python dict. ''' return { t['Key']:t['Value'] for t in tags } def dict_to_tag_set(tags): ''' Used to convert a python dictionary into the usual AWS TagSet format. ''' return [{ 'Key': k, 'Value': v } for k,v in tags.items()] def lambda_handler(event, _context): # pylint: disable=too-many-locals ''' Lambda handler. ''' accepted_records = [] failed_records = [] for record in event['Records']: try: logger.debug('raw record', extra={ 'record': record }) s3_event = json.loads(record['body']) queue_name = record['eventSourceARN'].split(':')[5] vault_event_uuid = s3_event['vault_event_uuid'] record['vault_event_uuid'] = vault_event_uuid origin_object = { 'Bucket': s3_event['s3']['bucket']['name'], 'Key': s3_event['s3']['object']['key'] } if 'versionId' in s3_event['s3']['object']: origin_object['VersionId'] = s3_event['s3']['object']['versionId'] logger.debug('event received', extra={ 'vault_event_uuid': vault_event_uuid, 'queue': queue_name, 'event': s3_event }) object_tag_response = s3.get_object_tagging(**origin_object) origin_tags = tag_set_to_dict(object_tag_response['TagSet']) logger.debug('fetched object tags', extra={ 'vault_event_uuid': vault_event_uuid, 'object': origin_object, 'tags': origin_tags }) storage_class = 'GLACIER' if origin_tags.get('uncomn:cheyenne:VaultStorage', '').lower() == 'glacier' else 'STANDARD_IA' record_processed_time = datetime.utcnow().replace(tzinfo=timezone.utc).isoformat(timespec='milliseconds') dest_key = f'{origin_object["Bucket"]}/{origin_object["Key"]}' vault_tags = { 'uncomn:cheyenne:VaultEventUUID': vault_event_uuid, 'uncomn:cheyenne:VaultEventProcessedTime': record_processed_time, 'uncomn:cheyenne:VaultProcessing': 'COMPLETED' } logger.debug('about to copy object', extra={ 'vault_event_uuid': vault_event_uuid, 'from': origin_object, 'to': { 'Bucket': VAULT_BUCKET, 'Key': dest_key, 'Tags': vault_tags }, 'storage_class': storage_class }) copy_response = s3.copy_object( Bucket=VAULT_BUCKET, Key=dest_key, CopySource=origin_object, StorageClass=storage_class, TaggingDirective='REPLACE', Tagging='&'.join([f'{k}={v}' for k,v in vault_tags.items()]) ) logger.info('successfully copied object', extra={ 'vault_event_uuid': vault_event_uuid, 'from': origin_object, 'to': { 'Bucket': VAULT_BUCKET, 'Key': dest_key, 'VersionId': copy_response['VersionId'], 'KMSKeyId': copy_response['SSEKMSKeyId'] }, 'storage_class': storage_class }) # tagging the original file for traceability and completion feedback target_tag_set = { **origin_object, 'Tagging': { 'TagSet': dict_to_tag_set({ **origin_tags, **vault_tags }) } } s3.put_object_tagging(**target_tag_set) logger.debug('tagged source object', extra={ 'vault_event_uuid': vault_event_uuid, 'processed_time': record_processed_time, 'object': origin_object }) accepted_records.append(record) except Exception: # pylint: disable=broad-except logger.exception('Failed to process record', extra={ 'message_id': record['messageId'] if 'messageId' in record else 'UNKNOWN', 'vault_event_uuid': vault_event_uuid }) failed_records.append(record) if len(failed_records) > 0: # # SQS + Lambda is...weird. # In the event of a partial failure, you need to delete the messages successfully # processed yourself, and then throw within the lambda to indicate that the messages # remaining that were to be processed need to be tossed back into the queue and retried. # logger.info(f'Directly deleting {len(accepted_records)} messages from upstream queue', extra={ 'vault_event_uuids': [record['vault_event_uuid'] for record in accepted_records] }) delete_message_entries = {} for record in accepted_records: queue_arn = record['eventSourceARN'] if queue_arn not in delete_message_entries: delete_message_entries[queue_arn] = [] delete_message_entries[queue_arn].append({ 'Id': record['messageId'], 'ReceiptHandle': record['receiptHandle'] }) for queue_arn, entries in delete_message_entries.items(): logger.info('Accepted one or more records', extra={ 'queue_arn': queue_arn, 'message_ids': [entry['messageId'] for entry in entries] }) sqs.delete_message_batch( QueueURL=build_queue_url_from_arn(queue_arn), Entries=entries ) logger.debug('failed records', extra={ 'records': failed_records }) logger.error('Failed to process one or more records', extra={ 'message_ids': [record['messageId'] for record in failed_records] }) raise Exception('Failed to process one or more records')
# Copyright 2016-2022 Swiss National Supercomputing Centre (CSCS/ETH Zurich) # ReFrame Project Developers. See the top-level LICENSE file for details. # # SPDX-License-Identifier: BSD-3-Clause import abc import copy import os import signal import sys import time import weakref import reframe.core.logging as logging import reframe.core.runtime as runtime import reframe.frontend.dependencies as dependencies import reframe.utility.jsonext as jsonext from reframe.core.exceptions import (AbortTaskError, JobNotStartedError, FailureLimitError, ForceExitError, SkipTestError, TaskExit) from reframe.core.schedulers.local import LocalJobScheduler from reframe.frontend.printer import PrettyPrinter from reframe.frontend.statistics import TestStats ABORT_REASONS = (AssertionError, FailureLimitError, KeyboardInterrupt, ForceExitError) class TestCase: '''A combination of a regression check, a system partition and a programming environment. ''' def __init__(self, check, partition, environ): self._check_orig = check self._check = copy.deepcopy(check) self._partition = copy.deepcopy(partition) self._environ = copy.deepcopy(environ) self._check._case = weakref.ref(self) self._deps = [] # Incoming dependencies self.in_degree = 0 # Level in the dependency chain self.level = 0 def __iter__(self): # Allow unpacking a test case with a single liner: # c, p, e = case return iter([self._check, self._partition, self._environ]) def __hash__(self): return (hash(self.check.unique_name) ^ hash(self.partition.fullname) ^ hash(self.environ.name)) def __eq__(self, other): if not isinstance(other, type(self)): return NotImplemented return (self.check.unique_name == other.check.unique_name and self.environ.name == other.environ.name and self.partition.fullname == other.partition.fullname) def __repr__(self): c = self.check.unique_name if self.check else None p = self.partition.fullname if self.partition else None e = self.environ.name if self.environ else None return f'({c!r}, {p!r}, {e!r})' @property def check(self): return self._check @property def partition(self): return self._partition @property def environ(self): return self._environ @property def deps(self): return self._deps @property def num_dependents(self): return self.in_degree def clone(self): # Return a fresh clone, i.e., one based on the original check return TestCase(self._check_orig, self._partition, self._environ) def generate_testcases(checks): '''Generate concrete test cases from checks.''' rt = runtime.runtime() cases = [] for c in checks: valid_comb = runtime.valid_sysenv_comb(c.valid_systems, c.valid_prog_environs) for part, environs in valid_comb.items(): for env in environs: cases.append(TestCase(c, part, env)) return cases class RegressionTask: '''A class representing a :class:`RegressionTest` through the regression pipeline.''' def __init__(self, case, listeners=[]): self._case = case self._failed_stage = None self._current_stage = 'startup' self._exc_info = (None, None, None) self._listeners = list(listeners) self._skipped = False # Reference count for dependent tests; safe to cleanup the test only # if it is zero self.ref_count = case.num_dependents # Test case has finished, but has not been waited for yet self.zombie = False # Timestamps for the start and finish phases of the pipeline self._timestamps = {} self._aborted = False def duration(self, phase): # Treat pseudo-phases first if phase == 'compile_complete': t_start = 'compile_start' t_finish = 'compile_wait_finish' elif phase == 'run_complete': t_start = 'run_start' t_finish = 'wait_finish' elif phase == 'total': t_start = 'setup_start' t_finish = 'pipeline_end' else: t_start = f'{phase}_start' t_finish = f'{phase}_finish' start = self._timestamps.get(t_start) if not start: return None finish = self._timestamps.get(t_finish) if not finish: finish = self._timestamps.get('pipeline_end') return finish - start def pipeline_timings(self, phases): def _tf(t): return f'{t:.3f}s' if t else 'n/a' msg = '' for phase in phases: if phase == 'compile_complete': msg += f"compile: {_tf(self.duration("compile_complete"))} " elif phase == 'run_complete': msg += f"run: {_tf(self.duration("run_complete"))} " else: msg += f"{phase}: {_tf(self.duration(phase))} " if msg: msg = msg[:-1] return msg def pipeline_timings_all(self): return self.pipeline_timings([ 'setup', 'compile_complete', 'run_complete', 'sanity', 'performance', 'total' ]) def pipeline_timings_basic(self): return self.pipeline_timings([ 'compile_complete', 'run_complete', 'total' ]) @property def testcase(self): return self._case @property def check(self): return self._case.check @property def exc_info(self): return self._exc_info @property def failed(self): return (self._failed_stage is not None and not self._aborted and not self._skipped) @property def state(self): if self.failed: return 'fail' if self.skipped: return 'skip' states = { 'startup': 'startup', 'setup': 'ready_compile', 'compile': 'compiling', 'compile_wait': 'ready_run', 'run': 'running', 'run_wait': 'completing', 'finalize': 'retired', 'cleanup': 'completed', } return states[self._current_stage] @property def failed_stage(self): return self._failed_stage @property def succeeded(self): return self._current_stage in {'finalize', 'cleanup'} @property def completed(self): return self.failed or self.succeeded @property def aborted(self): return self._aborted @property def skipped(self): return self._skipped def _notify_listeners(self, callback_name): for l in self._listeners: callback = getattr(l, callback_name) callback(self) def _safe_call(self, fn, *args, **kwargs): class update_timestamps: '''Context manager to set the start and finish timestamps.''' # We use `this` to refer to the update_timestamps object, because # we don't want to masquerade the self argument of our containing # function def __enter__(this): if fn.__name__ not in ('poll', 'run_complete', 'compile_complete'): stage = self._current_stage self._timestamps[f'{stage}_start'] = time.time() def __exit__(this, exc_type, exc_value, traceback): stage = self._current_stage self._timestamps[f'{stage}_finish'] = time.time() self._timestamps['pipeline_end'] = time.time() if fn.__name__ not in ('poll', 'run_complete', 'compile_complete'): self._current_stage = fn.__name__ try: with logging.logging_context(self.check) as logger: logger.debug(f'Entering stage: {self._current_stage}') with update_timestamps(): # Pick the configuration of the current partition with runtime.temp_config(self.testcase.partition.fullname): return fn(*args, **kwargs) except SkipTestError as e: if not self.succeeded: # Only skip a test if it hasn't finished yet; # This practically ignores skipping during the cleanup phase self.skip() raise TaskExit from e except ABORT_REASONS: self.fail() raise except BaseException as e: self.fail() raise TaskExit from e def setup(self, *args, **kwargs): self._safe_call(self.check.setup, *args, **kwargs) self._notify_listeners('on_task_setup') def compile(self): self._safe_call(self.check.compile) self._notify_listeners('on_task_compile') def compile_wait(self): self._safe_call(self.check.compile_wait) def run(self): self._safe_call(self.check.run) self._notify_listeners('on_task_run') def run_complete(self): done = self._safe_call(self.check.run_complete) if done: self.zombie = True self._notify_listeners('on_task_exit') return done def compile_complete(self): done = self._safe_call(self.check.compile_complete) if done: self._notify_listeners('on_task_compile_exit') return done def run_wait(self): self._safe_call(self.check.run_wait) self.zombie = False def sanity(self): self._safe_call(self.check.sanity) def performance(self): self._safe_call(self.check.performance) def finalize(self): try: jsonfile = os.path.join(self.check.stagedir, '.rfm_testcase.json') with open(jsonfile, 'w') as fp: jsonext.dump(self.check, fp, indent=2) except OSError as e: logging.getlogger().warning( f'could not dump test case {self.testcase}: {e}' ) self._current_stage = 'finalize' self._notify_listeners('on_task_success') def cleanup(self, *args, **kwargs): self._safe_call(self.check.cleanup, *args, **kwargs) def fail(self, exc_info=None): self._failed_stage = self._current_stage self._exc_info = exc_info or sys.exc_info() self._notify_listeners('on_task_failure') def skip(self, exc_info=None): self._skipped = True self._failed_stage = self._current_stage self._exc_info = exc_info or sys.exc_info() self._notify_listeners('on_task_skip') def abort(self, cause=None): if self.failed or self._aborted: return logging.getlogger().debug2('Aborting test case: {self.testcase!r}') exc = AbortTaskError() exc.__cause__ = cause self._aborted = True try: # FIXME: we should perhaps extend the RegressionTest interface # for supporting job cancelling if not self.zombie and self.check.job: self.check.job.cancel() except JobNotStartedError: self.fail((type(exc), exc, None)) except BaseException: self.fail() else: self.fail((type(exc), exc, None)) def info(self): '''Return an info string about this task.''' name = self.check.display_name part = self.testcase.partition.fullname env = self.testcase.environ.name return f'{name} @{part}+{env}' class TaskEventListener(abc.ABC): @abc.abstractmethod def on_task_setup(self, task): '''Called whenever the setup() method of a RegressionTask is called.''' @abc.abstractmethod def on_task_run(self, task): '''Called whenever the run() method of a RegressionTask is called.''' @abc.abstractmethod def on_task_compile(self, task): '''Called whenever the compile() method of a RegressionTask is called.''' @abc.abstractmethod def on_task_exit(self, task): '''Called whenever a RegressionTask finishes.''' @abc.abstractmethod def on_task_compile_exit(self, task): '''Called whenever a RegressionTask compilation phase finishes.''' @abc.abstractmethod def on_task_skip(self, task): '''Called whenever a RegressionTask is skipped.''' @abc.abstractmethod def on_task_failure(self, task): '''Called when a regression test has failed.''' @abc.abstractmethod def on_task_success(self, task): '''Called when a regression test has succeeded.''' def _handle_sigterm(signum, frame): raise ForceExitError('received TERM signal') class Runner: '''Responsible for executing a set of regression tests based on an execution policy.''' def __init__(self, policy, printer=None, max_retries=0, max_failures=sys.maxsize): self._policy = policy self._printer = printer or PrettyPrinter() self._max_retries = max_retries self._stats = TestStats() self._policy.stats = self._stats self._policy.printer = self._printer self._policy.max_failures = max_failures signal.signal(signal.SIGTERM, _handle_sigterm) @property def max_failures(self): return self._max_failures @property def max_retries(self): return self._max_retries @property def policy(self): return self._policy @property def stats(self): return self._stats def runall(self, testcases, restored_cases=None): num_checks = len({tc.check.unique_name for tc in testcases}) self._printer.separator('short double line', 'Running %d check(s)' % num_checks) self._printer.timestamp('Started on', 'short double line') self._printer.info('') try: self._runall(testcases) if self._max_retries: restored_cases = restored_cases or [] self._retry_failed(testcases + restored_cases) finally: # Print the summary line num_failures = len(self._stats.failed()) num_completed = len(self._stats.completed()) num_skipped = len(self._stats.skipped()) num_tasks = len(self._stats.tasks()) if num_failures > 0 or num_completed + num_skipped < num_tasks: status = 'FAILED' else: status = 'PASSED' total_run = len(testcases) total_completed = len(self._stats.completed(0)) total_skipped = len(self._stats.skipped(0)) self._printer.status( status, f'Ran {total_completed}/{total_run}' f' test case(s) from {num_checks} check(s) ' f'({num_failures} failure(s), {total_skipped} skipped)', just='center' ) self._printer.timestamp('Finished on', 'short double line') def _retry_failed(self, cases): rt = runtime.runtime() failures = self._stats.failed() while (failures and rt.current_run < self._max_retries): num_failed_checks = len({tc.check.unique_name for tc in failures}) rt.next_run() self._printer.separator( 'short double line', 'Retrying %d failed check(s) (retry %d/%d)' % (num_failed_checks, rt.current_run, self._max_retries) ) # Clone failed cases and rebuild dependencies among them failed_cases = [t.testcase.clone() for t in failures] cases_graph, _ = dependencies.build_deps(failed_cases, cases) failed_cases = dependencies.toposort(cases_graph, is_subgraph=True) self._runall(failed_cases) failures = self._stats.failed() def _runall(self, testcases): def print_separator(check, prefix): self._printer.separator( 'short single line', '%s %s (%s)' % (prefix, check.unique_name, check.descr) ) self._printer.separator('short single line', 'start processing checks') self._policy.enter() self._printer.reset_progress(len(testcases)) for t in testcases: self._policy.runcase(t) self._policy.exit() self._printer.separator('short single line', 'all spawned checks have finished\n') class ExecutionPolicy(abc.ABC): '''Base abstract class for execution policies. An execution policy implements the regression check pipeline.''' def __init__(self): # Options controlling the check execution self.force_local = False self.skip_sanity_check = False self.skip_performance_check = False self.keep_stage_files = False self.only_environs = None self.printer = None self.strict_check = False # Local scheduler for running forced local jobs self.local_scheduler = LocalJobScheduler() # Scheduler options self.sched_flex_alloc_nodes = None self.sched_options = [] # Task event listeners self.task_listeners = [] self.stats = None def enter(self): self._num_failed_tasks = 0 def exit(self): pass @abc.abstractmethod def runcase(self, case): '''Run a test case.''' if self.strict_check: case.check.strict_check = True if self.force_local: case.check.local = True
# Copyright 2016-2022 Swiss National Supercomputing Centre (CSCS/ETH Zurich) # ReFrame Project Developers. See the top-level LICENSE file for details. # # SPDX-License-Identifier: BSD-3-Clause import abc import copy import os import signal import sys import time import weakref import reframe.core.logging as logging import reframe.core.runtime as runtime import reframe.frontend.dependencies as dependencies import reframe.utility.jsonext as jsonext from reframe.core.exceptions import (AbortTaskError, JobNotStartedError, FailureLimitError, ForceExitError, SkipTestError, TaskExit) from reframe.core.schedulers.local import LocalJobScheduler from reframe.frontend.printer import PrettyPrinter from reframe.frontend.statistics import TestStats ABORT_REASONS = (AssertionError, FailureLimitError, KeyboardInterrupt, ForceExitError) class TestCase: '''A combination of a regression check, a system partition and a programming environment. ''' def __init__(self, check, partition, environ): self._check_orig = check self._check = copy.deepcopy(check) self._partition = copy.deepcopy(partition) self._environ = copy.deepcopy(environ) self._check._case = weakref.ref(self) self._deps = [] # Incoming dependencies self.in_degree = 0 # Level in the dependency chain self.level = 0 def __iter__(self): # Allow unpacking a test case with a single liner: # c, p, e = case return iter([self._check, self._partition, self._environ]) def __hash__(self): return (hash(self.check.unique_name) ^ hash(self.partition.fullname) ^ hash(self.environ.name)) def __eq__(self, other): if not isinstance(other, type(self)): return NotImplemented return (self.check.unique_name == other.check.unique_name and self.environ.name == other.environ.name and self.partition.fullname == other.partition.fullname) def __repr__(self): c = self.check.unique_name if self.check else None p = self.partition.fullname if self.partition else None e = self.environ.name if self.environ else None return f'({c!r}, {p!r}, {e!r})' @property def check(self): return self._check @property def partition(self): return self._partition @property def environ(self): return self._environ @property def deps(self): return self._deps @property def num_dependents(self): return self.in_degree def clone(self): # Return a fresh clone, i.e., one based on the original check return TestCase(self._check_orig, self._partition, self._environ) def generate_testcases(checks): '''Generate concrete test cases from checks.''' rt = runtime.runtime() cases = [] for c in checks: valid_comb = runtime.valid_sysenv_comb(c.valid_systems, c.valid_prog_environs) for part, environs in valid_comb.items(): for env in environs: cases.append(TestCase(c, part, env)) return cases class RegressionTask: '''A class representing a :class:`RegressionTest` through the regression pipeline.''' def __init__(self, case, listeners=[]): self._case = case self._failed_stage = None self._current_stage = 'startup' self._exc_info = (None, None, None) self._listeners = list(listeners) self._skipped = False # Reference count for dependent tests; safe to cleanup the test only # if it is zero self.ref_count = case.num_dependents # Test case has finished, but has not been waited for yet self.zombie = False # Timestamps for the start and finish phases of the pipeline self._timestamps = {} self._aborted = False def duration(self, phase): # Treat pseudo-phases first if phase == 'compile_complete': t_start = 'compile_start' t_finish = 'compile_wait_finish' elif phase == 'run_complete': t_start = 'run_start' t_finish = 'wait_finish' elif phase == 'total': t_start = 'setup_start' t_finish = 'pipeline_end' else: t_start = f'{phase}_start' t_finish = f'{phase}_finish' start = self._timestamps.get(t_start) if not start: return None finish = self._timestamps.get(t_finish) if not finish: finish = self._timestamps.get('pipeline_end') return finish - start def pipeline_timings(self, phases): def _tf(t): return f'{t:.3f}s' if t else 'n/a' msg = '' for phase in phases: if phase == 'compile_complete': msg += f"compile: {_tf(self.duration('compile_complete'))} " elif phase == 'run_complete': msg += f"run: {_tf(self.duration('run_complete'))} " else: msg += f"{phase}: {_tf(self.duration(phase))} " if msg: msg = msg[:-1] return msg def pipeline_timings_all(self): return self.pipeline_timings([ 'setup', 'compile_complete', 'run_complete', 'sanity', 'performance', 'total' ]) def pipeline_timings_basic(self): return self.pipeline_timings([ 'compile_complete', 'run_complete', 'total' ]) @property def testcase(self): return self._case @property def check(self): return self._case.check @property def exc_info(self): return self._exc_info @property def failed(self): return (self._failed_stage is not None and not self._aborted and not self._skipped) @property def state(self): if self.failed: return 'fail' if self.skipped: return 'skip' states = { 'startup': 'startup', 'setup': 'ready_compile', 'compile': 'compiling', 'compile_wait': 'ready_run', 'run': 'running', 'run_wait': 'completing', 'finalize': 'retired', 'cleanup': 'completed', } return states[self._current_stage] @property def failed_stage(self): return self._failed_stage @property def succeeded(self): return self._current_stage in {'finalize', 'cleanup'} @property def completed(self): return self.failed or self.succeeded @property def aborted(self): return self._aborted @property def skipped(self): return self._skipped def _notify_listeners(self, callback_name): for l in self._listeners: callback = getattr(l, callback_name) callback(self) def _safe_call(self, fn, *args, **kwargs): class update_timestamps: '''Context manager to set the start and finish timestamps.''' # We use `this` to refer to the update_timestamps object, because # we don't want to masquerade the self argument of our containing # function def __enter__(this): if fn.__name__ not in ('poll', 'run_complete', 'compile_complete'): stage = self._current_stage self._timestamps[f'{stage}_start'] = time.time() def __exit__(this, exc_type, exc_value, traceback): stage = self._current_stage self._timestamps[f'{stage}_finish'] = time.time() self._timestamps['pipeline_end'] = time.time() if fn.__name__ not in ('poll', 'run_complete', 'compile_complete'): self._current_stage = fn.__name__ try: with logging.logging_context(self.check) as logger: logger.debug(f'Entering stage: {self._current_stage}') with update_timestamps(): # Pick the configuration of the current partition with runtime.temp_config(self.testcase.partition.fullname): return fn(*args, **kwargs) except SkipTestError as e: if not self.succeeded: # Only skip a test if it hasn't finished yet; # This practically ignores skipping during the cleanup phase self.skip() raise TaskExit from e except ABORT_REASONS: self.fail() raise except BaseException as e: self.fail() raise TaskExit from e def setup(self, *args, **kwargs): self._safe_call(self.check.setup, *args, **kwargs) self._notify_listeners('on_task_setup') def compile(self): self._safe_call(self.check.compile) self._notify_listeners('on_task_compile') def compile_wait(self): self._safe_call(self.check.compile_wait) def run(self): self._safe_call(self.check.run) self._notify_listeners('on_task_run') def run_complete(self): done = self._safe_call(self.check.run_complete) if done: self.zombie = True self._notify_listeners('on_task_exit') return done def compile_complete(self): done = self._safe_call(self.check.compile_complete) if done: self._notify_listeners('on_task_compile_exit') return done def run_wait(self): self._safe_call(self.check.run_wait) self.zombie = False def sanity(self): self._safe_call(self.check.sanity) def performance(self): self._safe_call(self.check.performance) def finalize(self): try: jsonfile = os.path.join(self.check.stagedir, '.rfm_testcase.json') with open(jsonfile, 'w') as fp: jsonext.dump(self.check, fp, indent=2) except OSError as e: logging.getlogger().warning( f'could not dump test case {self.testcase}: {e}' ) self._current_stage = 'finalize' self._notify_listeners('on_task_success') def cleanup(self, *args, **kwargs): self._safe_call(self.check.cleanup, *args, **kwargs) def fail(self, exc_info=None): self._failed_stage = self._current_stage self._exc_info = exc_info or sys.exc_info() self._notify_listeners('on_task_failure') def skip(self, exc_info=None): self._skipped = True self._failed_stage = self._current_stage self._exc_info = exc_info or sys.exc_info() self._notify_listeners('on_task_skip') def abort(self, cause=None): if self.failed or self._aborted: return logging.getlogger().debug2('Aborting test case: {self.testcase!r}') exc = AbortTaskError() exc.__cause__ = cause self._aborted = True try: # FIXME: we should perhaps extend the RegressionTest interface # for supporting job cancelling if not self.zombie and self.check.job: self.check.job.cancel() except JobNotStartedError: self.fail((type(exc), exc, None)) except BaseException: self.fail() else: self.fail((type(exc), exc, None)) def info(self): '''Return an info string about this task.''' name = self.check.display_name part = self.testcase.partition.fullname env = self.testcase.environ.name return f'{name} @{part}+{env}' class TaskEventListener(abc.ABC): @abc.abstractmethod def on_task_setup(self, task): '''Called whenever the setup() method of a RegressionTask is called.''' @abc.abstractmethod def on_task_run(self, task): '''Called whenever the run() method of a RegressionTask is called.''' @abc.abstractmethod def on_task_compile(self, task): '''Called whenever the compile() method of a RegressionTask is called.''' @abc.abstractmethod def on_task_exit(self, task): '''Called whenever a RegressionTask finishes.''' @abc.abstractmethod def on_task_compile_exit(self, task): '''Called whenever a RegressionTask compilation phase finishes.''' @abc.abstractmethod def on_task_skip(self, task): '''Called whenever a RegressionTask is skipped.''' @abc.abstractmethod def on_task_failure(self, task): '''Called when a regression test has failed.''' @abc.abstractmethod def on_task_success(self, task): '''Called when a regression test has succeeded.''' def _handle_sigterm(signum, frame): raise ForceExitError('received TERM signal') class Runner: '''Responsible for executing a set of regression tests based on an execution policy.''' def __init__(self, policy, printer=None, max_retries=0, max_failures=sys.maxsize): self._policy = policy self._printer = printer or PrettyPrinter() self._max_retries = max_retries self._stats = TestStats() self._policy.stats = self._stats self._policy.printer = self._printer self._policy.max_failures = max_failures signal.signal(signal.SIGTERM, _handle_sigterm) @property def max_failures(self): return self._max_failures @property def max_retries(self): return self._max_retries @property def policy(self): return self._policy @property def stats(self): return self._stats def runall(self, testcases, restored_cases=None): num_checks = len({tc.check.unique_name for tc in testcases}) self._printer.separator('short double line', 'Running %d check(s)' % num_checks) self._printer.timestamp('Started on', 'short double line') self._printer.info('') try: self._runall(testcases) if self._max_retries: restored_cases = restored_cases or [] self._retry_failed(testcases + restored_cases) finally: # Print the summary line num_failures = len(self._stats.failed()) num_completed = len(self._stats.completed()) num_skipped = len(self._stats.skipped()) num_tasks = len(self._stats.tasks()) if num_failures > 0 or num_completed + num_skipped < num_tasks: status = 'FAILED' else: status = 'PASSED' total_run = len(testcases) total_completed = len(self._stats.completed(0)) total_skipped = len(self._stats.skipped(0)) self._printer.status( status, f'Ran {total_completed}/{total_run}' f' test case(s) from {num_checks} check(s) ' f'({num_failures} failure(s), {total_skipped} skipped)', just='center' ) self._printer.timestamp('Finished on', 'short double line') def _retry_failed(self, cases): rt = runtime.runtime() failures = self._stats.failed() while (failures and rt.current_run < self._max_retries): num_failed_checks = len({tc.check.unique_name for tc in failures}) rt.next_run() self._printer.separator( 'short double line', 'Retrying %d failed check(s) (retry %d/%d)' % (num_failed_checks, rt.current_run, self._max_retries) ) # Clone failed cases and rebuild dependencies among them failed_cases = [t.testcase.clone() for t in failures] cases_graph, _ = dependencies.build_deps(failed_cases, cases) failed_cases = dependencies.toposort(cases_graph, is_subgraph=True) self._runall(failed_cases) failures = self._stats.failed() def _runall(self, testcases): def print_separator(check, prefix): self._printer.separator( 'short single line', '%s %s (%s)' % (prefix, check.unique_name, check.descr) ) self._printer.separator('short single line', 'start processing checks') self._policy.enter() self._printer.reset_progress(len(testcases)) for t in testcases: self._policy.runcase(t) self._policy.exit() self._printer.separator('short single line', 'all spawned checks have finished\n') class ExecutionPolicy(abc.ABC): '''Base abstract class for execution policies. An execution policy implements the regression check pipeline.''' def __init__(self): # Options controlling the check execution self.force_local = False self.skip_sanity_check = False self.skip_performance_check = False self.keep_stage_files = False self.only_environs = None self.printer = None self.strict_check = False # Local scheduler for running forced local jobs self.local_scheduler = LocalJobScheduler() # Scheduler options self.sched_flex_alloc_nodes = None self.sched_options = [] # Task event listeners self.task_listeners = [] self.stats = None def enter(self): self._num_failed_tasks = 0 def exit(self): pass @abc.abstractmethod def runcase(self, case): '''Run a test case.''' if self.strict_check: case.check.strict_check = True if self.force_local: case.check.local = True
# Copyright (c) 2011-2016 Godefroid Chapelle and ipdb development team # # This file is part of ipdb-extended. # GNU package is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either version 2 of the License, or (at your option) # any later version. # # GNU package is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License # for more details. import os import sys from contextlib import contextmanager __version__ = '1.0.5' from IPython import get_ipython from IPython.core.debugger import BdbQuit_excepthook from IPython.terminal.ipapp import TerminalIPythonApp from IPython.terminal.embed import InteractiveShellEmbed from IPython.terminal.debugger import Pdb import configparser shell = get_ipython() if shell is None: # Not inside IPython # Build a terminal app in order to force ipython to load the # configuration ipapp = TerminalIPythonApp() # Avoid output (banner, prints) ipapp.interact = False ipapp.initialize(['--no-term-title']) shell = ipapp.shell else: # Running inside IPython # Detect if embed shell or not and display a message if isinstance(shell, InteractiveShellEmbed): sys.stderr.write( "\nYou are currently into an embedded ipython shell,\n" "the configuration will not be loaded.\n\n" ) # Let IPython decide about which debugger class to use # This is especially important for tools that fiddle with stdout debugger_cls = shell.debugger_cls def _init_pdb(context=None, prebreak=None, commands=[]) -> Pdb: if context is None: context = os.getenv("IPDBX_CONTEXT_SIZE", get_context_from_config()) try: p = debugger_cls(context=context) except TypeError: p = debugger_cls() p: Pdb # probably TerminalPdb # Interesting: # p.postcmd(stop, line) # Hook method executed just after a command dispatch is finished. # p.preloop(): Hook method executed once when the cmdloop() method is called. # commands += [f"from rich.console import Console; con = Console(); con.print_exception(show_locals=True)"] p.rcLines.extend(commands) # TODO: use p.run() | p.runcall() | p.runeval(). # also checkout pdb.preloop, pdb._runscript # support passing e.g. `function, arg0, arg1, kwarg='foo'` ? _exec_prebreak(prebreak) return p def wrap_sys_excepthook(): # make sure we wrap it only once or we would end up with a cycle # BdbQuit_excepthook.excepthook_ori == BdbQuit_excepthook if sys.excepthook != BdbQuit_excepthook: BdbQuit_excepthook.excepthook_ori = sys.excepthook sys.excepthook = BdbQuit_excepthook def wrap_sys_breakpointhook(*set_trace_args, **set_trace_kwargs): if sys.breakpointhook.__module__ == 'sys': if set_trace_args or set_trace_kwargs: from functools import partial set_trace_fn = partial(set_trace, *set_trace_args, **set_trace_kwargs) else: set_trace_fn = set_trace sys.breakpointhook = set_trace_fn print('wrapped sys.breakpointhook') else: print(f'sys.breakpointhook already patched: {sys.breakpointhook}') def unwrap_sys_breakpointhook(): if sys.breakpointhook.__module__ == 'sys': print(f'sys.breakpointhook already reset: {sys.breakpointhook}') return if sys.__breakpointhook__.__module__ != 'sys': print('ERROR | ipdbx.unwrap_sys_breakpointhook() | "backup" sys.__breakpointhook__ is itself patched. Cannot unwrap.') return sys.breakpointhook = sys.__breakpointhook__ print('reset sys.breakpointhook') def set_trace(frame=None, context=None, cond=True, prebreak=None): if not cond: return wrap_sys_excepthook() if frame is None: frame = sys._getframe().f_back p = _init_pdb(context, prebreak).set_trace(frame) if p and hasattr(p, 'shell'): p.shell.restore_sys_module_state() def _exec_prebreak(prebreak=None): """Can handle a python file path, string representing a python statement, or a code object""" # todo: support executing .ipy files print('ipdbx _exec_prebreak(%s)' % repr(prebreak)) if prebreak is False: # prebreak=False means explicitly not to run prebreak return prebreak = prebreak or os.getenv("IPDBX_PREBREAK", get_prebreak_from_config()) if prebreak is None: return try: with open(prebreak, 'rb') as f: exec(compile(f.read(), prebreak, 'exec')) except FileNotFoundError: try: # either a string or a code object exec(prebreak) except TypeError: print('ipdbx _exec_prebreak(): prebreak is not None but failed compilation and execution: ', repr(prebreak)) def get_prebreak_from_config(): """`prebreak` field can be a python file path, or string representing a python statement""" # todo: support multiple statements (list of strings?) parser = get_config() try: prebreak = parser.get('ipdbx', 'prebreak') print(f"ipdbx get_prebreak_from_config(): prebreak from {getattr(parser, "filepath", parser)}: ", prebreak) return prebreak except (configparser.NoSectionError, configparser.NoOptionError) as e: print('ipdbx get_prebreak_from_config(): NO prebreak from ', getattr(parser, 'filepath', parser)) return None def get_context_from_config(): parser = get_config() try: return parser.getint("tool.ipdbx", "context") except (configparser.NoSectionError, configparser.NoOptionError): return 10 except ValueError: value = parser.get("tool.ipdbx", "context") raise ValueError(f"In {getattr(parser,"filepath",parser)}, context value [{value}] cannot be converted into an integer.") class ConfigFile(object): """ Filehandle wrapper that adds a "[ipdbx]" section to the start of a config file so that users don't actually have to manually add a [ipdbx] section. Works with configparser versions from both Python 2 and 3 """ def __init__(self, filepath): self.first = True with open(filepath) as f: self.lines = f.readlines() def __iter__(self): return self def __next__(self): if self.first: self.first = False return "[ipdbx]\n" if self.lines: return self.lines.pop(0) raise StopIteration def get_config() -> configparser.ConfigParser: """ Get ipdbx config file settings. All available config files are read. If settings are in multiple configs, the last value encountered wins. Values specified on the command-line take precedence over all config file settings. Returns: A ConfigParser object. """ parser = configparser.ConfigParser() filepaths = [] # Low priority goes first in the list for cfg_file in ("setup.cfg", ".ipdbx", "pyproject.toml"): cwd_filepath = os.path.join(os.getcwd(), cfg_file) if os.path.isfile(cwd_filepath): filepaths.append(cwd_filepath) # Medium priority (whenever user wants to set a specific path to config file) home = os.getenv("HOME") if home: default_filepath = os.path.join(home, ".ipdbx") if os.path.isfile(default_filepath): filepaths.append(default_filepath) # High priority (default files) env_filepath = os.getenv("IPDBX_CONFIG") if env_filepath and os.path.isfile(env_filepath): filepaths.append(env_filepath) if filepaths: for filepath in filepaths: parser.filepath = filepath # Users are expected to put an [ipdbx] section # only if they use setup.cfg if filepath.endswith('setup.cfg') or filepath.endswith('pyproject.toml'): with open(filepath) as f: parser.remove_section("ipdbx") parser.read_file(f) else: parser.remove_section("tool.ipdbx") parser.read_file(ConfigFile(filepath)) return parser def post_mortem(tb=None): wrap_sys_excepthook() p = _init_pdb() p.reset() if tb is None: # sys.exc_info() returns (type, value, traceback) if an exception is # being handled, otherwise it returns None tb = sys.exc_info()[2] if tb: p.interaction(None, tb) def pm(): post_mortem(sys.last_traceback) def run(statement, globals=None, locals=None): _init_pdb().run(statement, globals, locals) def runcall(*args, **kwargs): return _init_pdb().runcall(*args, **kwargs) def runeval(expression, globals=None, locals=None): return _init_pdb().runeval(expression, globals, locals) @contextmanager def launch_ipdb_on_exception(): try: yield except Exception: e, m, tb = sys.exc_info() print(m.__repr__(), file=sys.stderr) post_mortem(tb) finally: pass _usage = """\ usage: python -m ipdbx [-m] [-c COMMAND] [-h, --help] [-V, --version] [-p, --prebreak PREBREAK] pyfile [arg] ... Debug the Python program given by pyfile. Initial commands are read from .pdbrc files in your home directory and in the current directory, if they exist. Commands supplied with -c are executed after commands from .pdbrc files. Looks for config files in the following order (last overruns first): - cwd: 'setup.cfg', '.ipdbx' - $HOME: '.ipdbx' - $IPDBX_CONFIG Config files support the following fields: - context (number) - prebreak Supported env vars: - IPDBX_CONFIG - IPDBX_CONTEXT_SIZE - IPDBX_PREBREAK To let the script run until an exception occurs, use "-c continue". To let the script run up to a given line X in the debugged file, use "-c 'until X'" Option -m is available only in Python 3.7 and later. ipdbx version %s.""" % __version__ def main(): import traceback import sys import getopt import os import logging logger = logging.Logger("root", level=logging.DEBUG) logger.debug(f"ipdbx | main({", ".join(sys.argv[1:])})") try: from pdb import Restart except ImportError: class Restart(Exception): pass if sys.version_info >= (3, 7): opts, args = getopt.getopt(sys.argv[1:], 'mhVp:c:', ['help', 'version', 'prebreak=', 'command=']) else: opts, args = getopt.getopt(sys.argv[1:], 'hVp:c:', ['help', 'version', 'prebreak=', 'command=']) commands = [] prebreak = None run_as_module = False for opt, optarg in opts: if opt in ['-h', '--help']: print(_usage) sys.exit() elif opt in ['-c', '--command']: breakpoint() commands.append(optarg) elif opt in ['-p', '--prebreak']: prebreak = optarg elif opt in ['-V', '--version']: print(f"ipdbx version: {__version__}") sys.exit() elif opt in ['-m']: run_as_module = True if not args: print(_usage) sys.exit(2) mainpyfile = args[0] # Get script filename if not run_as_module and not os.path.exists(mainpyfile): print('Error:', mainpyfile, 'does not exist') sys.exit(1) sys.argv = args # Hide "pdb.py" from argument list # Replace pdb's dir with script's dir in front of module search path. if not run_as_module: sys.path[0] = os.path.dirname(mainpyfile) # Note on saving/restoring sys.argv: it's a good idea when sys.argv was # modified by the script being debugged. It's a bad idea when it was # changed by the user from the command line. There is a "restart" command # which allows explicit specification of command line arguments. pdb = _init_pdb(prebreak=prebreak, commands=commands) while 1: try: if run_as_module: pdb._runmodule(mainpyfile) else: pdb._runscript(mainpyfile) if pdb._user_requested_quit: break print("The program finished and will be restarted") except Restart: print("Restarting", mainpyfile, "with arguments:") print("\t" + " ".join(sys.argv[1:])) except SystemExit: # In most cases SystemExit does not warrant a post-mortem session. print("The program exited via sys.exit(). Exit status: ", end='') print(sys.exc_info()[1]) except: traceback.print_exc() print("Uncaught exception. Entering post mortem debugging") print("Running 'cont' or 'step' will restart the program") t = sys.exc_info()[2] pdb.interaction(None, t) print("Post mortem debugger finished. The " + mainpyfile + " will be restarted") if __name__ == '__main__': main()
# Copyright (c) 2011-2016 Godefroid Chapelle and ipdb development team # # This file is part of ipdb-extended. # GNU package is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either version 2 of the License, or (at your option) # any later version. # # GNU package is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License # for more details. import os import sys from contextlib import contextmanager __version__ = '1.0.5' from IPython import get_ipython from IPython.core.debugger import BdbQuit_excepthook from IPython.terminal.ipapp import TerminalIPythonApp from IPython.terminal.embed import InteractiveShellEmbed from IPython.terminal.debugger import Pdb import configparser shell = get_ipython() if shell is None: # Not inside IPython # Build a terminal app in order to force ipython to load the # configuration ipapp = TerminalIPythonApp() # Avoid output (banner, prints) ipapp.interact = False ipapp.initialize(['--no-term-title']) shell = ipapp.shell else: # Running inside IPython # Detect if embed shell or not and display a message if isinstance(shell, InteractiveShellEmbed): sys.stderr.write( "\nYou are currently into an embedded ipython shell,\n" "the configuration will not be loaded.\n\n" ) # Let IPython decide about which debugger class to use # This is especially important for tools that fiddle with stdout debugger_cls = shell.debugger_cls def _init_pdb(context=None, prebreak=None, commands=[]) -> Pdb: if context is None: context = os.getenv("IPDBX_CONTEXT_SIZE", get_context_from_config()) try: p = debugger_cls(context=context) except TypeError: p = debugger_cls() p: Pdb # probably TerminalPdb # Interesting: # p.postcmd(stop, line) # Hook method executed just after a command dispatch is finished. # p.preloop(): Hook method executed once when the cmdloop() method is called. # commands += [f"from rich.console import Console; con = Console(); con.print_exception(show_locals=True)"] p.rcLines.extend(commands) # TODO: use p.run() | p.runcall() | p.runeval(). # also checkout pdb.preloop, pdb._runscript # support passing e.g. `function, arg0, arg1, kwarg='foo'` ? _exec_prebreak(prebreak) return p def wrap_sys_excepthook(): # make sure we wrap it only once or we would end up with a cycle # BdbQuit_excepthook.excepthook_ori == BdbQuit_excepthook if sys.excepthook != BdbQuit_excepthook: BdbQuit_excepthook.excepthook_ori = sys.excepthook sys.excepthook = BdbQuit_excepthook def wrap_sys_breakpointhook(*set_trace_args, **set_trace_kwargs): if sys.breakpointhook.__module__ == 'sys': if set_trace_args or set_trace_kwargs: from functools import partial set_trace_fn = partial(set_trace, *set_trace_args, **set_trace_kwargs) else: set_trace_fn = set_trace sys.breakpointhook = set_trace_fn print('wrapped sys.breakpointhook') else: print(f'sys.breakpointhook already patched: {sys.breakpointhook}') def unwrap_sys_breakpointhook(): if sys.breakpointhook.__module__ == 'sys': print(f'sys.breakpointhook already reset: {sys.breakpointhook}') return if sys.__breakpointhook__.__module__ != 'sys': print('ERROR | ipdbx.unwrap_sys_breakpointhook() | "backup" sys.__breakpointhook__ is itself patched. Cannot unwrap.') return sys.breakpointhook = sys.__breakpointhook__ print('reset sys.breakpointhook') def set_trace(frame=None, context=None, cond=True, prebreak=None): if not cond: return wrap_sys_excepthook() if frame is None: frame = sys._getframe().f_back p = _init_pdb(context, prebreak).set_trace(frame) if p and hasattr(p, 'shell'): p.shell.restore_sys_module_state() def _exec_prebreak(prebreak=None): """Can handle a python file path, string representing a python statement, or a code object""" # todo: support executing .ipy files print('ipdbx _exec_prebreak(%s)' % repr(prebreak)) if prebreak is False: # prebreak=False means explicitly not to run prebreak return prebreak = prebreak or os.getenv("IPDBX_PREBREAK", get_prebreak_from_config()) if prebreak is None: return try: with open(prebreak, 'rb') as f: exec(compile(f.read(), prebreak, 'exec')) except FileNotFoundError: try: # either a string or a code object exec(prebreak) except TypeError: print('ipdbx _exec_prebreak(): prebreak is not None but failed compilation and execution: ', repr(prebreak)) def get_prebreak_from_config(): """`prebreak` field can be a python file path, or string representing a python statement""" # todo: support multiple statements (list of strings?) parser = get_config() try: prebreak = parser.get('ipdbx', 'prebreak') print(f"ipdbx get_prebreak_from_config(): prebreak from {getattr(parser, 'filepath', parser)}: ", prebreak) return prebreak except (configparser.NoSectionError, configparser.NoOptionError) as e: print('ipdbx get_prebreak_from_config(): NO prebreak from ', getattr(parser, 'filepath', parser)) return None def get_context_from_config(): parser = get_config() try: return parser.getint("tool.ipdbx", "context") except (configparser.NoSectionError, configparser.NoOptionError): return 10 except ValueError: value = parser.get("tool.ipdbx", "context") raise ValueError(f"In {getattr(parser,'filepath',parser)}, context value [{value}] cannot be converted into an integer.") class ConfigFile(object): """ Filehandle wrapper that adds a "[ipdbx]" section to the start of a config file so that users don't actually have to manually add a [ipdbx] section. Works with configparser versions from both Python 2 and 3 """ def __init__(self, filepath): self.first = True with open(filepath) as f: self.lines = f.readlines() def __iter__(self): return self def __next__(self): if self.first: self.first = False return "[ipdbx]\n" if self.lines: return self.lines.pop(0) raise StopIteration def get_config() -> configparser.ConfigParser: """ Get ipdbx config file settings. All available config files are read. If settings are in multiple configs, the last value encountered wins. Values specified on the command-line take precedence over all config file settings. Returns: A ConfigParser object. """ parser = configparser.ConfigParser() filepaths = [] # Low priority goes first in the list for cfg_file in ("setup.cfg", ".ipdbx", "pyproject.toml"): cwd_filepath = os.path.join(os.getcwd(), cfg_file) if os.path.isfile(cwd_filepath): filepaths.append(cwd_filepath) # Medium priority (whenever user wants to set a specific path to config file) home = os.getenv("HOME") if home: default_filepath = os.path.join(home, ".ipdbx") if os.path.isfile(default_filepath): filepaths.append(default_filepath) # High priority (default files) env_filepath = os.getenv("IPDBX_CONFIG") if env_filepath and os.path.isfile(env_filepath): filepaths.append(env_filepath) if filepaths: for filepath in filepaths: parser.filepath = filepath # Users are expected to put an [ipdbx] section # only if they use setup.cfg if filepath.endswith('setup.cfg') or filepath.endswith('pyproject.toml'): with open(filepath) as f: parser.remove_section("ipdbx") parser.read_file(f) else: parser.remove_section("tool.ipdbx") parser.read_file(ConfigFile(filepath)) return parser def post_mortem(tb=None): wrap_sys_excepthook() p = _init_pdb() p.reset() if tb is None: # sys.exc_info() returns (type, value, traceback) if an exception is # being handled, otherwise it returns None tb = sys.exc_info()[2] if tb: p.interaction(None, tb) def pm(): post_mortem(sys.last_traceback) def run(statement, globals=None, locals=None): _init_pdb().run(statement, globals, locals) def runcall(*args, **kwargs): return _init_pdb().runcall(*args, **kwargs) def runeval(expression, globals=None, locals=None): return _init_pdb().runeval(expression, globals, locals) @contextmanager def launch_ipdb_on_exception(): try: yield except Exception: e, m, tb = sys.exc_info() print(m.__repr__(), file=sys.stderr) post_mortem(tb) finally: pass _usage = """\ usage: python -m ipdbx [-m] [-c COMMAND] [-h, --help] [-V, --version] [-p, --prebreak PREBREAK] pyfile [arg] ... Debug the Python program given by pyfile. Initial commands are read from .pdbrc files in your home directory and in the current directory, if they exist. Commands supplied with -c are executed after commands from .pdbrc files. Looks for config files in the following order (last overruns first): - cwd: 'setup.cfg', '.ipdbx' - $HOME: '.ipdbx' - $IPDBX_CONFIG Config files support the following fields: - context (number) - prebreak Supported env vars: - IPDBX_CONFIG - IPDBX_CONTEXT_SIZE - IPDBX_PREBREAK To let the script run until an exception occurs, use "-c continue". To let the script run up to a given line X in the debugged file, use "-c 'until X'" Option -m is available only in Python 3.7 and later. ipdbx version %s.""" % __version__ def main(): import traceback import sys import getopt import os import logging logger = logging.Logger("root", level=logging.DEBUG) logger.debug(f"ipdbx | main({', '.join(sys.argv[1:])})") try: from pdb import Restart except ImportError: class Restart(Exception): pass if sys.version_info >= (3, 7): opts, args = getopt.getopt(sys.argv[1:], 'mhVp:c:', ['help', 'version', 'prebreak=', 'command=']) else: opts, args = getopt.getopt(sys.argv[1:], 'hVp:c:', ['help', 'version', 'prebreak=', 'command=']) commands = [] prebreak = None run_as_module = False for opt, optarg in opts: if opt in ['-h', '--help']: print(_usage) sys.exit() elif opt in ['-c', '--command']: breakpoint() commands.append(optarg) elif opt in ['-p', '--prebreak']: prebreak = optarg elif opt in ['-V', '--version']: print(f"ipdbx version: {__version__}") sys.exit() elif opt in ['-m']: run_as_module = True if not args: print(_usage) sys.exit(2) mainpyfile = args[0] # Get script filename if not run_as_module and not os.path.exists(mainpyfile): print('Error:', mainpyfile, 'does not exist') sys.exit(1) sys.argv = args # Hide "pdb.py" from argument list # Replace pdb's dir with script's dir in front of module search path. if not run_as_module: sys.path[0] = os.path.dirname(mainpyfile) # Note on saving/restoring sys.argv: it's a good idea when sys.argv was # modified by the script being debugged. It's a bad idea when it was # changed by the user from the command line. There is a "restart" command # which allows explicit specification of command line arguments. pdb = _init_pdb(prebreak=prebreak, commands=commands) while 1: try: if run_as_module: pdb._runmodule(mainpyfile) else: pdb._runscript(mainpyfile) if pdb._user_requested_quit: break print("The program finished and will be restarted") except Restart: print("Restarting", mainpyfile, "with arguments:") print("\t" + " ".join(sys.argv[1:])) except SystemExit: # In most cases SystemExit does not warrant a post-mortem session. print("The program exited via sys.exit(). Exit status: ", end='') print(sys.exc_info()[1]) except: traceback.print_exc() print("Uncaught exception. Entering post mortem debugging") print("Running 'cont' or 'step' will restart the program") t = sys.exc_info()[2] pdb.interaction(None, t) print("Post mortem debugger finished. The " + mainpyfile + " will be restarted") if __name__ == '__main__': main()
try: import dask import dask.array from dask.array.utils import meta_from_array from dask.highlevelgraph import HighLevelGraph except ImportError: pass import collections import itertools import operator from typing import ( Any, Callable, DefaultDict, Dict, Hashable, Iterable, List, Mapping, Sequence, Tuple, TypeVar, Union, ) import numpy as np from xarray.core.indexes import PandasIndex from .alignment import align from .dataarray import DataArray from .dataset import Dataset T_DSorDA = TypeVar("T_DSorDA", DataArray, Dataset) def unzip(iterable): return zip(*iterable) def assert_chunks_compatible(a: Dataset, b: Dataset): a = a.unify_chunks() b = b.unify_chunks() for dim in set(a.chunks).intersection(set(b.chunks)): if a.chunks[dim] != b.chunks[dim]: raise ValueError(f"Chunk sizes along dimension {dim!r} are not equal.") def check_result_variables( result: Union[DataArray, Dataset], expected: Mapping[str, Any], kind: str ): if kind == "coords": nice_str = "coordinate" elif kind == "data_vars": nice_str = "data" # check that coords and data variables are as expected missing = expected[kind] - set(getattr(result, kind)) if missing: raise ValueError( "Result from applying user function does not contain " f"{nice_str} variables {missing}." ) extra = set(getattr(result, kind)) - expected[kind] if extra: raise ValueError( "Result from applying user function has unexpected " f"{nice_str} variables {extra}." ) def dataset_to_dataarray(obj: Dataset) -> DataArray: if not isinstance(obj, Dataset): raise TypeError(f"Expected Dataset, got {type(obj)}") if len(obj.data_vars) > 1: raise TypeError( "Trying to convert Dataset with more than one data variable to DataArray" ) return next(iter(obj.data_vars.values())) def dataarray_to_dataset(obj: DataArray) -> Dataset: # only using _to_temp_dataset would break # func = lambda x: x.to_dataset() # since that relies on preserving name. if obj.name is None: dataset = obj._to_temp_dataset() else: dataset = obj.to_dataset() return dataset def make_meta(obj): """If obj is a DataArray or Dataset, return a new object of the same type and with the same variables and dtypes, but where all variables have size 0 and numpy backend. If obj is neither a DataArray nor Dataset, return it unaltered. """ if isinstance(obj, DataArray): obj_array = obj obj = dataarray_to_dataset(obj) elif isinstance(obj, Dataset): obj_array = None else: return obj meta = Dataset() for name, variable in obj.variables.items(): meta_obj = meta_from_array(variable.data, ndim=variable.ndim) meta[name] = (variable.dims, meta_obj, variable.attrs) meta.attrs = obj.attrs meta = meta.set_coords(obj.coords) if obj_array is not None: return dataset_to_dataarray(meta) return meta def infer_template( func: Callable[..., T_DSorDA], obj: Union[DataArray, Dataset], *args, **kwargs ) -> T_DSorDA: """Infer return object by running the function on meta objects.""" meta_args = [make_meta(arg) for arg in (obj,) + args] try: template = func(*meta_args, **kwargs) except Exception as e: raise Exception( "Cannot infer object returned from running user provided function. " "Please supply the 'template' kwarg to map_blocks." ) from e if not isinstance(template, (Dataset, DataArray)): raise TypeError( "Function must return an xarray DataArray or Dataset. Instead it returned " f"{type(template)}" ) return template def make_dict(x: Union[DataArray, Dataset]) -> Dict[Hashable, Any]: """Map variable name to numpy(-like) data (Dataset.to_dict() is too complicated). """ if isinstance(x, DataArray): x = x._to_temp_dataset() return {k: v.data for k, v in x.variables.items()} def _get_chunk_slicer(dim: Hashable, chunk_index: Mapping, chunk_bounds: Mapping): if dim in chunk_index: which_chunk = chunk_index[dim] return slice(chunk_bounds[dim][which_chunk], chunk_bounds[dim][which_chunk + 1]) return slice(None) def map_blocks( func: Callable[..., T_DSorDA], obj: Union[DataArray, Dataset], args: Sequence[Any] = (), kwargs: Mapping[str, Any] = None, template: Union[DataArray, Dataset] = None, ) -> T_DSorDA: """Apply a function to each block of a DataArray or Dataset. .. warning:: This function is experimental and its signature may change. Parameters ---------- func : callable User-provided function that accepts a DataArray or Dataset as its first parameter ``obj``. The function will receive a subset or 'block' of ``obj`` (see below), corresponding to one chunk along each chunked dimension. ``func`` will be executed as ``func(subset_obj, *subset_args, **kwargs)``. This function must return either a single DataArray or a single Dataset. This function cannot add a new chunked dimension. obj : DataArray, Dataset Passed to the function as its first argument, one block at a time. args : sequence Passed to func after unpacking and subsetting any xarray objects by blocks. xarray objects in args must be aligned with obj, otherwise an error is raised. kwargs : mapping Passed verbatim to func after unpacking. xarray objects, if any, will not be subset to blocks. Passing dask collections in kwargs is not allowed. template : DataArray or Dataset, optional xarray object representing the final result after compute is called. If not provided, the function will be first run on mocked-up data, that looks like ``obj`` but has sizes 0, to determine properties of the returned object such as dtype, variable names, attributes, new dimensions and new indexes (if any). ``template`` must be provided if the function changes the size of existing dimensions. When provided, ``attrs`` on variables in `template` are copied over to the result. Any ``attrs`` set by ``func`` will be ignored. Returns ------- A single DataArray or Dataset with dask backend, reassembled from the outputs of the function. Notes ----- This function is designed for when ``func`` needs to manipulate a whole xarray object subset to each block. Each block is loaded into memory. In the more common case where ``func`` can work on numpy arrays, it is recommended to use ``apply_ufunc``. If none of the variables in ``obj`` is backed by dask arrays, calling this function is equivalent to calling ``func(obj, *args, **kwargs)``. See Also -------- dask.array.map_blocks, xarray.apply_ufunc, xarray.Dataset.map_blocks xarray.DataArray.map_blocks Examples -------- Calculate an anomaly from climatology using ``.groupby()``. Using ``xr.map_blocks()`` allows for parallel operations with knowledge of ``xarray``, its indices, and its methods like ``.groupby()``. >>> def calculate_anomaly(da, groupby_type="time.month"): ... gb = da.groupby(groupby_type) ... clim = gb.mean(dim="time") ... return gb - clim ... >>> time = xr.cftime_range("1990-01", "1992-01", freq="M") >>> month = xr.DataArray(time.month, coords={"time": time}, dims=["time"]) >>> np.random.seed(123) >>> array = xr.DataArray( ... np.random.rand(len(time)), ... dims=["time"], ... coords={"time": time, "month": month}, ... ).chunk() >>> array.map_blocks(calculate_anomaly, template=array).compute() <xarray.DataArray (time: 24)> array([ 0.12894847, 0.11323072, -0.0855964 , -0.09334032, 0.26848862, 0.12382735, 0.22460641, 0.07650108, -0.07673453, -0.22865714, -0.19063865, 0.0590131 , -0.12894847, -0.11323072, 0.0855964 , 0.09334032, -0.26848862, -0.12382735, -0.22460641, -0.07650108, 0.07673453, 0.22865714, 0.19063865, -0.0590131 ]) Coordinates: * time (time) object 1990-01-31 00:00:00 ... 1991-12-31 00:00:00 month (time) int64 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12 Note that one must explicitly use ``args=[]`` and ``kwargs={}`` to pass arguments to the function being applied in ``xr.map_blocks()``: >>> array.map_blocks( ... calculate_anomaly, ... kwargs={"groupby_type": "time.year"}, ... template=array, ... ) # doctest: +ELLIPSIS <xarray.DataArray (time: 24)> dask.array<<this-array>-calculate_anomaly, shape=(24,), dtype=float64, chunksize=(24,), chunktype=numpy.ndarray> Coordinates: * time (time) object 1990-01-31 00:00:00 ... 1991-12-31 00:00:00 month (time) int64 dask.array<chunksize=(24,), meta=np.ndarray> """ def _wrapper( func: Callable, args: List, kwargs: dict, arg_is_array: Iterable[bool], expected: dict, ): """ Wrapper function that receives datasets in args; converts to dataarrays when necessary; passes these to the user function `func` and checks returned objects for expected shapes/sizes/etc. """ converted_args = [ dataset_to_dataarray(arg) if is_array else arg for is_array, arg in zip(arg_is_array, args) ] result = func(*converted_args, **kwargs) # check all dims are present missing_dimensions = set(expected["shapes"]) - set(result.sizes) if missing_dimensions: raise ValueError( f"Dimensions {missing_dimensions} missing on returned object." ) # check that index lengths and values are as expected for name, index in result.xindexes.items(): if name in expected["shapes"]: if len(index) != expected["shapes"][name]: raise ValueError( f"Received dimension {name!r} of length {len(index)}. Expected length {expected["shapes"][name]}." ) if name in expected["indexes"]: expected_index = expected["indexes"][name] if not index.equals(expected_index): raise ValueError( f"Expected index {name!r} to be {expected_index!r}. Received {index!r} instead." ) # check that all expected variables were returned check_result_variables(result, expected, "coords") if isinstance(result, Dataset): check_result_variables(result, expected, "data_vars") return make_dict(result) if template is not None and not isinstance(template, (DataArray, Dataset)): raise TypeError( f"template must be a DataArray or Dataset. Received {type(template).__name__} instead." ) if not isinstance(args, Sequence): raise TypeError("args must be a sequence (for example, a list or tuple).") if kwargs is None: kwargs = {} elif not isinstance(kwargs, Mapping): raise TypeError("kwargs must be a mapping (for example, a dict)") for value in kwargs.values(): if dask.is_dask_collection(value): raise TypeError( "Cannot pass dask collections in kwargs yet. Please compute or " "load values before passing to map_blocks." ) if not dask.is_dask_collection(obj): return func(obj, *args, **kwargs) all_args = [obj] + list(args) is_xarray = [isinstance(arg, (Dataset, DataArray)) for arg in all_args] is_array = [isinstance(arg, DataArray) for arg in all_args] # there should be a better way to group this. partition? xarray_indices, xarray_objs = unzip( (index, arg) for index, arg in enumerate(all_args) if is_xarray[index] ) others = [ (index, arg) for index, arg in enumerate(all_args) if not is_xarray[index] ] # all xarray objects must be aligned. This is consistent with apply_ufunc. aligned = align(*xarray_objs, join="exact") xarray_objs = tuple( dataarray_to_dataset(arg) if is_da else arg for is_da, arg in zip(is_array, aligned) ) _, npargs = unzip( sorted(list(zip(xarray_indices, xarray_objs)) + others, key=lambda x: x[0]) ) # check that chunk sizes are compatible input_chunks = dict(npargs[0].chunks) input_indexes = dict(npargs[0].xindexes) for arg in xarray_objs[1:]: assert_chunks_compatible(npargs[0], arg) input_chunks.update(arg.chunks) input_indexes.update(arg.xindexes) if template is None: # infer template by providing zero-shaped arrays template = infer_template(func, aligned[0], *args, **kwargs) template_indexes = set(template.xindexes) preserved_indexes = template_indexes & set(input_indexes) new_indexes = template_indexes - set(input_indexes) indexes = {dim: input_indexes[dim] for dim in preserved_indexes} indexes.update({k: template.xindexes[k] for k in new_indexes}) output_chunks = { dim: input_chunks[dim] for dim in template.dims if dim in input_chunks } else: # template xarray object has been provided with proper sizes and chunk shapes indexes = dict(template.xindexes) if isinstance(template, DataArray): output_chunks = dict( zip(template.dims, template.chunks) # type: ignore[arg-type] ) else: output_chunks = dict(template.chunks) for dim in output_chunks: if dim in input_chunks and len(input_chunks[dim]) != len(output_chunks[dim]): raise ValueError( "map_blocks requires that one block of the input maps to one block of output. " f"Expected number of output chunks along dimension {dim!r} to be {len(input_chunks[dim])}. " f"Received {len(output_chunks[dim])} instead. Please provide template if not provided, or " "fix the provided template." ) if isinstance(template, DataArray): result_is_array = True template_name = template.name template = template._to_temp_dataset() elif isinstance(template, Dataset): result_is_array = False else: raise TypeError( f"func output must be DataArray or Dataset; got {type(template)}" ) # We're building a new HighLevelGraph hlg. We'll have one new layer # for each variable in the dataset, which is the result of the # func applied to the values. graph: Dict[Any, Any] = {} new_layers: DefaultDict[str, Dict[Any, Any]] = collections.defaultdict(dict) gname = "{}-{}".format( dask.utils.funcname(func), dask.base.tokenize(npargs[0], args, kwargs) ) # map dims to list of chunk indexes ichunk = {dim: range(len(chunks_v)) for dim, chunks_v in input_chunks.items()} # mapping from chunk index to slice bounds input_chunk_bounds = { dim: np.cumsum((0,) + chunks_v) for dim, chunks_v in input_chunks.items() } output_chunk_bounds = { dim: np.cumsum((0,) + chunks_v) for dim, chunks_v in output_chunks.items() } def subset_dataset_to_block( graph: dict, gname: str, dataset: Dataset, input_chunk_bounds, chunk_index ): """ Creates a task that subsets an xarray dataset to a block determined by chunk_index. Block extents are determined by input_chunk_bounds. Also subtasks that subset the constituent variables of a dataset. """ # this will become [[name1, variable1], # [name2, variable2], # ...] # which is passed to dict and then to Dataset data_vars = [] coords = [] chunk_tuple = tuple(chunk_index.values()) for name, variable in dataset.variables.items(): # make a task that creates tuple of (dims, chunk) if dask.is_dask_collection(variable.data): # recursively index into dask_keys nested list to get chunk chunk = variable.__dask_keys__() for dim in variable.dims: chunk = chunk[chunk_index[dim]] chunk_variable_task = (f"{name}-{gname}-{chunk[0]}",) + chunk_tuple graph[chunk_variable_task] = ( tuple, [variable.dims, chunk, variable.attrs], ) else: # non-dask array possibly with dimensions chunked on other variables # index into variable appropriately subsetter = { dim: _get_chunk_slicer(dim, chunk_index, input_chunk_bounds) for dim in variable.dims } subset = variable.isel(subsetter) chunk_variable_task = ( f"{name}-{gname}-{dask.base.tokenize(subset)}", ) + chunk_tuple graph[chunk_variable_task] = ( tuple, [subset.dims, subset, subset.attrs], ) # this task creates dict mapping variable name to above tuple if name in dataset._coord_names: coords.append([name, chunk_variable_task]) else: data_vars.append([name, chunk_variable_task]) return (Dataset, (dict, data_vars), (dict, coords), dataset.attrs) # iterate over all possible chunk combinations for chunk_tuple in itertools.product(*ichunk.values()): # mapping from dimension name to chunk index chunk_index = dict(zip(ichunk.keys(), chunk_tuple)) blocked_args = [ subset_dataset_to_block(graph, gname, arg, input_chunk_bounds, chunk_index) if isxr else arg for isxr, arg in zip(is_xarray, npargs) ] # expected["shapes", "coords", "data_vars", "indexes"] are used to # raise nice error messages in _wrapper expected = {} # input chunk 0 along a dimension maps to output chunk 0 along the same dimension # even if length of dimension is changed by the applied function expected["shapes"] = { k: output_chunks[k][v] for k, v in chunk_index.items() if k in output_chunks } expected["data_vars"] = set(template.data_vars.keys()) # type: ignore[assignment] expected["coords"] = set(template.coords.keys()) # type: ignore[assignment] # TODO: benbovy - flexible indexes: clean this up # for now assumes pandas index (thus can be indexed) but it won't be the case for # all indexes expected_indexes = {} for dim in indexes: idx = indexes[dim].to_pandas_index()[ _get_chunk_slicer(dim, chunk_index, output_chunk_bounds) ] expected_indexes[dim] = PandasIndex(idx) expected["indexes"] = expected_indexes from_wrapper = (gname,) + chunk_tuple graph[from_wrapper] = (_wrapper, func, blocked_args, kwargs, is_array, expected) # mapping from variable name to dask graph key var_key_map: Dict[Hashable, str] = {} for name, variable in template.variables.items(): if name in indexes: continue gname_l = f"{name}-{gname}" var_key_map[name] = gname_l key: Tuple[Any, ...] = (gname_l,) for dim in variable.dims: if dim in chunk_index: key += (chunk_index[dim],) else: # unchunked dimensions in the input have one chunk in the result # output can have new dimensions with exactly one chunk key += (0,) # We're adding multiple new layers to the graph: # The first new layer is the result of the computation on # the array. # Then we add one layer per variable, which extracts the # result for that variable, and depends on just the first new # layer. new_layers[gname_l][key] = (operator.getitem, from_wrapper, name) hlg = HighLevelGraph.from_collections( gname, graph, dependencies=[arg for arg in npargs if dask.is_dask_collection(arg)], ) # This adds in the getitems for each variable in the dataset. hlg = HighLevelGraph( {**hlg.layers, **new_layers}, dependencies={ **hlg.dependencies, **{name: {gname} for name in new_layers.keys()}, }, ) result = Dataset(coords=indexes, attrs=template.attrs) for index in result.xindexes: result[index].attrs = template[index].attrs result[index].encoding = template[index].encoding for name, gname_l in var_key_map.items(): dims = template[name].dims var_chunks = [] for dim in dims: if dim in output_chunks: var_chunks.append(output_chunks[dim]) elif dim in indexes: var_chunks.append((len(indexes[dim]),)) elif dim in template.dims: # new unindexed dimension var_chunks.append((template.sizes[dim],)) data = dask.array.Array( hlg, name=gname_l, chunks=var_chunks, dtype=template[name].dtype ) result[name] = (dims, data, template[name].attrs) result[name].encoding = template[name].encoding result = result.set_coords(template._coord_names) if result_is_array: da = dataset_to_dataarray(result) da.name = template_name return da # type: ignore[return-value] return result # type: ignore[return-value]
try: import dask import dask.array from dask.array.utils import meta_from_array from dask.highlevelgraph import HighLevelGraph except ImportError: pass import collections import itertools import operator from typing import ( Any, Callable, DefaultDict, Dict, Hashable, Iterable, List, Mapping, Sequence, Tuple, TypeVar, Union, ) import numpy as np from xarray.core.indexes import PandasIndex from .alignment import align from .dataarray import DataArray from .dataset import Dataset T_DSorDA = TypeVar("T_DSorDA", DataArray, Dataset) def unzip(iterable): return zip(*iterable) def assert_chunks_compatible(a: Dataset, b: Dataset): a = a.unify_chunks() b = b.unify_chunks() for dim in set(a.chunks).intersection(set(b.chunks)): if a.chunks[dim] != b.chunks[dim]: raise ValueError(f"Chunk sizes along dimension {dim!r} are not equal.") def check_result_variables( result: Union[DataArray, Dataset], expected: Mapping[str, Any], kind: str ): if kind == "coords": nice_str = "coordinate" elif kind == "data_vars": nice_str = "data" # check that coords and data variables are as expected missing = expected[kind] - set(getattr(result, kind)) if missing: raise ValueError( "Result from applying user function does not contain " f"{nice_str} variables {missing}." ) extra = set(getattr(result, kind)) - expected[kind] if extra: raise ValueError( "Result from applying user function has unexpected " f"{nice_str} variables {extra}." ) def dataset_to_dataarray(obj: Dataset) -> DataArray: if not isinstance(obj, Dataset): raise TypeError(f"Expected Dataset, got {type(obj)}") if len(obj.data_vars) > 1: raise TypeError( "Trying to convert Dataset with more than one data variable to DataArray" ) return next(iter(obj.data_vars.values())) def dataarray_to_dataset(obj: DataArray) -> Dataset: # only using _to_temp_dataset would break # func = lambda x: x.to_dataset() # since that relies on preserving name. if obj.name is None: dataset = obj._to_temp_dataset() else: dataset = obj.to_dataset() return dataset def make_meta(obj): """If obj is a DataArray or Dataset, return a new object of the same type and with the same variables and dtypes, but where all variables have size 0 and numpy backend. If obj is neither a DataArray nor Dataset, return it unaltered. """ if isinstance(obj, DataArray): obj_array = obj obj = dataarray_to_dataset(obj) elif isinstance(obj, Dataset): obj_array = None else: return obj meta = Dataset() for name, variable in obj.variables.items(): meta_obj = meta_from_array(variable.data, ndim=variable.ndim) meta[name] = (variable.dims, meta_obj, variable.attrs) meta.attrs = obj.attrs meta = meta.set_coords(obj.coords) if obj_array is not None: return dataset_to_dataarray(meta) return meta def infer_template( func: Callable[..., T_DSorDA], obj: Union[DataArray, Dataset], *args, **kwargs ) -> T_DSorDA: """Infer return object by running the function on meta objects.""" meta_args = [make_meta(arg) for arg in (obj,) + args] try: template = func(*meta_args, **kwargs) except Exception as e: raise Exception( "Cannot infer object returned from running user provided function. " "Please supply the 'template' kwarg to map_blocks." ) from e if not isinstance(template, (Dataset, DataArray)): raise TypeError( "Function must return an xarray DataArray or Dataset. Instead it returned " f"{type(template)}" ) return template def make_dict(x: Union[DataArray, Dataset]) -> Dict[Hashable, Any]: """Map variable name to numpy(-like) data (Dataset.to_dict() is too complicated). """ if isinstance(x, DataArray): x = x._to_temp_dataset() return {k: v.data for k, v in x.variables.items()} def _get_chunk_slicer(dim: Hashable, chunk_index: Mapping, chunk_bounds: Mapping): if dim in chunk_index: which_chunk = chunk_index[dim] return slice(chunk_bounds[dim][which_chunk], chunk_bounds[dim][which_chunk + 1]) return slice(None) def map_blocks( func: Callable[..., T_DSorDA], obj: Union[DataArray, Dataset], args: Sequence[Any] = (), kwargs: Mapping[str, Any] = None, template: Union[DataArray, Dataset] = None, ) -> T_DSorDA: """Apply a function to each block of a DataArray or Dataset. .. warning:: This function is experimental and its signature may change. Parameters ---------- func : callable User-provided function that accepts a DataArray or Dataset as its first parameter ``obj``. The function will receive a subset or 'block' of ``obj`` (see below), corresponding to one chunk along each chunked dimension. ``func`` will be executed as ``func(subset_obj, *subset_args, **kwargs)``. This function must return either a single DataArray or a single Dataset. This function cannot add a new chunked dimension. obj : DataArray, Dataset Passed to the function as its first argument, one block at a time. args : sequence Passed to func after unpacking and subsetting any xarray objects by blocks. xarray objects in args must be aligned with obj, otherwise an error is raised. kwargs : mapping Passed verbatim to func after unpacking. xarray objects, if any, will not be subset to blocks. Passing dask collections in kwargs is not allowed. template : DataArray or Dataset, optional xarray object representing the final result after compute is called. If not provided, the function will be first run on mocked-up data, that looks like ``obj`` but has sizes 0, to determine properties of the returned object such as dtype, variable names, attributes, new dimensions and new indexes (if any). ``template`` must be provided if the function changes the size of existing dimensions. When provided, ``attrs`` on variables in `template` are copied over to the result. Any ``attrs`` set by ``func`` will be ignored. Returns ------- A single DataArray or Dataset with dask backend, reassembled from the outputs of the function. Notes ----- This function is designed for when ``func`` needs to manipulate a whole xarray object subset to each block. Each block is loaded into memory. In the more common case where ``func`` can work on numpy arrays, it is recommended to use ``apply_ufunc``. If none of the variables in ``obj`` is backed by dask arrays, calling this function is equivalent to calling ``func(obj, *args, **kwargs)``. See Also -------- dask.array.map_blocks, xarray.apply_ufunc, xarray.Dataset.map_blocks xarray.DataArray.map_blocks Examples -------- Calculate an anomaly from climatology using ``.groupby()``. Using ``xr.map_blocks()`` allows for parallel operations with knowledge of ``xarray``, its indices, and its methods like ``.groupby()``. >>> def calculate_anomaly(da, groupby_type="time.month"): ... gb = da.groupby(groupby_type) ... clim = gb.mean(dim="time") ... return gb - clim ... >>> time = xr.cftime_range("1990-01", "1992-01", freq="M") >>> month = xr.DataArray(time.month, coords={"time": time}, dims=["time"]) >>> np.random.seed(123) >>> array = xr.DataArray( ... np.random.rand(len(time)), ... dims=["time"], ... coords={"time": time, "month": month}, ... ).chunk() >>> array.map_blocks(calculate_anomaly, template=array).compute() <xarray.DataArray (time: 24)> array([ 0.12894847, 0.11323072, -0.0855964 , -0.09334032, 0.26848862, 0.12382735, 0.22460641, 0.07650108, -0.07673453, -0.22865714, -0.19063865, 0.0590131 , -0.12894847, -0.11323072, 0.0855964 , 0.09334032, -0.26848862, -0.12382735, -0.22460641, -0.07650108, 0.07673453, 0.22865714, 0.19063865, -0.0590131 ]) Coordinates: * time (time) object 1990-01-31 00:00:00 ... 1991-12-31 00:00:00 month (time) int64 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12 Note that one must explicitly use ``args=[]`` and ``kwargs={}`` to pass arguments to the function being applied in ``xr.map_blocks()``: >>> array.map_blocks( ... calculate_anomaly, ... kwargs={"groupby_type": "time.year"}, ... template=array, ... ) # doctest: +ELLIPSIS <xarray.DataArray (time: 24)> dask.array<<this-array>-calculate_anomaly, shape=(24,), dtype=float64, chunksize=(24,), chunktype=numpy.ndarray> Coordinates: * time (time) object 1990-01-31 00:00:00 ... 1991-12-31 00:00:00 month (time) int64 dask.array<chunksize=(24,), meta=np.ndarray> """ def _wrapper( func: Callable, args: List, kwargs: dict, arg_is_array: Iterable[bool], expected: dict, ): """ Wrapper function that receives datasets in args; converts to dataarrays when necessary; passes these to the user function `func` and checks returned objects for expected shapes/sizes/etc. """ converted_args = [ dataset_to_dataarray(arg) if is_array else arg for is_array, arg in zip(arg_is_array, args) ] result = func(*converted_args, **kwargs) # check all dims are present missing_dimensions = set(expected["shapes"]) - set(result.sizes) if missing_dimensions: raise ValueError( f"Dimensions {missing_dimensions} missing on returned object." ) # check that index lengths and values are as expected for name, index in result.xindexes.items(): if name in expected["shapes"]: if len(index) != expected["shapes"][name]: raise ValueError( f"Received dimension {name!r} of length {len(index)}. Expected length {expected['shapes'][name]}." ) if name in expected["indexes"]: expected_index = expected["indexes"][name] if not index.equals(expected_index): raise ValueError( f"Expected index {name!r} to be {expected_index!r}. Received {index!r} instead." ) # check that all expected variables were returned check_result_variables(result, expected, "coords") if isinstance(result, Dataset): check_result_variables(result, expected, "data_vars") return make_dict(result) if template is not None and not isinstance(template, (DataArray, Dataset)): raise TypeError( f"template must be a DataArray or Dataset. Received {type(template).__name__} instead." ) if not isinstance(args, Sequence): raise TypeError("args must be a sequence (for example, a list or tuple).") if kwargs is None: kwargs = {} elif not isinstance(kwargs, Mapping): raise TypeError("kwargs must be a mapping (for example, a dict)") for value in kwargs.values(): if dask.is_dask_collection(value): raise TypeError( "Cannot pass dask collections in kwargs yet. Please compute or " "load values before passing to map_blocks." ) if not dask.is_dask_collection(obj): return func(obj, *args, **kwargs) all_args = [obj] + list(args) is_xarray = [isinstance(arg, (Dataset, DataArray)) for arg in all_args] is_array = [isinstance(arg, DataArray) for arg in all_args] # there should be a better way to group this. partition? xarray_indices, xarray_objs = unzip( (index, arg) for index, arg in enumerate(all_args) if is_xarray[index] ) others = [ (index, arg) for index, arg in enumerate(all_args) if not is_xarray[index] ] # all xarray objects must be aligned. This is consistent with apply_ufunc. aligned = align(*xarray_objs, join="exact") xarray_objs = tuple( dataarray_to_dataset(arg) if is_da else arg for is_da, arg in zip(is_array, aligned) ) _, npargs = unzip( sorted(list(zip(xarray_indices, xarray_objs)) + others, key=lambda x: x[0]) ) # check that chunk sizes are compatible input_chunks = dict(npargs[0].chunks) input_indexes = dict(npargs[0].xindexes) for arg in xarray_objs[1:]: assert_chunks_compatible(npargs[0], arg) input_chunks.update(arg.chunks) input_indexes.update(arg.xindexes) if template is None: # infer template by providing zero-shaped arrays template = infer_template(func, aligned[0], *args, **kwargs) template_indexes = set(template.xindexes) preserved_indexes = template_indexes & set(input_indexes) new_indexes = template_indexes - set(input_indexes) indexes = {dim: input_indexes[dim] for dim in preserved_indexes} indexes.update({k: template.xindexes[k] for k in new_indexes}) output_chunks = { dim: input_chunks[dim] for dim in template.dims if dim in input_chunks } else: # template xarray object has been provided with proper sizes and chunk shapes indexes = dict(template.xindexes) if isinstance(template, DataArray): output_chunks = dict( zip(template.dims, template.chunks) # type: ignore[arg-type] ) else: output_chunks = dict(template.chunks) for dim in output_chunks: if dim in input_chunks and len(input_chunks[dim]) != len(output_chunks[dim]): raise ValueError( "map_blocks requires that one block of the input maps to one block of output. " f"Expected number of output chunks along dimension {dim!r} to be {len(input_chunks[dim])}. " f"Received {len(output_chunks[dim])} instead. Please provide template if not provided, or " "fix the provided template." ) if isinstance(template, DataArray): result_is_array = True template_name = template.name template = template._to_temp_dataset() elif isinstance(template, Dataset): result_is_array = False else: raise TypeError( f"func output must be DataArray or Dataset; got {type(template)}" ) # We're building a new HighLevelGraph hlg. We'll have one new layer # for each variable in the dataset, which is the result of the # func applied to the values. graph: Dict[Any, Any] = {} new_layers: DefaultDict[str, Dict[Any, Any]] = collections.defaultdict(dict) gname = "{}-{}".format( dask.utils.funcname(func), dask.base.tokenize(npargs[0], args, kwargs) ) # map dims to list of chunk indexes ichunk = {dim: range(len(chunks_v)) for dim, chunks_v in input_chunks.items()} # mapping from chunk index to slice bounds input_chunk_bounds = { dim: np.cumsum((0,) + chunks_v) for dim, chunks_v in input_chunks.items() } output_chunk_bounds = { dim: np.cumsum((0,) + chunks_v) for dim, chunks_v in output_chunks.items() } def subset_dataset_to_block( graph: dict, gname: str, dataset: Dataset, input_chunk_bounds, chunk_index ): """ Creates a task that subsets an xarray dataset to a block determined by chunk_index. Block extents are determined by input_chunk_bounds. Also subtasks that subset the constituent variables of a dataset. """ # this will become [[name1, variable1], # [name2, variable2], # ...] # which is passed to dict and then to Dataset data_vars = [] coords = [] chunk_tuple = tuple(chunk_index.values()) for name, variable in dataset.variables.items(): # make a task that creates tuple of (dims, chunk) if dask.is_dask_collection(variable.data): # recursively index into dask_keys nested list to get chunk chunk = variable.__dask_keys__() for dim in variable.dims: chunk = chunk[chunk_index[dim]] chunk_variable_task = (f"{name}-{gname}-{chunk[0]}",) + chunk_tuple graph[chunk_variable_task] = ( tuple, [variable.dims, chunk, variable.attrs], ) else: # non-dask array possibly with dimensions chunked on other variables # index into variable appropriately subsetter = { dim: _get_chunk_slicer(dim, chunk_index, input_chunk_bounds) for dim in variable.dims } subset = variable.isel(subsetter) chunk_variable_task = ( f"{name}-{gname}-{dask.base.tokenize(subset)}", ) + chunk_tuple graph[chunk_variable_task] = ( tuple, [subset.dims, subset, subset.attrs], ) # this task creates dict mapping variable name to above tuple if name in dataset._coord_names: coords.append([name, chunk_variable_task]) else: data_vars.append([name, chunk_variable_task]) return (Dataset, (dict, data_vars), (dict, coords), dataset.attrs) # iterate over all possible chunk combinations for chunk_tuple in itertools.product(*ichunk.values()): # mapping from dimension name to chunk index chunk_index = dict(zip(ichunk.keys(), chunk_tuple)) blocked_args = [ subset_dataset_to_block(graph, gname, arg, input_chunk_bounds, chunk_index) if isxr else arg for isxr, arg in zip(is_xarray, npargs) ] # expected["shapes", "coords", "data_vars", "indexes"] are used to # raise nice error messages in _wrapper expected = {} # input chunk 0 along a dimension maps to output chunk 0 along the same dimension # even if length of dimension is changed by the applied function expected["shapes"] = { k: output_chunks[k][v] for k, v in chunk_index.items() if k in output_chunks } expected["data_vars"] = set(template.data_vars.keys()) # type: ignore[assignment] expected["coords"] = set(template.coords.keys()) # type: ignore[assignment] # TODO: benbovy - flexible indexes: clean this up # for now assumes pandas index (thus can be indexed) but it won't be the case for # all indexes expected_indexes = {} for dim in indexes: idx = indexes[dim].to_pandas_index()[ _get_chunk_slicer(dim, chunk_index, output_chunk_bounds) ] expected_indexes[dim] = PandasIndex(idx) expected["indexes"] = expected_indexes from_wrapper = (gname,) + chunk_tuple graph[from_wrapper] = (_wrapper, func, blocked_args, kwargs, is_array, expected) # mapping from variable name to dask graph key var_key_map: Dict[Hashable, str] = {} for name, variable in template.variables.items(): if name in indexes: continue gname_l = f"{name}-{gname}" var_key_map[name] = gname_l key: Tuple[Any, ...] = (gname_l,) for dim in variable.dims: if dim in chunk_index: key += (chunk_index[dim],) else: # unchunked dimensions in the input have one chunk in the result # output can have new dimensions with exactly one chunk key += (0,) # We're adding multiple new layers to the graph: # The first new layer is the result of the computation on # the array. # Then we add one layer per variable, which extracts the # result for that variable, and depends on just the first new # layer. new_layers[gname_l][key] = (operator.getitem, from_wrapper, name) hlg = HighLevelGraph.from_collections( gname, graph, dependencies=[arg for arg in npargs if dask.is_dask_collection(arg)], ) # This adds in the getitems for each variable in the dataset. hlg = HighLevelGraph( {**hlg.layers, **new_layers}, dependencies={ **hlg.dependencies, **{name: {gname} for name in new_layers.keys()}, }, ) result = Dataset(coords=indexes, attrs=template.attrs) for index in result.xindexes: result[index].attrs = template[index].attrs result[index].encoding = template[index].encoding for name, gname_l in var_key_map.items(): dims = template[name].dims var_chunks = [] for dim in dims: if dim in output_chunks: var_chunks.append(output_chunks[dim]) elif dim in indexes: var_chunks.append((len(indexes[dim]),)) elif dim in template.dims: # new unindexed dimension var_chunks.append((template.sizes[dim],)) data = dask.array.Array( hlg, name=gname_l, chunks=var_chunks, dtype=template[name].dtype ) result[name] = (dims, data, template[name].attrs) result[name].encoding = template[name].encoding result = result.set_coords(template._coord_names) if result_is_array: da = dataset_to_dataarray(result) da.name = template_name return da # type: ignore[return-value] return result # type: ignore[return-value]
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import copy import logging import string import sys import warnings from argparse import ArgumentParser from collections import defaultdict from typing import Any, Callable, DefaultDict, List, Optional, Sequence, Type, Union from omegaconf import Container, DictConfig, OmegaConf, open_dict from hydra._internal.utils import get_column_widths, run_and_report from hydra.core.config_loader import ConfigLoader from hydra.core.config_search_path import ConfigSearchPath from hydra.core.hydra_config import HydraConfig from hydra.core.plugins import Plugins from hydra.core.utils import ( JobReturn, JobRuntime, configure_log, run_job, setup_globals, simple_stdout_log_config, ) from hydra.plugins.completion_plugin import CompletionPlugin from hydra.plugins.config_source import ConfigSource from hydra.plugins.launcher import Launcher from hydra.plugins.search_path_plugin import SearchPathPlugin from hydra.plugins.sweeper import Sweeper from hydra.types import RunMode, TaskFunction from ..core.default_element import DefaultsTreeNode, InputDefault from .config_loader_impl import ConfigLoaderImpl from .utils import create_automatic_config_search_path log: Optional[logging.Logger] = None class Hydra: @classmethod def create_main_hydra_file_or_module( cls: Type["Hydra"], calling_file: Optional[str], calling_module: Optional[str], config_path: Optional[str], job_name: str, strict: Optional[bool], ) -> "Hydra": config_search_path = create_automatic_config_search_path( calling_file, calling_module, config_path ) return Hydra.create_main_hydra2(job_name, config_search_path, strict) @classmethod def create_main_hydra2( cls, task_name: str, config_search_path: ConfigSearchPath, strict: Optional[bool], ) -> "Hydra": if strict is None: strict = True else: # DEPRECATED: remove in 1.1 msg = ( "\n@hydra.main(strict) flag is deprecated and will removed in the next version." "\nSee https://hydra.cc/docs/next/upgrades/0.11_to_1.0/strict_mode_flag_deprecated" ) warnings.warn(message=msg, category=UserWarning) config_loader: ConfigLoader = ConfigLoaderImpl( config_search_path=config_search_path, default_strict=strict ) hydra = cls(task_name=task_name, config_loader=config_loader) from hydra.core.global_hydra import GlobalHydra GlobalHydra.instance().initialize(hydra) return hydra def __init__(self, task_name: str, config_loader: ConfigLoader) -> None: """ :param task_name: task name :param config_loader: config loader """ setup_globals() self.config_loader = config_loader JobRuntime().set("name", task_name) def run( self, config_name: Optional[str], task_function: TaskFunction, overrides: List[str], with_log_configuration: bool = True, ) -> JobReturn: cfg = self.compose_config( config_name=config_name, overrides=overrides, with_log_configuration=with_log_configuration, run_mode=RunMode.RUN, ) HydraConfig.instance().set_config(cfg) return run_job( config=cfg, task_function=task_function, job_dir_key="hydra.run.dir", job_subdir_key=None, configure_logging=with_log_configuration, ) def multirun( self, config_name: Optional[str], task_function: TaskFunction, overrides: List[str], with_log_configuration: bool = True, ) -> Any: # Initial config is loaded without strict (individual job configs may have strict). cfg = self.compose_config( config_name=config_name, overrides=overrides, strict=False, with_log_configuration=with_log_configuration, run_mode=RunMode.MULTIRUN, ) HydraConfig.instance().set_config(cfg) sweeper = Plugins.instance().instantiate_sweeper( config=cfg, config_loader=self.config_loader, task_function=task_function ) task_overrides = OmegaConf.to_container(cfg.hydra.overrides.task, resolve=False) assert isinstance(task_overrides, list) return sweeper.sweep(arguments=task_overrides) @staticmethod def get_sanitized_hydra_cfg(src_cfg: DictConfig) -> DictConfig: cfg = copy.deepcopy(src_cfg) with open_dict(cfg): for key in list(cfg.keys()): if key != "hydra": del cfg[key] with open_dict(cfg.hydra): del cfg.hydra["hydra_help"] del cfg.hydra["help"] return cfg def _get_cfg( self, config_name: Optional[str], overrides: List[str], cfg_type: str, with_log_configuration: bool, ) -> DictConfig: assert cfg_type in ["job", "hydra", "all"] cfg = self.compose_config( config_name=config_name, overrides=overrides, run_mode=RunMode.RUN, with_log_configuration=with_log_configuration, ) if cfg_type == "job": with open_dict(cfg): del cfg["hydra"] elif cfg_type == "hydra": cfg = self.get_sanitized_hydra_cfg(cfg) return cfg def show_cfg( self, config_name: Optional[str], overrides: List[str], cfg_type: str, package: Optional[str], ) -> None: cfg = self._get_cfg( config_name=config_name, overrides=overrides, cfg_type=cfg_type, with_log_configuration=False, ) if package == "_global_": package = None if package is not None: ret = OmegaConf.select(cfg, package) if ret is None: sys.stderr.write(f"package '{package}' not found in config\n") sys.exit(1) else: if isinstance(ret, Container): print(f"# @package {package}") sys.stdout.write(OmegaConf.to_yaml(ret)) else: print(ret) else: sys.stdout.write(OmegaConf.to_yaml(cfg)) @staticmethod def get_shell_to_plugin_map( config_loader: ConfigLoader, ) -> DefaultDict[str, List[CompletionPlugin]]: shell_to_plugin: DefaultDict[str, List[CompletionPlugin]] = defaultdict(list) for clazz in Plugins.instance().discover(CompletionPlugin): assert issubclass(clazz, CompletionPlugin) plugin = clazz(config_loader) shell_to_plugin[plugin.provides()].append(plugin) for shell, plugins in shell_to_plugin.items(): if len(plugins) > 1: lst = ",".join([type(plugin).__name__ for plugin in plugins]) raise ValueError(f"Multiple plugins installed for {shell} : {lst}") return shell_to_plugin def shell_completion( self, config_name: Optional[str], overrides: List[str] ) -> None: subcommands = ["install", "uninstall", "query"] arguments = OmegaConf.from_dotlist(overrides) num_commands = sum(1 for key in subcommands if arguments[key] is not None) if num_commands != 1: raise ValueError(f"Expecting one subcommand from {subcommands} to be set") shell_to_plugin = self.get_shell_to_plugin_map(self.config_loader) def find_plugin(cmd: str) -> CompletionPlugin: if cmd not in shell_to_plugin: lst = "\n".join(["\t" + x for x in shell_to_plugin.keys()]) raise ValueError( f"No completion plugin for '{cmd}' found, available : \n{lst}" ) return shell_to_plugin[cmd][0] if arguments.install is not None: plugin = find_plugin(arguments.install) plugin.install() elif arguments.uninstall is not None: plugin = find_plugin(arguments.uninstall) plugin.uninstall() elif arguments.query is not None: plugin = find_plugin(arguments.query) plugin.query(config_name=config_name) @staticmethod def format_args_help(args_parser: ArgumentParser) -> str: s = "" overrides: Any = None for action in args_parser._actions: if len(action.option_strings) == 0: overrides = action else: s += f"{",".join(action.option_strings)} : {action.help}\n" s += "Overrides : " + overrides.help return s def list_all_config_groups(self, parent: str = "") -> Sequence[str]: from hydra.core.object_type import ObjectType groups: List[str] = [] for group in self.config_loader.list_groups(parent): if parent == "": group_name = group else: group_name = "{}/{}".format(parent, group) files = self.config_loader.get_group_options(group_name, ObjectType.CONFIG) dirs = self.config_loader.get_group_options(group_name, ObjectType.GROUP) if len(files) > 0: groups.append(group_name) if len(dirs) > 0: groups.extend(self.list_all_config_groups(group_name)) return groups def format_config_groups( self, predicate: Callable[[str], bool], compact: bool = True ) -> str: groups = [x for x in self.list_all_config_groups() if predicate(x)] s = "" for group in sorted(groups): options = sorted(self.config_loader.get_group_options(group)) if compact: items = ", ".join(options) line = "{}: {}".format(group, items) else: items = "\n".join([" " + o for o in options]) line = "{}:\n{}".format(group, items) s += line + "\n" return s def get_help( self, help_cfg: DictConfig, cfg: DictConfig, args_parser: ArgumentParser ) -> str: s = string.Template(help_cfg.template) def is_hydra_group(x: str) -> bool: return x.startswith("hydra/") or x == "hydra" def is_not_hydra_group(x: str) -> bool: return not is_hydra_group(x) help_text = s.substitute( FLAGS_HELP=self.format_args_help(args_parser), HYDRA_CONFIG_GROUPS=self.format_config_groups(is_hydra_group), APP_CONFIG_GROUPS=self.format_config_groups(is_not_hydra_group), CONFIG=OmegaConf.to_yaml(cfg, resolve=False), ) return help_text def hydra_help( self, config_name: Optional[str], args_parser: ArgumentParser, args: Any ) -> None: cfg = self.compose_config( config_name=None, overrides=args.overrides, run_mode=RunMode.RUN, with_log_configuration=True, ) help_cfg = cfg.hydra.hydra_help cfg = self.get_sanitized_hydra_cfg(cfg) help_text = self.get_help(help_cfg, cfg, args_parser) print(help_text) def app_help( self, config_name: Optional[str], args_parser: ArgumentParser, args: Any ) -> None: cfg = self.compose_config( config_name=config_name, overrides=args.overrides, run_mode=RunMode.RUN, with_log_configuration=True, ) help_cfg = cfg.hydra.help clean_cfg = copy.deepcopy(cfg) with open_dict(clean_cfg): del clean_cfg["hydra"] help_text = self.get_help(help_cfg, clean_cfg, args_parser) print(help_text) @staticmethod def _log_header(header: str, prefix: str = "", filler: str = "-") -> None: assert log is not None log.debug(prefix + header) log.debug(prefix + "".ljust(len(header), filler)) @staticmethod def _log_footer(header: str, prefix: str = "", filler: str = "-") -> None: assert log is not None log.debug(prefix + "".ljust(len(header), filler)) def _print_plugins(self) -> None: assert log is not None self._log_header(header="Installed Hydra Plugins", filler="*") all_plugins = {p.__name__ for p in Plugins.instance().discover()} for plugin_type in [ ConfigSource, CompletionPlugin, Launcher, Sweeper, SearchPathPlugin, ]: # Mypy false positive? plugins = Plugins.instance().discover(plugin_type) # type: ignore if len(plugins) > 0: Hydra._log_header(header=f"{plugin_type.__name__}:", prefix="\t") for plugin in plugins: log.debug("\t\t{}".format(plugin.__name__)) if plugin.__name__ in all_plugins: all_plugins.remove(plugin.__name__) if len(all_plugins) > 0: Hydra._log_header(header="Generic plugins: ", prefix="\t") for plugin_name in all_plugins: log.debug("\t\t{}".format(plugin_name)) def _print_search_path(self) -> None: assert log is not None log.debug("") self._log_header(header="Config search path", filler="*") box: List[List[str]] = [["Provider", "Search path"]] for sp in self.config_loader.get_sources(): box.append([sp.provider, sp.full_path()]) provider_pad, search_path_pad = get_column_widths(box) header = "| {} | {} |".format( "Provider".ljust(provider_pad), "Search path".ljust(search_path_pad) ) self._log_header(header=header, filler="-") for source in self.config_loader.get_sources(): log.debug( "| {} | {} |".format( source.provider.ljust(provider_pad), source.full_path().ljust(search_path_pad), ) ) self._log_footer(header=header, filler="-") def _print_plugins_profiling_info(self, top_n: int) -> None: assert log is not None stats = Plugins.instance().get_stats() if stats is None: return items = list(stats.modules_import_time.items()) # hide anything that took less than 5ms filtered = filter(lambda x: x[1] > 0.0005, items) sorted_items = sorted(filtered, key=lambda x: x[1], reverse=True) top_n = max(len(sorted_items), top_n) box: List[List[str]] = [["Module", "Sec"]] for item in sorted_items[0:top_n]: box.append([item[0], f"{item[1]:.3f}"]) padding = get_column_widths(box) log.debug("") self._log_header(header="Profiling information", filler="*") self._log_header( header=f"Total plugins scan time : {stats.total_time:.3f} seconds", filler="-", ) header = f"| {box[0][0].ljust(padding[0])} | {box[0][1].ljust(padding[1])} |" self._log_header(header=header, filler="-") del box[0] for row in box: a = row[0].ljust(padding[0]) b = row[1].ljust(padding[1]) log.debug(f"| {a} | {b} |") self._log_footer(header=header, filler="-") def _print_config_info( self, config_name: Optional[str], overrides: List[str] ) -> None: assert log is not None self._print_search_path() self._print_defaults_tree(config_name=config_name, overrides=overrides) self._print_defaults_list(config_name=config_name, overrides=overrides) cfg = run_and_report( lambda: self._get_cfg( config_name=config_name, overrides=overrides, cfg_type="all", with_log_configuration=False, ) ) self._log_header(header="Config", filler="*") with open_dict(cfg): del cfg["hydra"] log.info(OmegaConf.to_yaml(cfg)) def _print_defaults_list( self, config_name: Optional[str], overrides: List[str] ) -> None: assert log is not None defaults = self.config_loader.compute_defaults_list( config_name=config_name, overrides=overrides, run_mode=RunMode.RUN, ) box: List[List[str]] = [ [ "Config path", "Package", "_self_", "Parent", ] ] for d in defaults.defaults: row = [ d.config_path, d.package, "True" if d.is_self else "False", d.parent, ] row = [x if x is not None else "" for x in row] box.append(row) padding = get_column_widths(box) del box[0] log.debug("") self._log_header("Defaults List", filler="*") header = "| {} | {} | {} | {} | ".format( "Config path".ljust(padding[0]), "Package".ljust(padding[1]), "_self_".ljust(padding[2]), "Parent".ljust(padding[3]), ) self._log_header(header=header, filler="-") for row in box: log.debug( "| {} | {} | {} | {} |".format( row[0].ljust(padding[0]), row[1].ljust(padding[1]), row[2].ljust(padding[2]), row[3].ljust(padding[3]), ) ) self._log_footer(header=header, filler="-") def _print_debug_info( self, config_name: Optional[str], overrides: List[str], ) -> None: assert log is not None if log.isEnabledFor(logging.DEBUG): self._print_all_info(config_name, overrides) def compose_config( self, config_name: Optional[str], overrides: List[str], run_mode: RunMode, strict: Optional[bool] = None, with_log_configuration: bool = False, from_shell: bool = True, ) -> DictConfig: """ :param config_name: :param overrides: :param run_mode: compose config for run or for multirun? :param with_log_configuration: True to configure logging subsystem from the loaded config :param strict: None for default behavior (default to true for config file, false if no config file). otherwise forces specific behavior. :param from_shell: True if the parameters are passed from the shell. used for more helpful error messages :return: """ cfg = self.config_loader.load_configuration( config_name=config_name, overrides=overrides, strict=strict, run_mode=run_mode, from_shell=from_shell, ) if with_log_configuration: configure_log(cfg.hydra.hydra_logging, cfg.hydra.verbose) global log log = logging.getLogger(__name__) self._print_debug_info(config_name, overrides) return cfg def _print_plugins_info( self, config_name: Optional[str], overrides: List[str] ) -> None: self._print_plugins() self._print_plugins_profiling_info(top_n=10) def _print_all_info(self, config_name: Optional[str], overrides: List[str]) -> None: from .. import __version__ self._log_header(f"Hydra {__version__}", filler="=") self._print_plugins() self._print_config_info(config_name, overrides) def _print_defaults_tree_impl( self, tree: Union[DefaultsTreeNode, InputDefault], indent: int = 0, ) -> None: assert log is not None from ..core.default_element import GroupDefault, InputDefault, VirtualRoot def to_str(node: InputDefault) -> str: if isinstance(node, VirtualRoot): return node.get_config_path() elif isinstance(node, GroupDefault): name = node.get_name() if name is None: name = "null" return node.get_override_key() + ": " + name else: return node.get_config_path() pad = " " * indent if isinstance(tree, DefaultsTreeNode): node_str = to_str(tree.node) if tree.children is not None and len(tree.children) > 0: log.info(pad + node_str + ":") for child in tree.children: self._print_defaults_tree_impl(tree=child, indent=indent + 1) else: log.info(pad + node_str) else: assert isinstance(tree, InputDefault) log.info(pad + to_str(tree)) def _print_defaults_tree( self, config_name: Optional[str], overrides: List[str] ) -> None: assert log is not None defaults = self.config_loader.compute_defaults_list( config_name=config_name, overrides=overrides, run_mode=RunMode.RUN, ) log.info("") self._log_header("Defaults Tree", filler="*") self._print_defaults_tree_impl(defaults.defaults_tree) def show_info( self, info: str, config_name: Optional[str], overrides: List[str] ) -> None: options = { "all": self._print_all_info, "defaults": self._print_defaults_list, "defaults-tree": self._print_defaults_tree, "config": self._print_config_info, "plugins": self._print_plugins_info, } simple_stdout_log_config(level=logging.DEBUG) global log log = logging.getLogger(__name__) if info not in options: opts = sorted(options.keys()) log.error(f"Info usage: --info [{"|".join(opts)}]") else: options[info](config_name=config_name, overrides=overrides)
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import copy import logging import string import sys import warnings from argparse import ArgumentParser from collections import defaultdict from typing import Any, Callable, DefaultDict, List, Optional, Sequence, Type, Union from omegaconf import Container, DictConfig, OmegaConf, open_dict from hydra._internal.utils import get_column_widths, run_and_report from hydra.core.config_loader import ConfigLoader from hydra.core.config_search_path import ConfigSearchPath from hydra.core.hydra_config import HydraConfig from hydra.core.plugins import Plugins from hydra.core.utils import ( JobReturn, JobRuntime, configure_log, run_job, setup_globals, simple_stdout_log_config, ) from hydra.plugins.completion_plugin import CompletionPlugin from hydra.plugins.config_source import ConfigSource from hydra.plugins.launcher import Launcher from hydra.plugins.search_path_plugin import SearchPathPlugin from hydra.plugins.sweeper import Sweeper from hydra.types import RunMode, TaskFunction from ..core.default_element import DefaultsTreeNode, InputDefault from .config_loader_impl import ConfigLoaderImpl from .utils import create_automatic_config_search_path log: Optional[logging.Logger] = None class Hydra: @classmethod def create_main_hydra_file_or_module( cls: Type["Hydra"], calling_file: Optional[str], calling_module: Optional[str], config_path: Optional[str], job_name: str, strict: Optional[bool], ) -> "Hydra": config_search_path = create_automatic_config_search_path( calling_file, calling_module, config_path ) return Hydra.create_main_hydra2(job_name, config_search_path, strict) @classmethod def create_main_hydra2( cls, task_name: str, config_search_path: ConfigSearchPath, strict: Optional[bool], ) -> "Hydra": if strict is None: strict = True else: # DEPRECATED: remove in 1.1 msg = ( "\n@hydra.main(strict) flag is deprecated and will removed in the next version." "\nSee https://hydra.cc/docs/next/upgrades/0.11_to_1.0/strict_mode_flag_deprecated" ) warnings.warn(message=msg, category=UserWarning) config_loader: ConfigLoader = ConfigLoaderImpl( config_search_path=config_search_path, default_strict=strict ) hydra = cls(task_name=task_name, config_loader=config_loader) from hydra.core.global_hydra import GlobalHydra GlobalHydra.instance().initialize(hydra) return hydra def __init__(self, task_name: str, config_loader: ConfigLoader) -> None: """ :param task_name: task name :param config_loader: config loader """ setup_globals() self.config_loader = config_loader JobRuntime().set("name", task_name) def run( self, config_name: Optional[str], task_function: TaskFunction, overrides: List[str], with_log_configuration: bool = True, ) -> JobReturn: cfg = self.compose_config( config_name=config_name, overrides=overrides, with_log_configuration=with_log_configuration, run_mode=RunMode.RUN, ) HydraConfig.instance().set_config(cfg) return run_job( config=cfg, task_function=task_function, job_dir_key="hydra.run.dir", job_subdir_key=None, configure_logging=with_log_configuration, ) def multirun( self, config_name: Optional[str], task_function: TaskFunction, overrides: List[str], with_log_configuration: bool = True, ) -> Any: # Initial config is loaded without strict (individual job configs may have strict). cfg = self.compose_config( config_name=config_name, overrides=overrides, strict=False, with_log_configuration=with_log_configuration, run_mode=RunMode.MULTIRUN, ) HydraConfig.instance().set_config(cfg) sweeper = Plugins.instance().instantiate_sweeper( config=cfg, config_loader=self.config_loader, task_function=task_function ) task_overrides = OmegaConf.to_container(cfg.hydra.overrides.task, resolve=False) assert isinstance(task_overrides, list) return sweeper.sweep(arguments=task_overrides) @staticmethod def get_sanitized_hydra_cfg(src_cfg: DictConfig) -> DictConfig: cfg = copy.deepcopy(src_cfg) with open_dict(cfg): for key in list(cfg.keys()): if key != "hydra": del cfg[key] with open_dict(cfg.hydra): del cfg.hydra["hydra_help"] del cfg.hydra["help"] return cfg def _get_cfg( self, config_name: Optional[str], overrides: List[str], cfg_type: str, with_log_configuration: bool, ) -> DictConfig: assert cfg_type in ["job", "hydra", "all"] cfg = self.compose_config( config_name=config_name, overrides=overrides, run_mode=RunMode.RUN, with_log_configuration=with_log_configuration, ) if cfg_type == "job": with open_dict(cfg): del cfg["hydra"] elif cfg_type == "hydra": cfg = self.get_sanitized_hydra_cfg(cfg) return cfg def show_cfg( self, config_name: Optional[str], overrides: List[str], cfg_type: str, package: Optional[str], ) -> None: cfg = self._get_cfg( config_name=config_name, overrides=overrides, cfg_type=cfg_type, with_log_configuration=False, ) if package == "_global_": package = None if package is not None: ret = OmegaConf.select(cfg, package) if ret is None: sys.stderr.write(f"package '{package}' not found in config\n") sys.exit(1) else: if isinstance(ret, Container): print(f"# @package {package}") sys.stdout.write(OmegaConf.to_yaml(ret)) else: print(ret) else: sys.stdout.write(OmegaConf.to_yaml(cfg)) @staticmethod def get_shell_to_plugin_map( config_loader: ConfigLoader, ) -> DefaultDict[str, List[CompletionPlugin]]: shell_to_plugin: DefaultDict[str, List[CompletionPlugin]] = defaultdict(list) for clazz in Plugins.instance().discover(CompletionPlugin): assert issubclass(clazz, CompletionPlugin) plugin = clazz(config_loader) shell_to_plugin[plugin.provides()].append(plugin) for shell, plugins in shell_to_plugin.items(): if len(plugins) > 1: lst = ",".join([type(plugin).__name__ for plugin in plugins]) raise ValueError(f"Multiple plugins installed for {shell} : {lst}") return shell_to_plugin def shell_completion( self, config_name: Optional[str], overrides: List[str] ) -> None: subcommands = ["install", "uninstall", "query"] arguments = OmegaConf.from_dotlist(overrides) num_commands = sum(1 for key in subcommands if arguments[key] is not None) if num_commands != 1: raise ValueError(f"Expecting one subcommand from {subcommands} to be set") shell_to_plugin = self.get_shell_to_plugin_map(self.config_loader) def find_plugin(cmd: str) -> CompletionPlugin: if cmd not in shell_to_plugin: lst = "\n".join(["\t" + x for x in shell_to_plugin.keys()]) raise ValueError( f"No completion plugin for '{cmd}' found, available : \n{lst}" ) return shell_to_plugin[cmd][0] if arguments.install is not None: plugin = find_plugin(arguments.install) plugin.install() elif arguments.uninstall is not None: plugin = find_plugin(arguments.uninstall) plugin.uninstall() elif arguments.query is not None: plugin = find_plugin(arguments.query) plugin.query(config_name=config_name) @staticmethod def format_args_help(args_parser: ArgumentParser) -> str: s = "" overrides: Any = None for action in args_parser._actions: if len(action.option_strings) == 0: overrides = action else: s += f"{','.join(action.option_strings)} : {action.help}\n" s += "Overrides : " + overrides.help return s def list_all_config_groups(self, parent: str = "") -> Sequence[str]: from hydra.core.object_type import ObjectType groups: List[str] = [] for group in self.config_loader.list_groups(parent): if parent == "": group_name = group else: group_name = "{}/{}".format(parent, group) files = self.config_loader.get_group_options(group_name, ObjectType.CONFIG) dirs = self.config_loader.get_group_options(group_name, ObjectType.GROUP) if len(files) > 0: groups.append(group_name) if len(dirs) > 0: groups.extend(self.list_all_config_groups(group_name)) return groups def format_config_groups( self, predicate: Callable[[str], bool], compact: bool = True ) -> str: groups = [x for x in self.list_all_config_groups() if predicate(x)] s = "" for group in sorted(groups): options = sorted(self.config_loader.get_group_options(group)) if compact: items = ", ".join(options) line = "{}: {}".format(group, items) else: items = "\n".join([" " + o for o in options]) line = "{}:\n{}".format(group, items) s += line + "\n" return s def get_help( self, help_cfg: DictConfig, cfg: DictConfig, args_parser: ArgumentParser ) -> str: s = string.Template(help_cfg.template) def is_hydra_group(x: str) -> bool: return x.startswith("hydra/") or x == "hydra" def is_not_hydra_group(x: str) -> bool: return not is_hydra_group(x) help_text = s.substitute( FLAGS_HELP=self.format_args_help(args_parser), HYDRA_CONFIG_GROUPS=self.format_config_groups(is_hydra_group), APP_CONFIG_GROUPS=self.format_config_groups(is_not_hydra_group), CONFIG=OmegaConf.to_yaml(cfg, resolve=False), ) return help_text def hydra_help( self, config_name: Optional[str], args_parser: ArgumentParser, args: Any ) -> None: cfg = self.compose_config( config_name=None, overrides=args.overrides, run_mode=RunMode.RUN, with_log_configuration=True, ) help_cfg = cfg.hydra.hydra_help cfg = self.get_sanitized_hydra_cfg(cfg) help_text = self.get_help(help_cfg, cfg, args_parser) print(help_text) def app_help( self, config_name: Optional[str], args_parser: ArgumentParser, args: Any ) -> None: cfg = self.compose_config( config_name=config_name, overrides=args.overrides, run_mode=RunMode.RUN, with_log_configuration=True, ) help_cfg = cfg.hydra.help clean_cfg = copy.deepcopy(cfg) with open_dict(clean_cfg): del clean_cfg["hydra"] help_text = self.get_help(help_cfg, clean_cfg, args_parser) print(help_text) @staticmethod def _log_header(header: str, prefix: str = "", filler: str = "-") -> None: assert log is not None log.debug(prefix + header) log.debug(prefix + "".ljust(len(header), filler)) @staticmethod def _log_footer(header: str, prefix: str = "", filler: str = "-") -> None: assert log is not None log.debug(prefix + "".ljust(len(header), filler)) def _print_plugins(self) -> None: assert log is not None self._log_header(header="Installed Hydra Plugins", filler="*") all_plugins = {p.__name__ for p in Plugins.instance().discover()} for plugin_type in [ ConfigSource, CompletionPlugin, Launcher, Sweeper, SearchPathPlugin, ]: # Mypy false positive? plugins = Plugins.instance().discover(plugin_type) # type: ignore if len(plugins) > 0: Hydra._log_header(header=f"{plugin_type.__name__}:", prefix="\t") for plugin in plugins: log.debug("\t\t{}".format(plugin.__name__)) if plugin.__name__ in all_plugins: all_plugins.remove(plugin.__name__) if len(all_plugins) > 0: Hydra._log_header(header="Generic plugins: ", prefix="\t") for plugin_name in all_plugins: log.debug("\t\t{}".format(plugin_name)) def _print_search_path(self) -> None: assert log is not None log.debug("") self._log_header(header="Config search path", filler="*") box: List[List[str]] = [["Provider", "Search path"]] for sp in self.config_loader.get_sources(): box.append([sp.provider, sp.full_path()]) provider_pad, search_path_pad = get_column_widths(box) header = "| {} | {} |".format( "Provider".ljust(provider_pad), "Search path".ljust(search_path_pad) ) self._log_header(header=header, filler="-") for source in self.config_loader.get_sources(): log.debug( "| {} | {} |".format( source.provider.ljust(provider_pad), source.full_path().ljust(search_path_pad), ) ) self._log_footer(header=header, filler="-") def _print_plugins_profiling_info(self, top_n: int) -> None: assert log is not None stats = Plugins.instance().get_stats() if stats is None: return items = list(stats.modules_import_time.items()) # hide anything that took less than 5ms filtered = filter(lambda x: x[1] > 0.0005, items) sorted_items = sorted(filtered, key=lambda x: x[1], reverse=True) top_n = max(len(sorted_items), top_n) box: List[List[str]] = [["Module", "Sec"]] for item in sorted_items[0:top_n]: box.append([item[0], f"{item[1]:.3f}"]) padding = get_column_widths(box) log.debug("") self._log_header(header="Profiling information", filler="*") self._log_header( header=f"Total plugins scan time : {stats.total_time:.3f} seconds", filler="-", ) header = f"| {box[0][0].ljust(padding[0])} | {box[0][1].ljust(padding[1])} |" self._log_header(header=header, filler="-") del box[0] for row in box: a = row[0].ljust(padding[0]) b = row[1].ljust(padding[1]) log.debug(f"| {a} | {b} |") self._log_footer(header=header, filler="-") def _print_config_info( self, config_name: Optional[str], overrides: List[str] ) -> None: assert log is not None self._print_search_path() self._print_defaults_tree(config_name=config_name, overrides=overrides) self._print_defaults_list(config_name=config_name, overrides=overrides) cfg = run_and_report( lambda: self._get_cfg( config_name=config_name, overrides=overrides, cfg_type="all", with_log_configuration=False, ) ) self._log_header(header="Config", filler="*") with open_dict(cfg): del cfg["hydra"] log.info(OmegaConf.to_yaml(cfg)) def _print_defaults_list( self, config_name: Optional[str], overrides: List[str] ) -> None: assert log is not None defaults = self.config_loader.compute_defaults_list( config_name=config_name, overrides=overrides, run_mode=RunMode.RUN, ) box: List[List[str]] = [ [ "Config path", "Package", "_self_", "Parent", ] ] for d in defaults.defaults: row = [ d.config_path, d.package, "True" if d.is_self else "False", d.parent, ] row = [x if x is not None else "" for x in row] box.append(row) padding = get_column_widths(box) del box[0] log.debug("") self._log_header("Defaults List", filler="*") header = "| {} | {} | {} | {} | ".format( "Config path".ljust(padding[0]), "Package".ljust(padding[1]), "_self_".ljust(padding[2]), "Parent".ljust(padding[3]), ) self._log_header(header=header, filler="-") for row in box: log.debug( "| {} | {} | {} | {} |".format( row[0].ljust(padding[0]), row[1].ljust(padding[1]), row[2].ljust(padding[2]), row[3].ljust(padding[3]), ) ) self._log_footer(header=header, filler="-") def _print_debug_info( self, config_name: Optional[str], overrides: List[str], ) -> None: assert log is not None if log.isEnabledFor(logging.DEBUG): self._print_all_info(config_name, overrides) def compose_config( self, config_name: Optional[str], overrides: List[str], run_mode: RunMode, strict: Optional[bool] = None, with_log_configuration: bool = False, from_shell: bool = True, ) -> DictConfig: """ :param config_name: :param overrides: :param run_mode: compose config for run or for multirun? :param with_log_configuration: True to configure logging subsystem from the loaded config :param strict: None for default behavior (default to true for config file, false if no config file). otherwise forces specific behavior. :param from_shell: True if the parameters are passed from the shell. used for more helpful error messages :return: """ cfg = self.config_loader.load_configuration( config_name=config_name, overrides=overrides, strict=strict, run_mode=run_mode, from_shell=from_shell, ) if with_log_configuration: configure_log(cfg.hydra.hydra_logging, cfg.hydra.verbose) global log log = logging.getLogger(__name__) self._print_debug_info(config_name, overrides) return cfg def _print_plugins_info( self, config_name: Optional[str], overrides: List[str] ) -> None: self._print_plugins() self._print_plugins_profiling_info(top_n=10) def _print_all_info(self, config_name: Optional[str], overrides: List[str]) -> None: from .. import __version__ self._log_header(f"Hydra {__version__}", filler="=") self._print_plugins() self._print_config_info(config_name, overrides) def _print_defaults_tree_impl( self, tree: Union[DefaultsTreeNode, InputDefault], indent: int = 0, ) -> None: assert log is not None from ..core.default_element import GroupDefault, InputDefault, VirtualRoot def to_str(node: InputDefault) -> str: if isinstance(node, VirtualRoot): return node.get_config_path() elif isinstance(node, GroupDefault): name = node.get_name() if name is None: name = "null" return node.get_override_key() + ": " + name else: return node.get_config_path() pad = " " * indent if isinstance(tree, DefaultsTreeNode): node_str = to_str(tree.node) if tree.children is not None and len(tree.children) > 0: log.info(pad + node_str + ":") for child in tree.children: self._print_defaults_tree_impl(tree=child, indent=indent + 1) else: log.info(pad + node_str) else: assert isinstance(tree, InputDefault) log.info(pad + to_str(tree)) def _print_defaults_tree( self, config_name: Optional[str], overrides: List[str] ) -> None: assert log is not None defaults = self.config_loader.compute_defaults_list( config_name=config_name, overrides=overrides, run_mode=RunMode.RUN, ) log.info("") self._log_header("Defaults Tree", filler="*") self._print_defaults_tree_impl(defaults.defaults_tree) def show_info( self, info: str, config_name: Optional[str], overrides: List[str] ) -> None: options = { "all": self._print_all_info, "defaults": self._print_defaults_list, "defaults-tree": self._print_defaults_tree, "config": self._print_config_info, "plugins": self._print_plugins_info, } simple_stdout_log_config(level=logging.DEBUG) global log log = logging.getLogger(__name__) if info not in options: opts = sorted(options.keys()) log.error(f"Info usage: --info [{'|'.join(opts)}]") else: options[info](config_name=config_name, overrides=overrides)
# -*- coding: utf-8 -*- """ @created on: 3/1/21, @author: Shreesha N, @version: v0.0.1 @system name: badgod Description: ..todo:: """ import json import random import time import numpy as np import torch import torch.nn as nn import torch.optim as optim from covid_19.networks.conv_ae import ConvAutoEncoder from covid_19.utils import file_utils from covid_19.utils.data_utils import read_pkl from covid_19.utils.logger import Logger from covid_19.utils.network_utils import accuracy_fn, log_summary, custom_confusion_matrix, \ log_conf_matrix, write_to_npy, to_tensor, to_numpy, log_learnable_parameter import pickle import wandb as wnb from sklearn import svm # setting seed torch.manual_seed(1234) np.random.seed(1234) class ConvAutoencoderRunner: def __init__(self, args, train_file, test_file): args['train_file'] = train_file self.train_file = train_file self.test_file = test_file self.run_name = args.run_name + '_' + train_file.split('.')[0] + '_' + str(time.time()).split('.')[0] self.current_run_basepath = args.network_metrics_basepath + '/' + self.run_name + '/' self.learning_rate = args.learning_rate self.epochs = args.epochs self.test_net = args.test_net self.train_net = args.train_net self.batch_size = args.batch_size self.num_classes = args.num_classes if args.data_source == 'mit': self.data_read_path = args.mit_data_save_path elif args.data_source == 'coswara': self.data_read_path = args.coswara_data_save_path else: # Keep coswara as default for now self.data_read_path = args.coswara_data_save_path self.is_cuda_available = torch.cuda.is_available() self.display_interval = args.display_interval self.logger = None self.network_metrics_basepath = args.network_metrics_basepath self.tensorboard_summary_path = self.current_run_basepath + args.tensorboard_summary_path self.network_save_path = self.current_run_basepath + args.network_save_path self.network_restore_path = args.network_restore_path self.device = torch.device("cuda" if self.is_cuda_available else "cpu") self.network_save_interval = args.network_save_interval self.normalise = args.normalise_while_training self.dropout = args.dropout self.threshold = args.threshold self.debug_filename = self.current_run_basepath + '/' + args.debug_filename paths = [self.network_save_path, self.tensorboard_summary_path] file_utils.create_dirs(paths) self.network = ConvAutoEncoder().to(self.device) self.pos_weight = None self.loss_function = None self.learning_rate_decay = args.learning_rate_decay self.optimiser = optim.Adam(self.network.parameters(), lr=self.learning_rate) self.scheduler = torch.optim.lr_scheduler.ExponentialLR(self.optimiser, gamma=self.learning_rate_decay) self._min, self._max = float('inf'), -float('inf') if self.train_net: wnb.init(project=args.project_name, config=args, save_code=True, name=self.run_name, entity="shreeshanwnb", reinit=True) wnb.watch(self.network) # , log='all', log_freq=3 self.network.train() self.logger = Logger(name=self.run_name, log_path=self.network_save_path).get_logger() self.logger.info("********* DATA FILE: " + train_file + " *********") self.logger.info(str(id(self.logger))) if self.test_net: self.logger.info('Loading Network') self.network.load_state_dict(torch.load(self.network_restore_path, map_location=self.device)) self.network.eval() self.logger.info('\n\n\n********************************************************') self.logger.info(f'Testing Model - {self.network_restore_path}') self.logger.info('********************************************************') self.logger.info(f"Network Architecture:\n,{self.network}") self.batch_loss, self.batch_accuracy, self.uar = [], [], [] self.logger.info(f'Configs used:\n{json.dumps(args, indent=4)}') def data_reader(self, data_filepath, data_files, train, should_batch=True, shuffle=True, infer=False): input_data, labels = [], [] def split_data(combined_data): return combined_data[0], combined_data[1] if infer: pass else: for file in data_files: self.logger.info('Reading input file ' + file) in_data = read_pkl(data_filepath + file) in_data, out_data = split_data(in_data) input_data.extend(in_data), labels.extend(out_data) split_type = None if train: split_type = 'train' for x in input_data: self._min = min(np.min(x), self._min) self._max = max(np.max(x), self._max) self._mean, self._std = np.mean(input_data), np.std(input_data) data = [(x, y) for x, y in zip(input_data, labels)] random.shuffle(data) input_data, labels = np.array([x[0] for x in data]), [x[1] for x in data] # Initialize pos_weight based on training data self.pos_weight = len([x for x in labels if x == 0]) / 1 if sum(labels) == 0 else len( [x for x in labels if x == 1]) self.logger.info(f'Pos weight for the train data - {self.pos_weight}') wnb.config.update({'pos_weight': self.pos_weight}) else: split_type = 'test' self.logger.info(f'Total data {str(len(input_data))}') wnb.config.update({split_type + '_data_len': len(input_data)}) self.logger.info(f'Event rate {str(sum(labels) / len(labels))}') wnb.config.update({split_type + '_event_rate': sum(labels) / len(labels)}) wnb.config.update( {split_type + '_ones_count': sum(labels), split_type + '_zeros_count': len(labels) - sum(labels)}) self.logger.info( f'Input data shape:{np.array(input_data).shape} | Output data shape:{np.array(labels).shape}') wnb.config.update({split_type + '_input_data_shape': np.array(input_data).shape}) self.logger.info(f'Min max values {self._min, self._max}') self.logger.info(f'Std values {self._std}') self.logger.info(f'Mean values {self._mean}') wnb.config.update({split_type + '_min_val': self._min, split_type + '_max_val': self._max, split_type + '_mean': self._mean, split_type + '_std': self._std}) # Normalizing `input data` on train dataset's min and max values if self.normalise: input_data = (input_data - self._min) / (self._max - self._min) input_data = (input_data - self._mean) / self._std if should_batch: batched_input = [input_data[pos:pos + self.batch_size] for pos in range(0, len(input_data), self.batch_size)] batched_labels = [labels[pos:pos + self.batch_size] for pos in range(0, len(labels), self.batch_size)] return batched_input, batched_labels else: return input_data, labels def mask_preds_for_one_class(self, predictions): # 1 --> inliers, -1 --> outliers # in our case, inliers are non covid samples. i.e label 0. # outliers are covid samples. i.e label 1. return [1 if x == -1 else 0 for x in predictions] def train(self): train_data, train_labels = self.data_reader(self.data_read_path, [self.train_file], shuffle=True, train=True) test_data, test_labels = self.data_reader(self.data_read_path, [self.test_file], shuffle=False, train=False) # For the purposes of assigning pos weight on the fly we are initializing the cost function here # self.loss_function = nn.BCEWithLogitsLoss(pos_weight=to_tensor(self.pos_weight, device=self.device)) self.loss_function = nn.MSELoss() for epoch in range(1, self.epochs): self.oneclass_svm = svm.OneClassSVM(nu=0.1, kernel="rbf", gamma=0.1) self.network.train() self.latent_features, train_predictions = [], [] for i, (audio_data, label) in enumerate( zip(train_data, train_labels)): self.optimiser.zero_grad() audio_data = to_tensor(audio_data, device=self.device) predictions, latent = self.network(audio_data) predictions = predictions.squeeze(1) self.latent_features.extend(to_numpy(latent.squeeze(1))) loss = self.loss_function(predictions, audio_data) loss.backward() self.optimiser.step() self.batch_loss.append(to_numpy(loss)) oneclass_predictions = self.oneclass_svm.fit_predict(self.latent_features) masked_predictions = self.mask_preds_for_one_class(oneclass_predictions) train_metrics = accuracy_fn(to_tensor(masked_predictions), to_tensor([element for sublist in train_labels for element in sublist]), threshold=self.threshold) wnb.log(train_metrics) wnb.log({'reconstruction_loss': np.mean(self.batch_loss)}) # Decay learning rate self.scheduler.step(epoch=epoch) wnb.log({"LR": self.optimiser.state_dict()['param_groups'][0]['lr']}) self.logger.info('***** Overall Train Metrics ***** ') self.logger.info( f"Epoch: {epoch} | Loss: {"%.5f" % np.mean(self.batch_loss)} | Accuracy: {"%.5f" % train_metrics["accuracy"]} " f"| UAR: {"%.5f" % train_metrics["uar"]} | F1:{"%.5f" % train_metrics["f1"]} " f"| Precision:{"%.5f" % train_metrics["precision"]} | Recall:{"%.5f" % train_metrics["recall"]} " f"| AUC:{"%.5f" % train_metrics["auc"]}") # test data self.run_for_epoch(epoch, test_data, test_labels, type='Test') self.oneclass_svm = None # Clearing the model for every epoch if epoch % self.network_save_interval == 0: save_path = self.network_save_path + '/' + self.run_name + '_' + str(epoch) + '.pt' save_path_oneclass_svm = self.network_save_path + '/oneclass_svm' + str(epoch) + '.pkl' torch.save(self.network.state_dict(), save_path) pickle.dump(self.oneclass_svm, open(save_path_oneclass_svm, 'wb')) self.logger.info(f'Network successfully saved: {save_path}') def run_for_epoch(self, epoch, x, y, type): self.network.eval() # for m in self.network.modules(): # if isinstance(m, nn.BatchNorm2d): # m.track_running_stats = False self.test_batch_loss, predictions, latent_features = [], [], [] with torch.no_grad(): for i, (audio_data, label) in enumerate(zip(x, y)): audio_data = to_tensor(audio_data, device=self.device) test_predictions, test_latent = self.network(audio_data) test_predictions = test_predictions.squeeze(1) latent_features.extend(to_numpy(test_latent.squeeze(1))) test_loss = self.loss_function(test_predictions, audio_data) self.test_batch_loss.append(to_numpy(test_loss)) oneclass_predictions = self.oneclass_svm.predict(latent_features) masked_predictions = self.mask_preds_for_one_class(oneclass_predictions) test_metrics = accuracy_fn(to_tensor(masked_predictions), to_tensor([element for sublist in y for element in sublist]), threshold=self.threshold) test_metrics = {'test_' + k: v for k, v in test_metrics.items()} self.logger.info(f'***** {type} Metrics ***** ') self.logger.info( f"Loss: {"%.5f" % np.mean(self.test_batch_loss)} | Accuracy: {"%.5f" % test_metrics["test_accuracy"]} " f"| UAR: {"%.5f" % test_metrics["test_uar"]}| F1:{"%.5f" % test_metrics["test_f1"]} " f"| Precision:{"%.5f" % test_metrics["test_precision"]} " f"| Recall:{"%.5f" % test_metrics["test_recall"]} | AUC:{"%.5f" % test_metrics["test_auc"]}") wnb.log(test_metrics) write_to_npy(filename=self.debug_filename, predictions=predictions, labels=y, epoch=epoch, accuracy=test_metrics['test_accuracy'], loss=np.mean(self.test_batch_loss), uar=test_metrics['test_auc'], precision=test_metrics['test_precision'], recall=test_metrics['test_recall'], auc=test_metrics['test_auc'], lr=self.optimiser.state_dict()['param_groups'][0]['lr'], type=type) if epoch + 1 == self.epochs: wnb.log({"test_cf": wnb.sklearn.plot_confusion_matrix(y_true=[label for sublist in y for label in sublist], y_pred=masked_predictions, labels=['Negative', 'Positive'])}) def test(self): test_data, test_labels = self.data_reader(self.data_read_path + 'test_challenge_data.npy', self.data_read_path + 'test_challenge_labels.npy', shuffle=False, train=False) test_predictions = self.network(test_data).squeeze(1) test_predictions = nn.Sigmoid()(test_predictions) test_accuracy, test_uar = accuracy_fn(test_predictions, test_labels, self.threshold) self.logger.info(f"Accuracy: {test_accuracy} | UAR: {test_uar}") self.logger.info(f"Accuracy: {test_accuracy} | UAR: {test_uar}") def infer(self, data_file): test_data = self.data_reader(data_file, shuffle=False, train=False, infer=True) test_predictions = self.network(test_data).squeeze(1) test_predictions = nn.Sigmoid()(test_predictions) return test_predictions
# -*- coding: utf-8 -*- """ @created on: 3/1/21, @author: Shreesha N, @version: v0.0.1 @system name: badgod Description: ..todo:: """ import json import random import time import numpy as np import torch import torch.nn as nn import torch.optim as optim from covid_19.networks.conv_ae import ConvAutoEncoder from covid_19.utils import file_utils from covid_19.utils.data_utils import read_pkl from covid_19.utils.logger import Logger from covid_19.utils.network_utils import accuracy_fn, log_summary, custom_confusion_matrix, \ log_conf_matrix, write_to_npy, to_tensor, to_numpy, log_learnable_parameter import pickle import wandb as wnb from sklearn import svm # setting seed torch.manual_seed(1234) np.random.seed(1234) class ConvAutoencoderRunner: def __init__(self, args, train_file, test_file): args['train_file'] = train_file self.train_file = train_file self.test_file = test_file self.run_name = args.run_name + '_' + train_file.split('.')[0] + '_' + str(time.time()).split('.')[0] self.current_run_basepath = args.network_metrics_basepath + '/' + self.run_name + '/' self.learning_rate = args.learning_rate self.epochs = args.epochs self.test_net = args.test_net self.train_net = args.train_net self.batch_size = args.batch_size self.num_classes = args.num_classes if args.data_source == 'mit': self.data_read_path = args.mit_data_save_path elif args.data_source == 'coswara': self.data_read_path = args.coswara_data_save_path else: # Keep coswara as default for now self.data_read_path = args.coswara_data_save_path self.is_cuda_available = torch.cuda.is_available() self.display_interval = args.display_interval self.logger = None self.network_metrics_basepath = args.network_metrics_basepath self.tensorboard_summary_path = self.current_run_basepath + args.tensorboard_summary_path self.network_save_path = self.current_run_basepath + args.network_save_path self.network_restore_path = args.network_restore_path self.device = torch.device("cuda" if self.is_cuda_available else "cpu") self.network_save_interval = args.network_save_interval self.normalise = args.normalise_while_training self.dropout = args.dropout self.threshold = args.threshold self.debug_filename = self.current_run_basepath + '/' + args.debug_filename paths = [self.network_save_path, self.tensorboard_summary_path] file_utils.create_dirs(paths) self.network = ConvAutoEncoder().to(self.device) self.pos_weight = None self.loss_function = None self.learning_rate_decay = args.learning_rate_decay self.optimiser = optim.Adam(self.network.parameters(), lr=self.learning_rate) self.scheduler = torch.optim.lr_scheduler.ExponentialLR(self.optimiser, gamma=self.learning_rate_decay) self._min, self._max = float('inf'), -float('inf') if self.train_net: wnb.init(project=args.project_name, config=args, save_code=True, name=self.run_name, entity="shreeshanwnb", reinit=True) wnb.watch(self.network) # , log='all', log_freq=3 self.network.train() self.logger = Logger(name=self.run_name, log_path=self.network_save_path).get_logger() self.logger.info("********* DATA FILE: " + train_file + " *********") self.logger.info(str(id(self.logger))) if self.test_net: self.logger.info('Loading Network') self.network.load_state_dict(torch.load(self.network_restore_path, map_location=self.device)) self.network.eval() self.logger.info('\n\n\n********************************************************') self.logger.info(f'Testing Model - {self.network_restore_path}') self.logger.info('********************************************************') self.logger.info(f"Network Architecture:\n,{self.network}") self.batch_loss, self.batch_accuracy, self.uar = [], [], [] self.logger.info(f'Configs used:\n{json.dumps(args, indent=4)}') def data_reader(self, data_filepath, data_files, train, should_batch=True, shuffle=True, infer=False): input_data, labels = [], [] def split_data(combined_data): return combined_data[0], combined_data[1] if infer: pass else: for file in data_files: self.logger.info('Reading input file ' + file) in_data = read_pkl(data_filepath + file) in_data, out_data = split_data(in_data) input_data.extend(in_data), labels.extend(out_data) split_type = None if train: split_type = 'train' for x in input_data: self._min = min(np.min(x), self._min) self._max = max(np.max(x), self._max) self._mean, self._std = np.mean(input_data), np.std(input_data) data = [(x, y) for x, y in zip(input_data, labels)] random.shuffle(data) input_data, labels = np.array([x[0] for x in data]), [x[1] for x in data] # Initialize pos_weight based on training data self.pos_weight = len([x for x in labels if x == 0]) / 1 if sum(labels) == 0 else len( [x for x in labels if x == 1]) self.logger.info(f'Pos weight for the train data - {self.pos_weight}') wnb.config.update({'pos_weight': self.pos_weight}) else: split_type = 'test' self.logger.info(f'Total data {str(len(input_data))}') wnb.config.update({split_type + '_data_len': len(input_data)}) self.logger.info(f'Event rate {str(sum(labels) / len(labels))}') wnb.config.update({split_type + '_event_rate': sum(labels) / len(labels)}) wnb.config.update( {split_type + '_ones_count': sum(labels), split_type + '_zeros_count': len(labels) - sum(labels)}) self.logger.info( f'Input data shape:{np.array(input_data).shape} | Output data shape:{np.array(labels).shape}') wnb.config.update({split_type + '_input_data_shape': np.array(input_data).shape}) self.logger.info(f'Min max values {self._min, self._max}') self.logger.info(f'Std values {self._std}') self.logger.info(f'Mean values {self._mean}') wnb.config.update({split_type + '_min_val': self._min, split_type + '_max_val': self._max, split_type + '_mean': self._mean, split_type + '_std': self._std}) # Normalizing `input data` on train dataset's min and max values if self.normalise: input_data = (input_data - self._min) / (self._max - self._min) input_data = (input_data - self._mean) / self._std if should_batch: batched_input = [input_data[pos:pos + self.batch_size] for pos in range(0, len(input_data), self.batch_size)] batched_labels = [labels[pos:pos + self.batch_size] for pos in range(0, len(labels), self.batch_size)] return batched_input, batched_labels else: return input_data, labels def mask_preds_for_one_class(self, predictions): # 1 --> inliers, -1 --> outliers # in our case, inliers are non covid samples. i.e label 0. # outliers are covid samples. i.e label 1. return [1 if x == -1 else 0 for x in predictions] def train(self): train_data, train_labels = self.data_reader(self.data_read_path, [self.train_file], shuffle=True, train=True) test_data, test_labels = self.data_reader(self.data_read_path, [self.test_file], shuffle=False, train=False) # For the purposes of assigning pos weight on the fly we are initializing the cost function here # self.loss_function = nn.BCEWithLogitsLoss(pos_weight=to_tensor(self.pos_weight, device=self.device)) self.loss_function = nn.MSELoss() for epoch in range(1, self.epochs): self.oneclass_svm = svm.OneClassSVM(nu=0.1, kernel="rbf", gamma=0.1) self.network.train() self.latent_features, train_predictions = [], [] for i, (audio_data, label) in enumerate( zip(train_data, train_labels)): self.optimiser.zero_grad() audio_data = to_tensor(audio_data, device=self.device) predictions, latent = self.network(audio_data) predictions = predictions.squeeze(1) self.latent_features.extend(to_numpy(latent.squeeze(1))) loss = self.loss_function(predictions, audio_data) loss.backward() self.optimiser.step() self.batch_loss.append(to_numpy(loss)) oneclass_predictions = self.oneclass_svm.fit_predict(self.latent_features) masked_predictions = self.mask_preds_for_one_class(oneclass_predictions) train_metrics = accuracy_fn(to_tensor(masked_predictions), to_tensor([element for sublist in train_labels for element in sublist]), threshold=self.threshold) wnb.log(train_metrics) wnb.log({'reconstruction_loss': np.mean(self.batch_loss)}) # Decay learning rate self.scheduler.step(epoch=epoch) wnb.log({"LR": self.optimiser.state_dict()['param_groups'][0]['lr']}) self.logger.info('***** Overall Train Metrics ***** ') self.logger.info( f"Epoch: {epoch} | Loss: {'%.5f' % np.mean(self.batch_loss)} | Accuracy: {'%.5f' % train_metrics['accuracy']} " f"| UAR: {'%.5f' % train_metrics['uar']} | F1:{'%.5f' % train_metrics['f1']} " f"| Precision:{'%.5f' % train_metrics['precision']} | Recall:{'%.5f' % train_metrics['recall']} " f"| AUC:{'%.5f' % train_metrics['auc']}") # test data self.run_for_epoch(epoch, test_data, test_labels, type='Test') self.oneclass_svm = None # Clearing the model for every epoch if epoch % self.network_save_interval == 0: save_path = self.network_save_path + '/' + self.run_name + '_' + str(epoch) + '.pt' save_path_oneclass_svm = self.network_save_path + '/oneclass_svm' + str(epoch) + '.pkl' torch.save(self.network.state_dict(), save_path) pickle.dump(self.oneclass_svm, open(save_path_oneclass_svm, 'wb')) self.logger.info(f'Network successfully saved: {save_path}') def run_for_epoch(self, epoch, x, y, type): self.network.eval() # for m in self.network.modules(): # if isinstance(m, nn.BatchNorm2d): # m.track_running_stats = False self.test_batch_loss, predictions, latent_features = [], [], [] with torch.no_grad(): for i, (audio_data, label) in enumerate(zip(x, y)): audio_data = to_tensor(audio_data, device=self.device) test_predictions, test_latent = self.network(audio_data) test_predictions = test_predictions.squeeze(1) latent_features.extend(to_numpy(test_latent.squeeze(1))) test_loss = self.loss_function(test_predictions, audio_data) self.test_batch_loss.append(to_numpy(test_loss)) oneclass_predictions = self.oneclass_svm.predict(latent_features) masked_predictions = self.mask_preds_for_one_class(oneclass_predictions) test_metrics = accuracy_fn(to_tensor(masked_predictions), to_tensor([element for sublist in y for element in sublist]), threshold=self.threshold) test_metrics = {'test_' + k: v for k, v in test_metrics.items()} self.logger.info(f'***** {type} Metrics ***** ') self.logger.info( f"Loss: {'%.5f' % np.mean(self.test_batch_loss)} | Accuracy: {'%.5f' % test_metrics['test_accuracy']} " f"| UAR: {'%.5f' % test_metrics['test_uar']}| F1:{'%.5f' % test_metrics['test_f1']} " f"| Precision:{'%.5f' % test_metrics['test_precision']} " f"| Recall:{'%.5f' % test_metrics['test_recall']} | AUC:{'%.5f' % test_metrics['test_auc']}") wnb.log(test_metrics) write_to_npy(filename=self.debug_filename, predictions=predictions, labels=y, epoch=epoch, accuracy=test_metrics['test_accuracy'], loss=np.mean(self.test_batch_loss), uar=test_metrics['test_auc'], precision=test_metrics['test_precision'], recall=test_metrics['test_recall'], auc=test_metrics['test_auc'], lr=self.optimiser.state_dict()['param_groups'][0]['lr'], type=type) if epoch + 1 == self.epochs: wnb.log({"test_cf": wnb.sklearn.plot_confusion_matrix(y_true=[label for sublist in y for label in sublist], y_pred=masked_predictions, labels=['Negative', 'Positive'])}) def test(self): test_data, test_labels = self.data_reader(self.data_read_path + 'test_challenge_data.npy', self.data_read_path + 'test_challenge_labels.npy', shuffle=False, train=False) test_predictions = self.network(test_data).squeeze(1) test_predictions = nn.Sigmoid()(test_predictions) test_accuracy, test_uar = accuracy_fn(test_predictions, test_labels, self.threshold) self.logger.info(f"Accuracy: {test_accuracy} | UAR: {test_uar}") self.logger.info(f"Accuracy: {test_accuracy} | UAR: {test_uar}") def infer(self, data_file): test_data = self.data_reader(data_file, shuffle=False, train=False, infer=True) test_predictions = self.network(test_data).squeeze(1) test_predictions = nn.Sigmoid()(test_predictions) return test_predictions
import numpy as np # I used this class from our PPO group project class AnnealedParam(float): def __new__(cls, param_min, param_max, period, param_value=None, param_max_decay=1.0, param_min_decay=1.0, schedule_type="linear", iteration=0 ): param_value = param_value if param_value else param_max return float.__new__(cls, param_value) def __getnewargs__(self): return self.param_min, self.param_max, self.period def __init__( self, param_min, param_max, period, param_value=None, param_max_decay=1.0, param_min_decay=1.0, schedule_type="linear", iteration=0 ): assert param_min <= param_max, ValueError param_value = param_value if param_value else param_max float.__init__(param_value) self.param_min = param_min self.param_max = param_max self.period = period self.param_max_decay = param_max_decay self.param_min_decay = param_min_decay self.schedule_type = schedule_type self.iteration = iteration def calculate_param_from_schedule(self): if self.schedule_type == "linear": cycle_pct = (self.period - self.iteration % self.period) / self.period return self.param_min + (self.param_max - self.param_min) * cycle_pct elif self.schedule_type == "sinusoidal": cycle_pct = (1 + np.cost(np.pi * self.iteration / self.period)) / 2 return self.param_min + (self.param_max - self.param_min) * cycle_pct else: raise NotImplementedError def update(self): new_param_value = self.calculate_param_from_schedule() self.param_max = self.param_max_decay*self.param_max + (1 - self.param_max_decay)*self.param_min self.param_min = self.param_min_decay*self.param_min + (1 - self.param_min_decay)*self.param_max self.iteration += 1 return AnnealedParam(**self.__dict__, param_value=new_param_value) def __str__(self): return f"annealed_{"{0:.1E}".format(self.param_min)}_{"{0:.1E}".format(self.param_max)}_{self.period}".replace( ".", "-" )
import numpy as np # I used this class from our PPO group project class AnnealedParam(float): def __new__(cls, param_min, param_max, period, param_value=None, param_max_decay=1.0, param_min_decay=1.0, schedule_type="linear", iteration=0 ): param_value = param_value if param_value else param_max return float.__new__(cls, param_value) def __getnewargs__(self): return self.param_min, self.param_max, self.period def __init__( self, param_min, param_max, period, param_value=None, param_max_decay=1.0, param_min_decay=1.0, schedule_type="linear", iteration=0 ): assert param_min <= param_max, ValueError param_value = param_value if param_value else param_max float.__init__(param_value) self.param_min = param_min self.param_max = param_max self.period = period self.param_max_decay = param_max_decay self.param_min_decay = param_min_decay self.schedule_type = schedule_type self.iteration = iteration def calculate_param_from_schedule(self): if self.schedule_type == "linear": cycle_pct = (self.period - self.iteration % self.period) / self.period return self.param_min + (self.param_max - self.param_min) * cycle_pct elif self.schedule_type == "sinusoidal": cycle_pct = (1 + np.cost(np.pi * self.iteration / self.period)) / 2 return self.param_min + (self.param_max - self.param_min) * cycle_pct else: raise NotImplementedError def update(self): new_param_value = self.calculate_param_from_schedule() self.param_max = self.param_max_decay*self.param_max + (1 - self.param_max_decay)*self.param_min self.param_min = self.param_min_decay*self.param_min + (1 - self.param_min_decay)*self.param_max self.iteration += 1 return AnnealedParam(**self.__dict__, param_value=new_param_value) def __str__(self): return f"annealed_{'{0:.1E}'.format(self.param_min)}_{'{0:.1E}'.format(self.param_max)}_{self.period}".replace( ".", "-" )
import brownie import pytest from brownie import ZERO_ADDRESS from tests.conftest import approx REWARD = 10 ** 20 WEEK = 7 * 86400 LP_AMOUNT = 10 ** 18 @pytest.fixture(scope="module") def reward_contract_2(MobiusRewards, mock_lp_token, accounts, coin_a): contract = MobiusRewards.deploy(mock_lp_token, coin_a, {"from": accounts[0]}) contract.setRewardDistribution(accounts[0], {"from": accounts[0]}) yield contract @pytest.fixture(scope="module", autouse=True) def initial_setup(gauge_v2, mock_lp_token, alice, reward_contract, coin_reward): mock_lp_token.approve(gauge_v2, 2 ** 256 - 1, {"from": alice}) gauge_v2.deposit(1, {"from": alice}) sigs = [ reward_contract.stake.signature[2:], reward_contract.withdraw.signature[2:], reward_contract.getReward.signature[2:], ] sigs = f"0x{sigs[0]}{sigs[1]}{sigs[2]}{"00" * 20}" gauge_v2.set_rewards(reward_contract, sigs, [coin_reward] + [ZERO_ADDRESS] * 7, {"from": alice}) gauge_v2.withdraw(1, {"from": alice}) def test_unset_no_totalsupply(alice, coin_reward, reward_contract, gauge_v2, mock_lp_token): gauge_v2.set_rewards(ZERO_ADDRESS, "0x00", [ZERO_ADDRESS] * 8, {"from": alice}) assert mock_lp_token.allowance(gauge_v2, reward_contract) == 0 assert gauge_v2.reward_contract() == ZERO_ADDRESS assert [gauge_v2.reward_tokens(i) for i in range(8)] == [ZERO_ADDRESS] * 8 def test_unset_with_totalsupply(alice, coin_reward, reward_contract, gauge_v2, mock_lp_token): gauge_v2.deposit(LP_AMOUNT, {"from": alice}) gauge_v2.set_rewards(ZERO_ADDRESS, "0x00", [ZERO_ADDRESS] * 8, {"from": alice}) assert mock_lp_token.allowance(gauge_v2, reward_contract) == 0 assert mock_lp_token.balanceOf(gauge_v2) == LP_AMOUNT assert gauge_v2.reward_contract() == ZERO_ADDRESS assert [gauge_v2.reward_tokens(i) for i in range(8)] == [ZERO_ADDRESS] * 8 def test_unsetting_claims(alice, chain, coin_reward, reward_contract, gauge_v2): gauge_v2.deposit(LP_AMOUNT, {"from": alice}) coin_reward._mint_for_testing(reward_contract, REWARD) reward_contract.notifyRewardAmount(REWARD, {"from": alice}) chain.sleep(WEEK) gauge_v2.set_rewards(ZERO_ADDRESS, "0x00", [ZERO_ADDRESS] * 8, {"from": alice}) reward = coin_reward.balanceOf(gauge_v2) assert reward <= REWARD assert approx(REWARD, reward, 1.001 / WEEK) def test_modify_no_deposit_no_ts(reward_contract_2, alice, gauge_v2, coin_a): sigs = f"0x{"00" * 4}{"00" * 4}{reward_contract_2.getReward.signature[2:]}{"00" * 20}" gauge_v2.set_rewards(reward_contract_2, sigs, [coin_a] + [ZERO_ADDRESS] * 7, {"from": alice}) assert gauge_v2.reward_contract() == reward_contract_2 assert gauge_v2.reward_tokens(0) == coin_a assert gauge_v2.reward_tokens(1) == ZERO_ADDRESS def test_modify_no_deposit( reward_contract, reward_contract_2, alice, gauge_v2, chain, coin_a, coin_reward, mock_lp_token ): gauge_v2.deposit(LP_AMOUNT, {"from": alice}) coin_reward._mint_for_testing(reward_contract, REWARD) reward_contract.notifyRewardAmount(REWARD, {"from": alice}) chain.sleep(86400) sigs = f"0x{"00" * 4}{"00" * 4}{reward_contract_2.getReward.signature[2:]}{"00" * 20}" gauge_v2.set_rewards(reward_contract_2, sigs, [coin_a] + [ZERO_ADDRESS] * 7, {"from": alice}) assert mock_lp_token.balanceOf(gauge_v2) == LP_AMOUNT assert gauge_v2.reward_contract() == reward_contract_2 assert gauge_v2.reward_tokens(0) == coin_a assert gauge_v2.reward_tokens(1) == ZERO_ADDRESS assert coin_reward.balanceOf(gauge_v2) > 0 def test_modify_deposit( reward_contract, reward_contract_2, alice, gauge_v2, chain, coin_a, coin_reward, mock_lp_token ): gauge_v2.deposit(LP_AMOUNT, {"from": alice}) coin_reward._mint_for_testing(reward_contract, REWARD) reward_contract.notifyRewardAmount(REWARD, {"from": alice}) chain.sleep(86400) sigs = [ reward_contract.stake.signature[2:], reward_contract.withdraw.signature[2:], reward_contract.getReward.signature[2:], ] sigs = f"0x{sigs[0]}{sigs[1]}{sigs[2]}{"00" * 20}" gauge_v2.set_rewards(reward_contract_2, sigs, [coin_a] + [ZERO_ADDRESS] * 7, {"from": alice}) assert mock_lp_token.balanceOf(reward_contract_2) == LP_AMOUNT assert gauge_v2.reward_contract() == reward_contract_2 assert gauge_v2.reward_tokens(0) == coin_a assert gauge_v2.reward_tokens(1) == ZERO_ADDRESS assert coin_reward.balanceOf(gauge_v2) > 0 def test_modify_deposit_no_ts(reward_contract_2, alice, gauge_v2, coin_a): sigs = [ reward_contract_2.stake.signature[2:], reward_contract_2.withdraw.signature[2:], reward_contract_2.getReward.signature[2:], ] sigs = f"0x{sigs[0]}{sigs[1]}{sigs[2]}{"00" * 20}" with brownie.reverts("dev: zero total supply"): gauge_v2.set_rewards( reward_contract_2, sigs, [coin_a] + [ZERO_ADDRESS] * 7, {"from": alice} )
import brownie import pytest from brownie import ZERO_ADDRESS from tests.conftest import approx REWARD = 10 ** 20 WEEK = 7 * 86400 LP_AMOUNT = 10 ** 18 @pytest.fixture(scope="module") def reward_contract_2(MobiusRewards, mock_lp_token, accounts, coin_a): contract = MobiusRewards.deploy(mock_lp_token, coin_a, {"from": accounts[0]}) contract.setRewardDistribution(accounts[0], {"from": accounts[0]}) yield contract @pytest.fixture(scope="module", autouse=True) def initial_setup(gauge_v2, mock_lp_token, alice, reward_contract, coin_reward): mock_lp_token.approve(gauge_v2, 2 ** 256 - 1, {"from": alice}) gauge_v2.deposit(1, {"from": alice}) sigs = [ reward_contract.stake.signature[2:], reward_contract.withdraw.signature[2:], reward_contract.getReward.signature[2:], ] sigs = f"0x{sigs[0]}{sigs[1]}{sigs[2]}{'00' * 20}" gauge_v2.set_rewards(reward_contract, sigs, [coin_reward] + [ZERO_ADDRESS] * 7, {"from": alice}) gauge_v2.withdraw(1, {"from": alice}) def test_unset_no_totalsupply(alice, coin_reward, reward_contract, gauge_v2, mock_lp_token): gauge_v2.set_rewards(ZERO_ADDRESS, "0x00", [ZERO_ADDRESS] * 8, {"from": alice}) assert mock_lp_token.allowance(gauge_v2, reward_contract) == 0 assert gauge_v2.reward_contract() == ZERO_ADDRESS assert [gauge_v2.reward_tokens(i) for i in range(8)] == [ZERO_ADDRESS] * 8 def test_unset_with_totalsupply(alice, coin_reward, reward_contract, gauge_v2, mock_lp_token): gauge_v2.deposit(LP_AMOUNT, {"from": alice}) gauge_v2.set_rewards(ZERO_ADDRESS, "0x00", [ZERO_ADDRESS] * 8, {"from": alice}) assert mock_lp_token.allowance(gauge_v2, reward_contract) == 0 assert mock_lp_token.balanceOf(gauge_v2) == LP_AMOUNT assert gauge_v2.reward_contract() == ZERO_ADDRESS assert [gauge_v2.reward_tokens(i) for i in range(8)] == [ZERO_ADDRESS] * 8 def test_unsetting_claims(alice, chain, coin_reward, reward_contract, gauge_v2): gauge_v2.deposit(LP_AMOUNT, {"from": alice}) coin_reward._mint_for_testing(reward_contract, REWARD) reward_contract.notifyRewardAmount(REWARD, {"from": alice}) chain.sleep(WEEK) gauge_v2.set_rewards(ZERO_ADDRESS, "0x00", [ZERO_ADDRESS] * 8, {"from": alice}) reward = coin_reward.balanceOf(gauge_v2) assert reward <= REWARD assert approx(REWARD, reward, 1.001 / WEEK) def test_modify_no_deposit_no_ts(reward_contract_2, alice, gauge_v2, coin_a): sigs = f"0x{'00' * 4}{'00' * 4}{reward_contract_2.getReward.signature[2:]}{'00' * 20}" gauge_v2.set_rewards(reward_contract_2, sigs, [coin_a] + [ZERO_ADDRESS] * 7, {"from": alice}) assert gauge_v2.reward_contract() == reward_contract_2 assert gauge_v2.reward_tokens(0) == coin_a assert gauge_v2.reward_tokens(1) == ZERO_ADDRESS def test_modify_no_deposit( reward_contract, reward_contract_2, alice, gauge_v2, chain, coin_a, coin_reward, mock_lp_token ): gauge_v2.deposit(LP_AMOUNT, {"from": alice}) coin_reward._mint_for_testing(reward_contract, REWARD) reward_contract.notifyRewardAmount(REWARD, {"from": alice}) chain.sleep(86400) sigs = f"0x{'00' * 4}{'00' * 4}{reward_contract_2.getReward.signature[2:]}{'00' * 20}" gauge_v2.set_rewards(reward_contract_2, sigs, [coin_a] + [ZERO_ADDRESS] * 7, {"from": alice}) assert mock_lp_token.balanceOf(gauge_v2) == LP_AMOUNT assert gauge_v2.reward_contract() == reward_contract_2 assert gauge_v2.reward_tokens(0) == coin_a assert gauge_v2.reward_tokens(1) == ZERO_ADDRESS assert coin_reward.balanceOf(gauge_v2) > 0 def test_modify_deposit( reward_contract, reward_contract_2, alice, gauge_v2, chain, coin_a, coin_reward, mock_lp_token ): gauge_v2.deposit(LP_AMOUNT, {"from": alice}) coin_reward._mint_for_testing(reward_contract, REWARD) reward_contract.notifyRewardAmount(REWARD, {"from": alice}) chain.sleep(86400) sigs = [ reward_contract.stake.signature[2:], reward_contract.withdraw.signature[2:], reward_contract.getReward.signature[2:], ] sigs = f"0x{sigs[0]}{sigs[1]}{sigs[2]}{'00' * 20}" gauge_v2.set_rewards(reward_contract_2, sigs, [coin_a] + [ZERO_ADDRESS] * 7, {"from": alice}) assert mock_lp_token.balanceOf(reward_contract_2) == LP_AMOUNT assert gauge_v2.reward_contract() == reward_contract_2 assert gauge_v2.reward_tokens(0) == coin_a assert gauge_v2.reward_tokens(1) == ZERO_ADDRESS assert coin_reward.balanceOf(gauge_v2) > 0 def test_modify_deposit_no_ts(reward_contract_2, alice, gauge_v2, coin_a): sigs = [ reward_contract_2.stake.signature[2:], reward_contract_2.withdraw.signature[2:], reward_contract_2.getReward.signature[2:], ] sigs = f"0x{sigs[0]}{sigs[1]}{sigs[2]}{'00' * 20}" with brownie.reverts("dev: zero total supply"): gauge_v2.set_rewards( reward_contract_2, sigs, [coin_a] + [ZERO_ADDRESS] * 7, {"from": alice} )
# coding: utf-8 # Copyright 2020-2021 Huawei Technologies Co., Ltd # # 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. # ============================================================================ """Operators for array.""" import copy import functools import itertools import numbers from collections import Counter import numpy as np from mindspore import log as logger from mindspore.common.initializer import Zero from .. import signature as sig from .._utils import get_broadcast_shape, is_shape_unknown from .._utils import get_concat_offset from ..operations.math_ops import _infer_shape_reduce from ..primitive import Primitive, PrimitiveWithInfer, PrimitiveWithCheck, prim_attr_register, _run_op from ..._checkparam import Rel from ..._checkparam import Validator as validator from ..._checkparam import _check_3d_int_or_tuple from ...common import dtype as mstype from ...common._decorator import deprecated from ...common.parameter import Parameter from ...common.tensor import Tensor from ..._c_expression import Tensor as Tensor_ class _ScatterOp(PrimitiveWithInfer): """ Defines Scatter operators """ __mindspore_signature__ = ( sig.make_sig('x', sig.sig_rw.RW_WRITE, dtype=sig.sig_dtype.T), sig.make_sig('indices', dtype=sig.sig_dtype.T1), sig.make_sig('updates', dtype=sig.sig_dtype.T) ) def _check_scatter_shape(self, x_shape, indices_shape, updates_shape, prim_name): if indices_shape != [-1] and updates_shape and updates_shape != indices_shape + x_shape[1:]: raise ValueError(f"For '{prim_name}', " f"updates_shape = indices_shape + x_shape[1:], but got x_shape: {x_shape}, " f"indices_shape: {indices_shape}, updates_shape: {updates_shape}.") @prim_attr_register def __init__(self, use_locking=False): """Initialize _ScatterOp""" validator.check_value_type('use_locking', use_locking, [bool], self.name) self.init_prim_io_names(inputs=['x', 'indices', 'updates'], outputs=['y']) self.add_prim_attr('side_effect_mem', True) def infer_shape(self, x_shape, indices_shape, updates_shape): self._check_scatter_shape(x_shape, indices_shape, updates_shape, self.name) return x_shape def infer_dtype(self, x_dtype, indices_dtype, updates_dtype): validator.check_tensor_dtype_valid('indices', indices_dtype, [mstype.int32], self.name) args = {"x": x_dtype, "updates": updates_dtype} validator.check_tensors_dtypes_same_and_valid(args, mstype.number_type, self.name) return x_dtype class _ScatterOpDynamic(PrimitiveWithCheck): """ Defines Scatter operators with dynamic shape """ __mindspore_signature__ = ( sig.make_sig('x', sig.sig_rw.RW_WRITE, dtype=sig.sig_dtype.T), sig.make_sig('indices', dtype=sig.sig_dtype.T1), sig.make_sig('updates', dtype=sig.sig_dtype.T) ) def _check_scatter_shape(self, x_shape, indices_shape, updates_shape, prim_name): # x_shape cannot be dynamic if np.any(np.array(x_shape) == -1): raise ValueError(f"For '{prim_name}', the 'input_x' does not support dynamic shape, " f"but got the shape of 'input_x' is {x_shape}.") # support indices and updates dynamic if np.any(np.array(indices_shape) == -1) or np.any(np.array(updates_shape) == -1): pass elif indices_shape != [-1] and updates_shape and updates_shape != indices_shape + x_shape[1:]: raise ValueError(f"For '{prim_name}', " f"updates_shape = indices_shape + x_shape[1:], but got x_shape: {x_shape}, " f"indices_shape: {indices_shape}, updates_shape: {updates_shape}.") @prim_attr_register def __init__(self, use_locking=False): """Initialize _ScatterOpDynamic""" validator.check_value_type('use_locking', use_locking, [bool], self.name) self.init_prim_io_names(inputs=['x', 'indices', 'updates'], outputs=['y']) self.add_prim_attr('side_effect_mem', True) def check_shape(self, x_shape, indices_shape, updates_shape): self._check_scatter_shape(x_shape, indices_shape, updates_shape, self.name) def check_dtype(self, x_dtype, indices_dtype, updates_dtype): validator.check_tensor_dtype_valid('indices', indices_dtype, [mstype.int32], self.name) args = {"x": x_dtype, "updates": updates_dtype} validator.check_tensors_dtypes_same_and_valid(args, mstype.number_type, self.name) class _ScatterNdOp(_ScatterOp): """ Defines _ScatterNd operators """ def _check_scatter_shape(self, x_shape, indices_shape, updates_shape, prim_name): validator.check('the dimension of x', len(x_shape), 'the dimension of indices', indices_shape[-1], Rel.GE) if indices_shape[:-1] + x_shape[indices_shape[-1]:] != updates_shape: raise ValueError(f"For '{prim_name}', updates_shape = " f"indices_shape[:-1] + x_shape[indices_shape[-1]:], but got x_shape: {x_shape}, " f"indices_shape: {indices_shape}, updates_shape: {updates_shape}.") def _check_infer_attr_reduce(axis, keep_dims, prim_name): validator.check_value_type('keep_dims', keep_dims, [bool], prim_name) validator.check_value_type('axis', axis, [int, tuple], prim_name) if isinstance(axis, tuple): for index, value in enumerate(axis): validator.check_value_type('axis[%d]' % index, value, [int], prim_name) class ExpandDims(PrimitiveWithInfer): """ Adds an additional dimension to `input_x` at the given axis. Note: If the specified axis is a negative number, the index is counted backward from the end and starts at 1. Inputs: - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. - **axis** (int) - Specifies the dimension index at which to expand the shape of `input_x`. The value of axis must be in the range `[-input_x.ndim-1, input_x.ndim]`. Only constant value is allowed. Outputs: Tensor, the shape of tensor is :math:`(1, x_1, x_2, ..., x_R)` if the value of `axis` is 0. It has the same data type as `input_x`. Raises: ValueError: If `axis` is not an int or not in the valid range. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_tensor = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32) >>> expand_dims = ops.ExpandDims() >>> output = expand_dims(input_tensor, 0) >>> print(output) [[[2. 2.] [2. 2.]]] """ @prim_attr_register def __init__(self): """Initialize ExpandDims""" self.init_prim_io_names(inputs=['x', 'axis'], outputs=['output']) def __infer__(self, x, axis): validator.check_subclass("x", x['dtype'], mstype.tensor, self.name) x_shape = list(x['shape']) axis_v = axis['value'] rank = len(x_shape) validator.check_int_range(axis_v, -rank - 1, rank, Rel.INC_BOTH, 'axis', self.name) value = None if x['value'] is not None: value = x['value'].asnumpy() value = np.expand_dims(value, axis_v) value = Tensor(value) if axis_v < 0: axis_v = rank + 1 + axis_v x_shape.insert(axis_v, 1) out = {'shape': x_shape, 'dtype': x['dtype'], 'value': value} if 'min_shape' in x and 'max_shape' in x: out['min_shape'] = x['min_shape'] out['min_shape'].insert(axis_v, 1) out['max_shape'] = x['max_shape'] out['max_shape'].insert(axis_v, 1) return out class DType(Primitive): """ Returns the data type of the input tensor as mindspore.dtype. Inputs: - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. Outputs: mindspore.dtype, the data type of a tensor. Raises: TypeError: If `input_x` is not a Tensor. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_tensor = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32) >>> output = ops.DType()(input_tensor) >>> print(output) Float32 """ @prim_attr_register def __init__(self): """Initialize DType""" class SameTypeShape(PrimitiveWithInfer): """ Checks whether the data type and shape of two tensors are the same. Inputs: - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. - **input_y** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_S)`. Outputs: Tensor, the shape of tensor is :math:`(x_1, x_2, ..., x_R)`, if data type and shape of `input_x` and `input_y` are the same. Raises: TypeError: If the data types of `input_x` and `input_y` are not the same. ValueError: If the shapes of `input_x` and `input_y` are not the same. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32) >>> input_y = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32) >>> output = ops.SameTypeShape()(input_x, input_y) >>> print(output) [[2. 2.] [2. 2.]] """ @prim_attr_register def __init__(self): """Initialize Same""" def __call__(self, x, y): """run in PyNative mode""" validator.check_value_type('x', x, Tensor, self.name) validator.check_value_type('y', y, Tensor, self.name) validator.check('x dtype', x.dtype, 'y dtype', y.dtype, Rel.EQ, self.name, TypeError) validator.check('x shape', x.shape, 'y shape', y.shape, Rel.EQ, self.name) return x def __infer__(self, x, y): validator.check_subclass('x', x['dtype'], mstype.tensor, self.name) validator.check_subclass('y', y['dtype'], mstype.tensor, self.name) validator.check('x dtype', x['dtype'], 'y dtype', y['dtype'], Rel.EQ, self.name, TypeError) validator.check('x shape', x['shape'], 'y shape', y['shape'], Rel.EQ, self.name) return x class Cast(PrimitiveWithInfer): """ Returns a tensor with the new specified data type. Inputs: - **input_x** (Union[Tensor, Number]) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. The tensor to be cast. - **type** (dtype.Number) - The valid data type of the output tensor. Only constant value is allowed. Outputs: Tensor, the shape of tensor is the same as `input_x`, :math:`(x_1, x_2, ..., x_R)`. Raises: TypeError: If `input_x` is neither Tensor nor Number. TypeError: If `type` is not a Number. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_np = np.random.randn(2, 3, 4, 5).astype(np.float32) >>> input_x = Tensor(input_np) >>> type_dst = mindspore.int32 >>> cast = ops.Cast() >>> output = cast(input_x, type_dst) >>> print(output.dtype) Int32 >>> print(output.shape) (2, 3, 4, 5) """ @prim_attr_register def __init__(self): # if primitive need setattr in __infer__ need add this flag """Initialize Cast""" self.init_prim_io_names(inputs=['x', 'dst_type'], outputs=['output']) def check_elim(self, x, dtype): if isinstance(x, (Tensor, numbers.Number, Parameter)): if isinstance(x, Parameter): data = x.data if data.dtype == dtype: return (True, x) if isinstance(x, Tensor) and x.dtype == dtype: x = Tensor(x) x.set_cast_dtype() return (True, x) if isinstance(x, numbers.Number): return (True, Tensor(x, dtype=dtype)) return (False, None) def __infer__(self, x, t): src_type = x['dtype'] dst_type = t['value'] validator.check_subclass("input_x", src_type, [mstype.tensor, mstype.number], self.name) validator.check_subclass("type", dst_type, mstype.number, self.name) if isinstance(src_type, type(mstype.tensor)): src_type = x['dtype'].element_type() if isinstance(dst_type, type(mstype.tensor)): dst_type = dst_type.element_type() self.add_prim_attr('DstT', dst_type) self.add_prim_attr('SrcT', src_type) self.add_prim_attr('dst_type', dst_type) value = None if x['value'] is not None: np_dst_type = mstype.dtype_to_nptype(dst_type) if isinstance(x['value'], (int, float)): value = Tensor(np.array(x['value']).astype(np_dst_type)) else: value = Tensor(x['value'].asnumpy().astype(np_dst_type)) out = {'shape': x['shape'], 'dtype': mstype.tensor_type(t['value']), 'value': value} if 'min_shape' in x and 'max_shape' in x: out['min_shape'] = x['min_shape'] out['max_shape'] = x['max_shape'] return out class IsSubClass(PrimitiveWithInfer): """ Checks whether this type is a sub-class of another type. Inputs: - **sub_type** (mindspore.dtype) - The type to be checked. Only constant value is allowed. - **type_** (mindspore.dtype) - The target type. Only constant value is allowed. Outputs: bool, the check result. Raises: TypeError: If `sub_type` or `type_` is not a Type. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> output = ops.IsSubClass()(mindspore.int32, mindspore.intc) >>> print(output) True """ @prim_attr_register def __init__(self): pass def __infer__(self, sub_type, type_): sub_type_t = sub_type['value'] type_v = type_['value'] validator.check_value_type("sub_type", sub_type_t, [mstype.Type], self.name) validator.check_value_type("type_", type_v, [mstype.Type], self.name) value = mstype.issubclass_(sub_type_t, type_v) out = {'shape': (), 'dtype': mstype.type_type, 'value': value} return out class IsInstance(PrimitiveWithInfer): """ Checks whether an object is an instance of a target type. Inputs: - **inst** (Any Object) - The instance to be checked. Only constant value is allowed. - **type_** (mindspore.dtype) - The target type. Only constant value is allowed. Outputs: bool, the check result. Raises: TypeError: If `type_` is not a Type. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> inst = 1 >>> output = ops.IsInstance()(inst, mindspore.int32) >>> print(output) False """ @prim_attr_register def __init__(self): pass def __infer__(self, inst, type_): sub_type_t = inst['dtype'] type_v = type_['value'] validator.check_value_type("type_", type_v, [mstype.Type], self.name) if type_v == mstype.list_: value = isinstance(sub_type_t, list) elif type_v == mstype.tuple_: value = isinstance(sub_type_t, tuple) else: value = mstype.issubclass_(sub_type_t, type_v) out = {'shape': (), 'dtype': mstype.type_type, 'value': value} return out class Reshape(PrimitiveWithInfer): """ Reshapes the input tensor with the same values based on a given shape tuple. The 'input_shape' can only have one -1 at most, in which case it’s inferred from the remaining dimensions and the number of elements in the input. Inputs: - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. - **input_shape** (tuple[int]) - The input tuple is constructed by multiple integers, i.e., :math:`(y_1, y_2, ..., y_S)`. Only constant value is allowed. Outputs: Tensor, the shape of tensor is :math:`(y_1, y_2, ..., y_S)`. Raises: ValueError: Given a shape tuple, if it has several -1; or if the product of its elements is less than or equal to 0 or cannot be divided by the product of the input tensor shape; or if it does not match the input's array size. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32) >>> reshape = ops.Reshape() >>> output = reshape(input_x, (3, 2)) >>> print(output) [[-0.1 0.3] [ 3.6 0.4] [ 0.5 -3.2]] """ @prim_attr_register def __init__(self): """Initialize Reshape""" self.init_prim_io_names(inputs=['tensor', 'shape'], outputs=['output']) def _get_shape_and_range(self, x, shape): """ get min and max shape when output shape is dynamic""" min_shape = None max_shape = None x_shp = x['shape'] if is_shape_unknown(shape['shape']): out_shape = [-2] return out_shape, min_shape, max_shape shape_rank = shape['shape'][0] if not x_shp: # x is a scalar, output shape fixed out_shape = [1] * shape_rank return out_shape, min_shape, max_shape out_shape = [-1] * shape_rank if "max_value" in shape and "min_value" in shape: min_shape = shape["min_value"] max_shape = shape["max_value"] if len(min_shape) != shape_rank or len(max_shape) != shape_rank: raise RuntimeError("The primitive[Reshape]'s input[shape] min or max value not math the shape rank.") for i in range(shape_rank): if min_shape[i] == max_shape[i]: out_shape[i] = min_shape[i] elif is_shape_unknown(x_shp) and "max_shape" in x: # when dynamic memory allocation is supported, max_shape can be left out min_shape = [1] * shape_rank max_shape = [int(np.prod(x["max_shape"]))] * shape_rank return out_shape, min_shape, max_shape def __infer__(self, x, shape): shape_v = shape['value'] x_shp = x['shape'] validator.check_subclass("x", x['dtype'], mstype.tensor, self.name) # for shape is not constant if shape_v is None: out_shape, min_shape, max_shape = self._get_shape_and_range(x, shape) if is_shape_unknown(out_shape): # `min_shape` and `max_shape` can't be None before dynamic memory allocation is supported shape_shp = shape['shape'] shape_rank = 1 if is_shape_unknown(shape_shp) else shape_shp[0] min_shape = [1] * shape_rank if min_shape is None else min_shape max_shape = [1] * shape_rank if max_shape is None else max_shape return { 'shape': out_shape, 'dtype': x['dtype'], 'value': None, 'max_shape': max_shape, 'min_shape': min_shape } if isinstance(shape_v, Tensor_): validator.check_tensor_dtype_valid("shape", shape['dtype'], [mstype.int64], self.name) shape_v = shape_v.asnumpy().tolist() else: validator.check_value_type("shape", shape_v, [tuple], self.name) shape_v = list(shape_v) neg_index = -1 dim_prod = 1 for i, shp_i in enumerate(shape_v): validator.check_value_type("shape[%d]" % i, shp_i, [int], self.name) if shp_i == -1: if neg_index != -1: raise ValueError(f"For '{self.name}', there can be at most one '-1' in 'input_shape', " f"but got {shape_v}.") neg_index = i else: dim_prod *= shp_i if is_shape_unknown(x_shp): if 'max_shape' in x: x_max_shape = x['max_shape'] else: x_max_shape = x['shape'] if 'min_shape' in x: x_min_shape = x['min_shape'] else: x_min_shape = x['shape'] max_arr_prod = np.prod(x_max_shape) min_arr_prod = np.prod(x_min_shape) max_shape = list(shape_v) min_shape = list(shape_v) if neg_index != -1: max_shape[neg_index] = int(max_arr_prod / dim_prod) min_shape[neg_index] = int(min_arr_prod / dim_prod) out = {'shape': shape_v, 'dtype': x['dtype'], 'value': None, 'max_shape': tuple(max_shape), 'min_shape': tuple(min_shape)} else: arr_prod = np.prod(x_shp) if dim_prod <= 0: raise ValueError(f"For '{self.name}', the shape of 'input_x' is {x_shp}, " f"the value of 'input_shape' is {shape_v}. " f"The product of 'input_shape' should > 0, but got {dim_prod}.") if neg_index != -1: shape_v[neg_index] = int(arr_prod / dim_prod) dim_prod *= shape_v[neg_index] if dim_prod != arr_prod: raise ValueError(f"For '{self.name}', the shape of 'input_x' is {x_shp}, " f"the value of 'input_shape' value is {shape_v}. " f"The product of the shape of 'input_x' should be equal to product of 'input_shape', " f"but product of the shape of 'input_x' is {arr_prod}, " f"product of 'input_shape' is {dim_prod}.") value = None if x['value'] is not None: value = Tensor(x['value'].asnumpy().reshape(shape_v)) out = {'shape': tuple(shape_v), 'dtype': x['dtype'], 'value': value} return out class Shape(Primitive): """ Returns the shape of the input tensor. And it used to be static shape. static shape: A shape that can be obtained without running the graph. It is an inherent property of tensor and may be unknown. The static shape information can be completed by artificial setting. No matter what the input of the graph is, the static shape is not affected. Inputs: - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. Outputs: tuple[int], the output tuple is constructed by multiple integers, :math:`(x_1, x_2, ..., x_R)`. Raises: TypeError: If `input_x` is not a Tensor. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Tensor(np.ones(shape=[3, 2, 1]), mindspore.float32) >>> shape = ops.Shape() >>> output = shape(input_x) >>> print(output) (3, 2, 1) """ @prim_attr_register def __init__(self): """Initialize Shape""" class DynamicShape(Primitive): """ Returns the shape of the input tensor. And it used to be dynamic shape. Note: Dynamic shape: After the graph is running, as the tensor flows in the graph, the specific shape of the tensor on each node on the graph can be inferred according to the structure of the graph. This shape is called a dynamic shape. As the input shape of the graph is different, the dynamic shape of the tensor in the graph will change. Inputs: - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. Outputs: Tensor[int], 1-dim Tensor of type int32 Raises: TypeError: If `input_x` is not a Tensor. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Tensor(np.ones(shape=[3, 2, 1]), mindspore.float32) >>> shape = ops.DynamicShape() >>> output = shape(input_x) >>> print(output) [3 2 1] """ @prim_attr_register def __init__(self): """init Shape""" self.init_prim_io_names(inputs=['tensor'], outputs=['output']) self.add_prim_attr('is_dynamic_shape', True) class Squeeze(PrimitiveWithInfer): """ Returns a tensor with the same data type but dimensions of 1 are removed based on `axis`. If `axis` is specified, it will remove the dimensions of size 1 in the given `axis`. It `axis` is None, it will remove all the dimensions of size 1. For example, if input is of shape: (A×1×B×C×1×D), then the out tensor will be of shape: (A×B×C×D); When dim is given, a squeeze operation is done only in the given dimension. If input is of shape: (A×1×B), squeeze(input, 0) leaves the tensor unchanged, but squeeze(input, 1) will squeeze the tensor to the shape (A×B). Please note that in dynamic graph mode, the output Tensor will share data with the input Tensor, and there is no Tensor data copy process. Note: The dimension index starts at 0 and must be in the range `[-input.ndim, input.ndim]`. Args: axis (Union[int, tuple(int)]): Specifies the dimension indexes of shape to be removed, which will remove all the dimensions that are equal to 1. If specified, it must be int32 or int64. Default: (), an empty tuple. Inputs: - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. Outputs: Tensor, the shape of tensor is :math:`(x_1, x_2, ..., x_S)`. Raises: TypeError: If `axis` is neither an int nor tuple. TypeError: If `axis` is a tuple whose elements are not all int. ValueError: If the corresponding dimension of the specified axis isn't equal to 1. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Tensor(np.ones(shape=[3, 2, 1]), mindspore.float32) >>> squeeze = ops.Squeeze(2) >>> output = squeeze(input_x) >>> print(output) [[1. 1.] [1. 1.] [1. 1.]] """ @prim_attr_register def __init__(self, axis=()): """Initialize Squeeze""" self.init_prim_io_names(inputs=['x'], outputs=['output']) validator.check_value_type('axis', axis, [int, tuple], self.name) if isinstance(axis, tuple): for idx, item in enumerate(axis): validator.check_value_type("axis[%d]" % idx, item, [int], self.name) else: self.axis = (axis,) self.add_prim_attr("axis", (axis,)) class Transpose(Primitive): """ Permutes the dimensions of the input tensor according to input permutation. For a 1-D array this has no effect, as a transposed vector is simply the same vector. To convert a 1-D array into a 2D column vecto please refer the class: mindspore.ops.ExpandDims. For a 2-D array, this is a standard matrix transpose. For an n-D array, if axes are given, their order indicates how the axes are permuted (see Examples). If axes are not provided and a.shape = (i[0], i[1], ... i[n-2], i[n-1]), then a.transpose().shape = (i[n-1], i[n-2], ... i[1], i[0]). Inputs: - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. - **input_perm** (tuple[int]) - The permutation to be converted. The elements in `input_perm` are composed of the indexes of each dimension of `input_x`. The length of `input_perm` and the shape of `input_x` must be the same. Only constant value is allowed. Must be in the range [0, rank(input_x)). Outputs: Tensor, the type of output tensor is the same as `input_x` and the shape of output tensor is decided by the shape of `input_x` and the value of `input_perm`. Raises: TypeError: If `input_perm` is not a tuple. ValueError: If length of shape of `input_x` is not equal to length of shape of `input_perm`. ValueError: If the same element exists in `input_perm`. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Tensor(np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]), mindspore.float32) >>> input_perm = (0, 2, 1) >>> transpose = ops.Transpose() >>> output = transpose(input_x, input_perm) >>> print(output) [[[ 1. 4.] [ 2. 5.] [ 3. 6.]] [[ 7. 10.] [ 8. 11.] [ 9. 12.]]] """ @prim_attr_register def __init__(self): """Initialize Transpose""" self.init_prim_io_names(inputs=['x', 'perm'], outputs=['output']) class Unique(Primitive): """ Returns the unique elements of input tensor and also return a tensor containing the index of each value of input tensor corresponding to the output unique tensor. The output contains Tensor `y` and Tensor `idx`, the format is probably similar to (`y`, `idx`). The shape of Tensor `y` and Tensor `idx` is different in most cases, because Tensor `y` will be deduplicated, and the shape of Tensor `idx` is consistent with the input. To get the same shape between `idx` and `y`, please ref to 'UniqueWithPad' operator. Inputs: - **input_x** (Tensor) - The input tensor. The shape is :math:`(N,*)` where :math:`*` means, any number of additional dimensions. Outputs: Tuple, containing Tensor objects (`y`, `idx`), `y` is a tensor with the same type as `input_x`, and contains the unique elements in `x`, sorted in ascending order. `idx` is a tensor containing indices of elements in the input corresponding to the output tensor. Raises: TypeError: If `input_x` is not a Tensor. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Tensor(np.array([1, 2, 5, 2]), mindspore.int32) >>> output = ops.Unique()(input_x) >>> print(output) (Tensor(shape=[3], dtype=Int32, value= [1, 2, 5]), Tensor(shape=[4], dtype=Int32, value= [0, 1, 2, 1])) >>> y = output[0] >>> print(y) [1 2 5] >>> idx = output[1] >>> print(idx) [0 1 2 1] >>> # As can be seen from the above, y and idx shape >>> # note that for GPU, this operator must be wrapped inside a model, and executed in graph mode. >>> class UniqueNet(nn.Cell): ... def __init__(self): ... super(UniqueNet, self).__init__() ... self.unique_op = ops.Unique() ... ... def construct(self, x): ... output, indices = self.unique_op(x) ... return output, indices ... >>> input_x = Tensor(np.array([1, 2, 5, 2]), mindspore.int32) >>> net = UniqueNet() >>> output = net(input_x) >>> print(output) (Tensor(shape=[3], dtype=Int32, value= [1, 2, 5]), Tensor(shape=[4], dtype=Int32, value= [0, 1, 2, 1])) """ @prim_attr_register def __init__(self): self.init_prim_io_names(inputs=['x'], outputs=['output']) class Gather(Primitive): r""" Returns a slice of the input tensor based on the specified indices and axis. Slices the input tensor base on the indices at specified axis. See the following example for more clear. Inputs: - **input_params** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. The original Tensor. - **input_indices** (Tensor) - The shape of tensor is :math:`(y_1, y_2, ..., y_S)`. Specifies the indices of elements of the original Tensor. Must be in the range `[0, input_param.shape[axis])` which are only validated on CPU. The data type can be int32 or int64. - **axis** (int) - Specifies the dimension index to gather indices. Outputs: Tensor, the shape of tensor is :math:`input\_params.shape[:axis] + input\_indices.shape + input\_params.shape[axis + 1:]`. Raises: TypeError: If `axis` is not an int. TypeError: If `input_indices` is not an int. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_params = Tensor(np.array([[1, 2, 7, 42], [3, 4, 54, 22], [2, 2, 55, 3]]), mindspore.float32) >>> input_indices = Tensor(np.array([1, 2]), mindspore.int32) >>> axis = 1 >>> output = ops.Gather()(input_params, input_indices, axis) >>> print(output) [[ 2. 7.] [ 4. 54.] [ 2. 55.]] >>> axis = 0 >>> output = ops.Gather()(input_params, input_indices, axis) >>> print(output) [[3. 4. 54. 22.] [2. 2. 55. 3.]] """ @prim_attr_register def __init__(self): """Initialize Gather""" self.init_prim_io_names(inputs=['params', 'indices', 'axis'], outputs=['output']) class GatherV2(PrimitiveWithCheck): """ Same as operator Gather. GatherV2 will be deprecated in the future. Please use Gather instead. """ @deprecated("1.1", "Gather", True) @prim_attr_register def __init__(self): """Initialize GatherV2""" self.init_prim_io_names(inputs=['params', 'indices', 'axis'], outputs=['output']) def __check__(self, params, indices, axis): validator.check_subclass("params", params['dtype'], mstype.tensor, self.name) validator.check_tensor_dtype_valid("indices", indices['dtype'], mstype.int_type, self.name) validator.check_subclass("axis", axis['dtype'], [mstype.number], self.name) axis_v = axis['value'] validator.check_value_type('axis', axis_v, [int], self.name) rank = len(params['shape']) validator.check_int_range(axis_v, -rank, rank, Rel.INC_LEFT, "axis", self.name) class SparseGatherV2(PrimitiveWithCheck): """ Returns a slice of input tensor based on the specified indices and axis. Inputs: - **input_params** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. - **input_indices** (Tensor) - The shape of tensor is :math:`(y_1, y_2, ..., y_S)`. Specifies the indices of elements of the original Tensor, must be in the range `[0, input_param.shape[axis])`. - **axis** (int) - Specifies the dimension index to gather indices. Outputs: Tensor, the shape of tensor is :math:`(z_1, z_2, ..., z_N)`. Raises: TypeError: If `axis` is not an int. Supported Platforms: ``Ascend`` ``GPU`` Examples: >>> input_params = Tensor(np.array([[1, 2, 7, 42], [3, 4, 54, 22], [2, 2, 55, 3]]), mindspore.float32) >>> input_indices = Tensor(np.array([1, 2]), mindspore.int32) >>> axis = 1 >>> out = ops.SparseGatherV2()(input_params, input_indices, axis) >>> print(out) [[2. 7.] [4. 54.] [2. 55.]] """ @prim_attr_register def __init__(self): """Initialize SparseGatherV2""" self.init_prim_io_names(inputs=['params', 'indices', 'axis'], outputs=['output']) def __check__(self, params, indices, axis): validator.check_subclass("params", params['dtype'], mstype.tensor, self.name) validator.check_tensor_dtype_valid("indices", indices['dtype'], mstype.int_type, self.name) validator.check_subclass("axis", axis['dtype'], [mstype.number], self.name) axis_v = axis['value'] validator.check_value_type('axis', axis_v, [int], self.name) rank = len(params['shape']) validator.check_int_range(axis_v, -rank, rank, Rel.INC_LEFT, "axis", self.name) class Padding(PrimitiveWithInfer): """ Extends the last dimension of the input tensor from 1 to pad_dim_size, by filling with 0. Args: pad_dim_size (int): The value of the last dimension of `x` to be extended, which must be positive. Default: 8. Inputs: - **x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. The rank of `x` must be at least 2. The last dimension of `x` must be 1. The data type is Number. Outputs: Tensor, the shape of tensor is :math:`(z_1, z_2, ..., z_N)`. Raises: TypeError: If `pad_dim_size` is not an int. ValueError: If `pad_dim_size` is less than 1. ValueError: If last dim of `x` is not equal 1. Supported Platforms: ``Ascend`` Examples: >>> x = Tensor(np.array([[8], [10]]), mindspore.float32) >>> pad_dim_size = 4 >>> output = ops.Padding(pad_dim_size)(x) >>> print(output) [[ 8. 0. 0. 0.] [10. 0. 0. 0.]] """ @prim_attr_register def __init__(self, pad_dim_size=8): """Initialize padding""" validator.check_value_type("pad_dim_size", pad_dim_size, [int], self.name) validator.check_positive_int(pad_dim_size, "pad_dim_size", self.name) self.pad_dim_size = pad_dim_size def __infer__(self, x): validator.check_subclass("x", x['dtype'], mstype.tensor, self.name) x_shape = list(x['shape']) validator.check_int(len(x_shape), 1, Rel.GT, "rank of x", self.name) validator.check_int(x_shape[-1], 1, Rel.EQ, "last dim of x", self.name) out_shape = x_shape out_shape[-1] = self.pad_dim_size out = {'shape': out_shape, 'dtype': x['dtype'], 'value': None} return out class UniqueWithPad(PrimitiveWithInfer): """ Returns unique elements and relative indexes in 1-D tensor, filled with padding num. The basic function is the same as the Unique operator, but the UniqueWithPad operator adds a Pad function. The returned tuple(`y`, `idx`) after the input Tensor `x` is processed by the unique operator, in which the shapes of `y` and `idx` are mostly not equal. Therefore, in order to solve the above situation, the UniqueWithPad operator will fill the `y` Tensor with the `pad_num` specified by the user to make it have the same shape as the Tensor `idx`. Inputs: - **x** (Tensor) - The tensor need to be unique. Must be 1-D vector with types: int32, int64. - **pad_num** (int) - Pad num. The data type is an int. Outputs: tuple(Tensor), tuple of 2 tensors, `y` and `idx`. - y (Tensor) - The unique elements filled with pad_num, the shape and data type same as `x`. - idx (Tensor) - The index of each value of `x` in the unique output `y`, the shape and data type same as `x`. Raises: TypeError: If dtype of `x` is neither int32 nor int64. ValueError: If length of shape of `x` is not equal to 1. Supported Platforms: ``Ascend`` ``CPU`` Examples: >>> x = Tensor(np.array([1, 1, 5, 5, 4, 4, 3, 3, 2, 2,]), mindspore.int32) >>> pad_num = 8 >>> output = ops.UniqueWithPad()(x, pad_num) >>> print(output) (Tensor(shape=[10], dtype=Int32, value= [1, 5, 4, 3, 2, 8, 8, 8, 8, 8]), Tensor(shape=[10], dtype=Int32, value= [0, 0, 1, 1, 2, 2, 3, 3, 4, 4])) """ @prim_attr_register def __init__(self): """init UniqueWithPad""" def __infer__(self, x, pad_num): validator.check_tensor_dtype_valid("x", x['dtype'], [mstype.int32, mstype.int64], self.name) validator.check_subclass("pad_num", pad_num['dtype'], [mstype.int32, mstype.int64], self.name) x_shape = list(x['shape']) validator.check("rank of x", len(x_shape), "expected", 1, Rel.EQ, self.name) out_shape = x_shape out = {'shape': (out_shape, out_shape), 'dtype': (x['dtype'], x['dtype']), 'value': None} return out class Split(PrimitiveWithCheck): """ Splits the input tensor into output_num of tensors along the given axis and output numbers. The `input_x` tensor will be split into equally sized sub-tensors. This requires that `input_x.shape(axis)` is divisible by `output_num`. Args: axis (int): Index of the split position. Default: 0. output_num (int): The number of output tensors. Must be positive int. Default: 1. Inputs: - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. Outputs: tuple[Tensor], the shape of each output tensor is the same, which is :math:`(y_1, y_2, ..., y_S)`. And the data type is the same with `input_x`. Raises: TypeError: If `axis` or `output_num` is not an int. ValueError: If `axis` is out of the range [-len(`input_x.shape`), len(`input_x.shape`)), or if the `output_num` is less than or equal to 0. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> split = ops.Split(1, 2) >>> x = Tensor(np.array([[1, 1, 1, 1], [2, 2, 2, 2]]), mindspore.int32) >>> print(x) [[1 1 1 1] [2 2 2 2]] >>> output = split(x) >>> print(output) (Tensor(shape=[2, 2], dtype=Int32, value= [[1, 1], [2, 2]]), Tensor(shape=[2, 2], dtype=Int32, value= [[1, 1], [2, 2]])) >>> split = ops.Split(1, 4) >>> output = split(x) >>> print(output) (Tensor(shape=[2, 1], dtype=Int32, value= [[1], [2]]), Tensor(shape=[2, 1], dtype=Int32, value= [[1], [2]]), Tensor(shape=[2, 1], dtype=Int32, value= [[1], [2]]), Tensor(shape=[2, 1], dtype=Int32, value= [[1], [2]])) """ @prim_attr_register def __init__(self, axis=0, output_num=1): """Initialize Split""" validator.check_value_type("axis", axis, [int], self.name) validator.check_value_type("output_num", output_num, [int], self.name) validator.check_positive_int(output_num, "output_num", self.name) self.axis = axis self.output_num = output_num def __check__(self, x): validator.check_subclass("x", x['dtype'], mstype.tensor, self.name) x_shape = list(x['shape']) dim = len(x_shape) validator.check_int_range(self.axis, -dim, dim, Rel.INC_LEFT, 'axis value', self.name) if -1 not in x_shape: # only validate when shape fully known output_valid_check = x_shape[self.axis] % self.output_num if output_valid_check != 0: raise ValueError(f"For '{self.name}', the specified axis of 'input_x' should be divided exactly by " f"'output_num', but got the shape of 'input_x' in 'axis' {self.axis} is " f"{x_shape[self.axis]}, 'output_num': {self.output_num}.") size_splits = [x_shape[self.axis] // self.output_num] * self.output_num self.add_prim_attr('size_splits', size_splits) class Rank(PrimitiveWithInfer): """ Returns the rank of a tensor. Returns a 0-D int32 Tensor representing the rank of input; the rank of a tensor is the number of indices required to uniquely select each element of the tensor. Inputs: - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. The data type is Number. Outputs: Tensor. 0-D int32 Tensor representing the rank of input, i.e., :math:`R`. The data type is an int. Raises: TypeError: If `input_x` is not a Tensor. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_tensor = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32) >>> rank = ops.Rank() >>> output = rank(input_tensor) >>> print(output) 2 >>> print(type(output)) <class 'int'> """ @prim_attr_register def __init__(self): """Initialize Rank""" def __infer__(self, x): validator.check_subclass("x", x['dtype'], mstype.tensor, self.name) out = {'shape': None, 'dtype': None, 'value': len(x['shape'])} return out class TruncatedNormal(PrimitiveWithInfer): """ Returns a tensor of the specified shape filled with truncated normal values. The generated values follow a normal distribution. Args: seed (int): A integer number used to create random seed. Default: 0. dtype (:class:`mindspore.dtype`): Data type. Default: mindspore.float32. Inputs: - **shape** (tuple[int]) - The shape of the output tensor, is a tuple of positive integer. Outputs: Tensor, the data type of output tensor is the same as attribute `dtype`. Examples: >>> shape = (1, 2, 3) >>> truncated_normal = ops.TruncatedNormal() >>> output = truncated_normal(shape) """ @prim_attr_register def __init__(self, seed=0, dtype=mstype.float32): """Initialize TruncatedNormal""" validator.check_value_type('seed', seed, [int], self.name) validator.check_types_same_and_valid({'dtype': dtype}, mstype.number_type, self.name) def __infer__(self, shape): shape_value = shape['value'] validator.check_value_type("shape", shape_value, [tuple], self.name) for i, value in enumerate(shape_value): validator.check_positive_int(value, f'{i}th value of shape', self.name) out = {'shape': shape_value, 'dtype': mstype.tensor_type(self.dtype), 'value': None} return out class Size(PrimitiveWithInfer): r""" Returns the size of a Tensor. Returns an int scalar representing the elements' size of input, the total number of elements in the tensor. Inputs: - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. The data type is Number. Outputs: int. A scalar representing the elements' size of `input_x`, tensor is the number of elements in a tensor, :math:`size=x_1*x_2*...x_R`. The data type is an int. Raises: TypeError: If `input_x` is not a Tensor. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32) >>> size = ops.Size() >>> output = size(input_x) >>> print(output) 4 """ @prim_attr_register def __init__(self): """Initialize Size""" def __infer__(self, x): size = 1 validator.check_subclass("x", x['dtype'], mstype.tensor, self.name) shp = x['shape'] if not shp: size = 0 else: size = functools.reduce(lambda x, y: x * y, x['shape']) out = {'shape': None, 'dtype': mstype.int64, 'value': size} return out class Fill(PrimitiveWithInfer): """ Creates a tensor filled with a scalar value. Creates a tensor with shape described by the first argument and fills it with values in the second argument. Inputs: - **type** (mindspore.dtype) - The specified type of output tensor. Only constant value is allowed. - **shape** (tuple) - The specified shape of output tensor. Only constant value is allowed. - **value** (scalar) - Value to fill the returned tensor. Only constant value is allowed. Outputs: Tensor, has the same type and shape as input value. Raises: TypeError: If `shape` is not a tuple. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> fill = ops.Fill() >>> output = fill(mindspore.float32, (2, 2), 1) >>> print(output) [[1. 1.] [1. 1.]] >>> output = fill(mindspore.float32, (3, 3), 0) >>> print(output) [[0. 0. 0.] [0. 0. 0.] [0. 0. 0.]] """ @prim_attr_register def __init__(self): """Initialize Fill""" def __infer__(self, dtype, dims, x): validator.check_value_type("shape", dims['value'], [tuple], self.name) validator.check_value_type("value", x['value'], [numbers.Number, bool], self.name) for i, item in enumerate(dims['value']): validator.check_positive_int(item, f'dims[{i}]', self.name) valid_dtypes = [mstype.bool_, mstype.int8, mstype.int16, mstype.int32, mstype.int64, mstype.uint8, mstype.uint16, mstype.uint32, mstype.uint64, mstype.float16, mstype.float32, mstype.float64, mstype.complex64, mstype.complex128] validator.check_types_same_and_valid({"value": dtype['value']}, valid_dtypes, self.name) x_nptype = mstype.dtype_to_nptype(dtype['value']) ret = np.full(dims['value'], x['value'], x_nptype) out = { 'value': Tensor(ret), 'shape': dims['value'], 'dtype': x['dtype'], } return out class Ones(Primitive): r""" Creates a tensor filled with value ones. Creates a tensor with shape described by the first argument and fills it with value ones in type of the second argument. Inputs: - **shape** (Union[tuple[int], int]) - The specified shape of output tensor. Only constant positive int is allowed. - **type** (mindspore.dtype) - The specified type of output tensor. Only constant value is allowed. Outputs: Tensor, has the same type and shape as input shape value. Raises: TypeError: If `shape` is neither tuple nor int. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> ones = ops.Ones() >>> output = ones((2, 2), mindspore.float32) >>> print(output) [[1. 1.] [1. 1.]] >>> output = ones((3, 3), mindspore.float32) >>> print(output) [[1. 1. 1.] [1. 1. 1.] [1. 1. 1.]] """ @prim_attr_register def __init__(self): """Initialize Ones""" class Zeros(Primitive): r""" Creates a tensor filled with value zeros. Creates a tensor with shape described by the first argument and fills it with value zeros in type of the second argument. Inputs: - **shape** (Union[tuple[int], int]) - The specified shape of output tensor. Only constant positive int is allowed. - **type** (mindspore.dtype) - The specified type of output tensor. Only constant value is allowed. Outputs: Tensor, has the same type and shape as input shape value. Raises: TypeError: If `shape` is neither int nor tuple. TypeError: If `shape` is a tuple whose elements are not all int. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> zeros = ops.Zeros() >>> output = zeros((2, 2), mindspore.float32) >>> print(output) [[0. 0.] [0. 0.]] """ @prim_attr_register def __init__(self): """Initialize Zeros""" class OnesLike(Primitive): """ Creates a new tensor. The values of all elements are 1. Returns a tensor of ones with the same shape and type as the input. Inputs: - **input_x** (Tensor) - Input tensor. The shape is :math:`(N,*)` where :math:`*` means, any number of additional dimensions. Outputs: Tensor, has the same shape and type as `input_x` but filled with ones. Raises: TypeError: If `input_x` is not a Tensor. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> oneslike = ops.OnesLike() >>> input_x = Tensor(np.array([[0, 1], [2, 1]]).astype(np.int32)) >>> output = oneslike(input_x) >>> print(output) [[1 1] [1 1]] """ @prim_attr_register def __init__(self): """Initialize OnesLike""" class ZerosLike(Primitive): """ Creates a new tensor. All elements value are 0. Returns a tensor of zeros with the same shape and data type as the input tensor. Inputs: - **input_x** (Tensor) - Input tensor. The data type is int32, int64, float16 or float32. The shape is :math:`(N,*)` where :math:`*` means, any number of additional dimensions. Outputs: Tensor, has the same shape and data type as `input_x` but filled with zeros. Raises: TypeError: If `input_x` is not a Tensor. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> zeroslike = ops.ZerosLike() >>> input_x = Tensor(np.array([[0, 1], [2, 1]]).astype(np.float32)) >>> output = zeroslike(input_x) >>> print(output) [[0. 0.] [0. 0.]] """ @prim_attr_register def __init__(self): """Initialize ZerosLike""" self.init_prim_io_names(inputs=['x'], outputs=['y']) class TupleToArray(PrimitiveWithInfer): """ Converts a tuple to a tensor. If the type of the first number in the tuple is integer, the data type of the output tensor is int. Otherwise, the data type of the output tensor is float. Inputs: - **input_x** (tuple) - A tuple of numbers. These numbers have the same type. Only constant value is allowed. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. Outputs: Tensor, if the input tuple contains `N` numbers, then the shape of the output tensor is (N,). Raises: TypeError: If `input_x` is not a tuple. ValueError: If length of `input_x` is less than or equal to 0. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = (1,2,3) >>> print(type(input_x)) <class 'tuple'> >>> output = ops.TupleToArray()(input_x) >>> print(type(output)) <class 'mindspore.common.tensor.Tensor'> >>> print(output) [1 2 3] """ @prim_attr_register def __init__(self): """Initialize TupleToArray""" def infer_value(self, x): validator.check_value_type("x", x, [tuple], self.name) validator.check("size of x", len(x), '', 0, Rel.GT, self.name) dtype = type(x[0]) for i, item in enumerate(x): validator.check_value_type(f"x[{i}]", item, [numbers.Number], self.name) if not all(isinstance(item, dtype) for item in x): raise TypeError(f"For \'{self.name}\', all elements of 'input_x' must be have same type.") if isinstance(x[0], int): ret = np.array(x, np.int32) else: ret = np.array(x, np.float32) return Tensor(ret) def __call__(self, x): args = list() if isinstance(x, range): args.append(tuple(x)) else: args.append(x) return _run_op(self, self.name, args) class ScalarToArray(PrimitiveWithInfer): """ Converts a scalar to a `Tensor`. Inputs: - **input_x** (Union[int, float]) - The input is a scalar. Only constant value is allowed. Outputs: Tensor. 0-D Tensor and the content is the input. Raises: TypeError: If `input_x` is neither int nor float. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> op = ops.ScalarToArray() >>> input_x = 1.0 >>> print(type(input_x)) <class 'float'> >>> output = op(input_x) >>> print(type(output)) <class 'mindspore.common.tensor.Tensor'> >>> print(output) 1.0 """ @prim_attr_register def __init__(self): pass def infer_value(self, x): validator.check_value_type("x", x, [int, float], self.name) if isinstance(x, int): ret = np.array(x, np.int32) else: ret = np.array(x, np.float32) return Tensor(ret) class ScalarToTensor(PrimitiveWithInfer): """ Converts a scalar to a `Tensor`, and converts the data type to the specified type. Inputs: - **input_x** (Union[int, float]) - The input is a scalar. Only constant value is allowed. - **dtype** (mindspore.dtype) - The target data type. Default: mindspore.float32. Only constant value is allowed. Outputs: Tensor. 0-D Tensor and the content is the input. Raises: TypeError: If `input_x` is neither int nor float. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> op = ops.ScalarToTensor() >>> data = 1 >>> output = op(data, mindspore.float32) >>> print(output) 1.0 """ @prim_attr_register def __init__(self): pass def infer_value(self, x, dtype=mstype.float32): validator.check_value_type("x", x, [int, float], self.name) validator.check_subclass("dtype", dtype, mstype.number, self.name) data_type = mstype.dtype_to_nptype(dtype) return Tensor(np.array(x, data_type)) class InvertPermutation(PrimitiveWithInfer): r""" Computes the inverse of an index permutation. This operator is mainly used to calculate the inverse of index permutation. It requires a 1-dimensional integer tensor x, which represents the index of a zero-based array, and exchanges each value with its index position. In other words, For output tensor y and input tensor x, this operation calculates the following values: :math:`y[x[i]] = i, \quad i \in [0, 1, \ldots, \text{len}(x)-1]`. Note: These values must include 0. There must be no duplicate values and the values can not be negative. Inputs: - **input_x** (Union(tuple[int], list[int])) - The input is constructed by multiple integers, i.e., :math:`(y_1, y_2, ..., y_S)` representing the indices. The values must include 0. There can be no duplicate values or negative values. Only constant value is allowed. The maximum value must be equal to length of input_x. Outputs: tuple[int]. It has the same length as the input. Raises: TypeError: If `input_x` is neither tuple nor list. TypeError: If element of `input_x` is not an int. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> invert = ops.InvertPermutation() >>> input_data = (3, 4, 0, 2, 1) >>> output = invert(input_data) >>> print(output) (2, 4, 3, 0, 1) """ @prim_attr_register def __init__(self): """Initialize InvertPermutation""" self.set_const_prim(True) def __infer__(self, x): x_shp = x['shape'] x_value = x['value'] if mstype.issubclass_(x['dtype'], mstype.tensor): raise ValueError(f"For \'{self.name}\", the value of "input_x" must be non-Tensor, but got {x["dtype"]}") if x_value is None: raise ValueError(f"For '{self.name}', the value of 'input_x' can not be None, but got {x_value}.") validator.check_value_type("shape", x_shp, [tuple, list], self.name) for shp in x_shp: if shp: x_rank = len(np.array(x_value, np.int64).shape) raise ValueError(f"For \'{self.name}\', the dimension of 'input_x' must be 1, but got {x_rank}.") for i, value in enumerate(x_value): validator.check_value_type("input[%d]" % i, value, [int], self.name) z = [x_value[i] for i in range(len(x_value))] z.sort() for i in range(1, len(z)): if z[i - 1] == z[i]: raise ValueError(f"For '{self.name}', the 'input_x' can not contain duplicate values, " f"but got duplicated {z[i]} in the 'input_x'.") validator.check(f'value min', min(x_value), '', 0, Rel.EQ, self.name) validator.check(f'value max', max(x_value), '', len(x_value) - 1, Rel.EQ, self.name) y = [None] * len(x_value) for i, value in enumerate(x_value): validator.check_value_type("input[%d]" % i, value, [int], self.name) validator.check(f'value', z[i], f'index', i, Rel.EQ, self.name) y[value] = i z.append(value) return {'shape': x_shp, 'dtype': x['dtype'], 'value': tuple(y)} class Argmax(PrimitiveWithInfer): """ Returns the indices of the maximum value of a tensor across the axis. If the shape of input tensor is :math:`(x_1, ..., x_N)`, the shape of the output tensor will be :math:`(x_1, ..., x_{axis-1}, x_{axis+1}, ..., x_N)`. Args: axis (int): Axis where the Argmax operation applies to. Default: -1. output_type (:class:`mindspore.dtype`): An optional data type of `mindspore.dtype.int32`. Default: `mindspore.dtype.int32`. Inputs: - **input_x** (Tensor) - Input tensor. :math:`(N,*)` where :math:`*` means, any number of additional dimensions. Support data type list as follows: - Ascend: Float16, Float32. - GPU: Float16, Float32. - CPU: Float16, Float32, Float64. Outputs: Tensor, indices of the max value of input tensor across the axis. Raises: TypeError: If `axis` is not an int. TypeError: If `output_type` is neither int32 nor int64. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Tensor(np.array([[1, 20, 5], [67, 8, 9], [130, 24, 15]]).astype(np.float32)) >>> output = ops.Argmax(output_type=mindspore.int32)(input_x) >>> print(output) [1 0 0] """ @prim_attr_register def __init__(self, axis=-1, output_type=mstype.int32): """Initialize Argmax""" self.init_prim_io_names(inputs=['x'], outputs=['output']) validator.check_value_type("axis", axis, [int], self.name) validator.check_types_same_and_valid({'output': output_type}, [mstype.int32], self.name) self.axis = axis self.add_prim_attr('output_type', output_type) def infer_shape(self, x_shape): axis = self.axis if axis is None: axis = 0 x_rank = len(x_shape) validator.check_int_range(axis, -x_rank, x_rank, Rel.INC_LEFT, "axis", self.name) axis = axis + x_rank if axis < 0 else axis ouput_shape = [x_shape[i] for i in range(x_rank) if i != axis] return ouput_shape def infer_dtype(self, x_dtype): validator.check_tensor_dtype_valid("input_x", x_dtype, [mstype.float16, mstype.float32, mstype.float64], self.name) return mstype.tensor_type(self.output_type) class Argmin(PrimitiveWithInfer): """ Returns the indices of the minimum value of a tensor across the axis. If the shape of input tensor is :math:`(x_1, ..., x_N)`, the shape of the output tensor is :math:`(x_1, ..., x_{axis-1}, x_{axis+1}, ..., x_N)`. Args: axis (int): Axis where the Argmin operation applies to. Default: -1. output_type (:class:`mindspore.dtype`): An optional data type of `mindspore.dtype.int32`. Default: `mindspore.dtype.int32`. Inputs: - **input_x** (Tensor) - Input tensor. The shape is :math:`(N,*)` where :math:`*` means, any number of additional dimensions. Outputs: Tensor, indices of the min value of input tensor across the axis. Raises: TypeError: If `axis` is not an int. TypeError: If `output_type` is neither int32 nor int64. Supported Platforms: ``Ascend`` Examples: >>> input_x = Tensor(np.array([2.0, 3.1, 1.2]), mindspore.float32) >>> index = ops.Argmin()(input_x) >>> print(index) 2 """ @prim_attr_register def __init__(self, axis=-1, output_type=mstype.int32): """Initialize Argmin""" self.init_prim_io_names(inputs=['x'], outputs=['output']) validator.check_value_type("axis", axis, [int], self.name) validator.check_type_name("output_type", output_type, [mstype.int32, mstype.int64], self.name) self.axis = axis self.add_prim_attr('output_type', output_type) def infer_shape(self, x_shape): axis = self.axis if axis is None: axis = 0 x_rank = len(x_shape) validator.check_int_range(axis, -x_rank, x_rank, Rel.INC_LEFT, "axis", self.name) axis = axis + x_rank if axis < 0 else axis ouput_shape = [x_shape[i] for i in range(x_rank) if i != axis] return ouput_shape def infer_dtype(self, x_dtype): validator.check_subclass("input_x", x_dtype, mstype.tensor, self.name) return mstype.tensor_type(self.output_type) class ArgMaxWithValue(PrimitiveWithInfer): """ Calculates the maximum value with the corresponding index. Calculates the maximum value along with the given axis for the input tensor. It returns the maximum values and indices. Note: In auto_parallel and semi_auto_parallel mode, the first output index can not be used. .. warning:: - If there are multiple maximum values, the index of the first maximum value is used. - The value range of "axis" is [-dims, dims - 1]. "dims" is the dimension length of "input_x". Args: axis (int): The dimension to reduce. Default: 0. keep_dims (bool): Whether to reduce dimension, if true, the output will keep same dimension with the input, the output will reduce dimension if false. Default: False. Inputs: - **input_x** (Tensor) - The input tensor, can be any dimension. Set the shape of input tensor as :math:`(x_1, x_2, ..., x_N)`. And the data type only support mindspore.float16 or float32. Outputs: tuple (Tensor), tuple of 2 tensors, containing the corresponding index and the maximum value of the input tensor. - index (Tensor) - The index for the maximum value of the input tensor. If `keep_dims` is true, the shape of output tensors is :math:`(x_1, x_2, ..., x_{axis-1}, 1, x_{axis+1}, ..., x_N)`. Otherwise, the shape is :math:`(x_1, x_2, ..., x_{axis-1}, x_{axis+1}, ..., x_N)`. - output_x (Tensor) - The maximum value of input tensor, with the same shape as index. Raises: TypeError: If `keep_dims` is not a bool. TypeError: If `axis` is not an int. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Tensor(np.array([0.0, 0.4, 0.6, 0.7, 0.1]), mindspore.float32) >>> index, output = ops.ArgMaxWithValue()(input_x) >>> print(index, output) 3 0.7 >>> index, output = ops.ArgMaxWithValue(keep_dims=True)(input_x) >>> print(index, output) [3] [0.7] """ @prim_attr_register def __init__(self, axis=0, keep_dims=False): """Initialize ArgMaxWithValue""" self.axis = axis self.keep_dims = keep_dims validator.check_value_type('keep_dims', keep_dims, [bool], self.name) validator.check_value_type('axis', axis, [int], self.name) def infer_shape(self, x_shape): axis = self.axis x_rank = len(x_shape) validator.check_int_range(axis, -x_rank, x_rank, Rel.INC_LEFT, "axis", self.name) ouput_shape = _infer_shape_reduce(x_shape, self.axis, self.keep_dims, self.name) return ouput_shape, ouput_shape def infer_dtype(self, x_dtype): validator.check_subclass("input_x", x_dtype, mstype.tensor, self.name) return mstype.tensor_type(mstype.int32), x_dtype class ArgMinWithValue(PrimitiveWithInfer): """ Calculates the minimum value with corresponding index, and returns indices and values. Calculates the minimum value along with the given axis for the input tensor. It returns the minimum values and indices. Note: In auto_parallel and semi_auto_parallel mode, the first output index can not be used. .. warning:: - If there are multiple minimum values, the index of the first minimum value is used. - The value range of "axis" is [-dims, dims - 1]. "dims" is the dimension length of "input_x". Args: axis (int): The dimension to reduce. Default: 0. keep_dims (bool): Whether to reduce dimension, if true the output will keep the same dimension as the input, the output will reduce dimension if false. Default: False. Inputs: - **input_x** (Tensor) - The input tensor, can be any dimension. Set the shape of input tensor as :math:`(x_1, x_2, ..., x_N)`. Outputs: tuple (Tensor), tuple of 2 tensors, containing the corresponding index and the minimum value of the input tensor. - index (Tensor) - The index for the minimum value of the input tensor. If `keep_dims` is true, the shape of output tensors is :math:`(x_1, x_2, ..., x_{axis-1}, 1, x_{axis+1}, ..., x_N)`. Otherwise, the shape is :math:`(x_1, x_2, ..., x_{axis-1}, x_{axis+1}, ..., x_N)`. - output_x (Tensor) - The minimum value of input tensor, with the same shape as index. Raises: TypeError: If `keep_dims` is not a bool. TypeError: If `axis` is not an int. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Tensor(np.array([0.0, 0.4, 0.6, 0.7, 0.1]), mindspore.float32) >>> output = ops.ArgMinWithValue()(input_x) >>> print(output) (Tensor(shape=[], dtype=Int32, value= 0), Tensor(shape=[], dtype=Float32, value= 0)) >>> output = ops.ArgMinWithValue(keep_dims=True)(input_x) >>> print(output) (Tensor(shape=[1], dtype=Int32, value= [0]), Tensor(shape=[1], dtype=Float32, value= [ 0.00000000e+00])) """ @prim_attr_register def __init__(self, axis=0, keep_dims=False): """Initialize ArgMinWithValue""" self.axis = axis self.keep_dims = keep_dims validator.check_value_type('keep_dims', keep_dims, [bool], self.name) validator.check_value_type('axis', axis, [int], self.name) def infer_shape(self, x_shape): axis = self.axis x_rank = len(x_shape) validator.check_int_range(axis, -x_rank, x_rank, Rel.INC_LEFT, "axis", self.name) ouput_shape = _infer_shape_reduce(x_shape, self.axis, self.keep_dims, self.name) return ouput_shape, ouput_shape def infer_dtype(self, x_dtype): validator.check_subclass("input_x", x_dtype, mstype.tensor, self.name) return mstype.tensor_type(mstype.int32), x_dtype class Tile(PrimitiveWithInfer): r""" Replicates a tensor with given multiples times. Creates a new tensor by replicating `input_x` `multiples` times. The i'th dimension of output tensor has `input_x.shape(i) * multiples[i]` elements, and the values of `input_x` are replicated `multiples[i]` times along the i'th dimension. Note: The length of `multiples` must be greater or equal to the length of dimension in `input_x`. Inputs: - **input_x** (Tensor) - 1-D or higher Tensor. Set the shape of input tensor as :math:`(x_1, x_2, ..., x_S)`. - **multiples** (tuple[int]) - The input tuple is constructed by multiple integers, i.e., :math:`(y_1, y_2, ..., y_S)`. The length of `multiples` cannot be smaller than the length of the shape of `input_x`. Only constant value is allowed. Outputs: Tensor, has the same data type as the `input_x`. - If the length of `multiples` is the same as the length of shape of `input_x`, then the shape of their corresponding positions can be multiplied, and the shape of Outputs is :math:`(x_1*y_1, x_2*y_2, ..., x_S*y_R)`. - If the length of `multiples` is larger than the length of shape of `input_x`, fill in multiple 1 in the length of the shape of `input_x` until their lengths are consistent. Such as set the shape of `input_x` as :math:`(1, ..., x_1, x_2, ..., x_S)`, then the shape of their corresponding positions can be multiplied, and the shape of Outputs is :math:`(1*y_1, ..., x_S*y_R)`. Raises: TypeError: If `multiples` is not a tuple or its elements are not all int. ValueError: If the elements of `multiples` are not all greater than 0. ValueError: If the length of `multiples` are smaller than the length of dimension in `input_x`. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> tile = ops.Tile() >>> input_x = Tensor(np.array([[1, 2], [3, 4]]), mindspore.float32) >>> multiples = (2, 3) >>> output = tile(input_x, multiples) >>> print(output) [[1. 2. 1. 2. 1. 2.] [3. 4. 3. 4. 3. 4.] [1. 2. 1. 2. 1. 2.] [3. 4. 3. 4. 3. 4.]] >>> multiples = (2, 3, 2) >>> output = tile(input_x, multiples) >>> print(output) [[[1. 2. 1. 2.] [3. 4. 3. 4.] [1. 2. 1. 2.] [3. 4. 3. 4.] [1. 2. 1. 2.] [3. 4. 3. 4.]] [[1. 2. 1. 2.] [3. 4. 3. 4.] [1. 2. 1. 2.] [3. 4. 3. 4.] [1. 2. 1. 2.] [3. 4. 3. 4.]]] """ @prim_attr_register def __init__(self): """Initialize Tile""" self.init_prim_io_names(inputs=['x', 'multiples'], outputs=['output']) def check_elim(self, base_tensor, multiplier): if not isinstance(base_tensor, Tensor): raise TypeError(f"For '{self.name}', the type of 'input_x' should be Tensor, " f"but got {type(base_tensor).__name__}.") if all(v == 1 for v in multiplier) and len(base_tensor.shape) >= len(multiplier): return (True, base_tensor) return (False, None) def __infer__(self, x, multiples): multiples_v = multiples['value'] if multiples_v is None: if len(multiples['shape']) != 1: raise ValueError(f'For \'{self.name}\' the dim of multiples must be 1.') rank = max(len(x['shape']), multiples['shape'][0]) out_shape = [-1] * rank # tile can't infer min/max shape if multiples_v is None return {'shape': out_shape, 'dtype': x['dtype'], 'value': None, 'min_shape': [1] * rank, 'max_shape': [1] * rank } x_shp = x['shape'] validator.check_value_type( "multiples", multiples_v, [tuple], self.name) for i, multiple in enumerate(multiples_v): validator.check_positive_int( multiple, "multiples[%d]" % i, self.name) validator.check_value_type( "x[\'dtype\']", x["dtype"], mstype.tensor_type, self.name) len_sub = len(multiples_v) - len(x_shp) multiples_w = None if len_sub == 0: multiples_w = multiples_v if len_sub > 0: for i in range(0, len_sub): x_shp.insert(0, 1) multiples_w = multiples_v elif len_sub < 0: raise ValueError(f"For '{self.name}', the length of 'multiples' can not be smaller than " f"the dimension of 'input_x', but got length of 'multiples': {len(multiples_v)} " f"and dimension of 'input_x': {len(x_shp)}.") for i, a in enumerate(multiples_w): x_shp[i] *= a value = None if x['value'] is not None: value = Tensor(np.tile(x['value'].asnumpy(), multiples_w)) return {'shape': x_shp, 'dtype': x['dtype'], 'value': value} class UnsortedSegmentSum(PrimitiveWithInfer): r""" Computes the sum of a tensor along segments. Calculates a tensor such that :math:`\text{output}[i] = \sum_{segment\_ids[j] == i} \text{data}[j, \ldots]`, where :math:`j` is a tuple describing the index of element in data. `segment_ids` selects which elements in data to sum up. Segment_ids does not need to be sorted, and it does not need to cover all values in the entire valid value range. The following figure shows the calculation process of UnsortedSegmentSum: .. image:: api_img/UnsortedSegmentSum.png Note: - If the segment_id i is absent in the segment_ids, then output[i] will be filled with 0. - On Ascend, if the value of segment_id is less than 0 or greater than the length of the input data shape, an execution error will occur. If the sum of the given segment_ids :math:`i` is empty, then :math:`\text{output}[i] = 0`. If the given segment_ids is negative, the value will be ignored. 'num_segments' must be equal to the number of different segment_ids. Inputs: - **input_x** (Tensor) - The shape is :math:`(x_1, x_2, ..., x_R)`. - **segment_ids** (Tensor) - Set the shape as :math:`(x_1, x_2, ..., x_N)`, where 0 < N <= R. - **num_segments** (int) - Set :math:`z` as num_segments. Outputs: Tensor, the shape is :math:`(z, x_{N+1}, ..., x_R)`. Raises: TypeError: If `num_segments` is not an int. ValueError: If length of shape of `segment_ids` is less than 1. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Tensor([1, 2, 3, 4], mindspore.float32) >>> segment_ids = Tensor([0, 0, 1, 2], mindspore.int32) >>> num_segments = 4 >>> output = ops.UnsortedSegmentSum()(input_x, segment_ids, num_segments) >>> print(output) [3. 3. 4. 0.] >>> input_x = Tensor([1, 2, 3, 4, 2, 5], mindspore.float32) >>> segment_ids = Tensor([0, 0, 1, 2, 3, 4], mindspore.int32) >>> num_segments = 6 >>> output = ops.UnsortedSegmentSum()(input_x, segment_ids, num_segments) >>> print(output) [3. 3. 4. 2. 5. 0.] """ @prim_attr_register def __init__(self): """Initialize UnsortedSegmentSum""" self.init_prim_io_names(inputs=['x', 'segment_ids', 'num_segments'], outputs=['y']) def __infer__(self, x, segment_ids, num_segments): x_type = x['dtype'] x_shp = x['shape'] validator.check_subclass("input_x", x_type, mstype.tensor, self.name) validator.check_value_type("x_shape", x_shp, [list], self.name) x_shp_len = len(x_shp) validator.check_positive_int(x_shp_len, "rank of input_x", self.name) segment_ids_shp = segment_ids['shape'] segment_ids_type = segment_ids['dtype'] validator.check_subclass("segment_ids", segment_ids_type, mstype.tensor, self.name) validator.check_value_type("segment_ids", segment_ids_shp, [list], self.name) segment_ids_shp_len = len(segment_ids_shp) validator.check_positive_int(segment_ids_shp_len, "rank of segment_ids", self.name) validator.check(f'rank of input_x', len(x_shp), 'rank of segments_id', len(segment_ids_shp), Rel.GE, self.name) if -1 not in x_shp and -1 not in segment_ids_shp: # only validate when both shapes fully known for i, value in enumerate(segment_ids_shp): validator.check("ids[%d]" % i, value, 'input[%d]' % i, x_shp[i], Rel.EQ, self.name) num_segments_v = num_segments['value'] num_segments_type = num_segments['dtype'] validator.check_subclass("num_segments", num_segments_type, [mstype.tensor, mstype.number], self.name) if isinstance(num_segments_type, type(mstype.tensor)): validator.check_tensor_dtype_valid("num_segments", num_segments_type, [mstype.int32, mstype.int64], self.name) shp = [-1] else: validator.check_value_type('num_segments', num_segments_v, [int], self.name) validator.check_positive_int(num_segments_v, "num_segments", self.name) shp = [num_segments_v] shp += x_shp[segment_ids_shp_len:] if "max_value" in num_segments and "min_value" in num_segments: output_max_shape = list(num_segments['max_value']) output_min_shape = list(num_segments['min_value']) else: if isinstance(num_segments_type, type(mstype.tensor)): raise ValueError(f"For '{self.name}', the dtype of 'num_segments' only support int type " f"when it is not a dynamic value, but got type of 'num_segments': " f"{num_segments_type}.") output_max_shape = [num_segments_v] output_min_shape = [num_segments_v] if 'max_shape' in x and 'min_shape' in x: max_output_incoming = x['max_shape'] min_output_incoming = x['min_shape'] else: max_output_incoming = x_shp min_output_incoming = x_shp output_max_shape += max_output_incoming[segment_ids_shp_len:] output_min_shape += min_output_incoming[segment_ids_shp_len:] return {'shape': shp, 'max_shape': output_max_shape, 'min_shape': output_min_shape, 'dtype': mstype.tensor_type(x_type.element_type()), 'value': None} class UnsortedSegmentMin(PrimitiveWithCheck): r""" Computes the minimum of a tensor along segments. The following figure shows the calculation process of UnsortedSegmentMin: .. image:: api_img/UnsortedSegmentMin.png .. math:: \text { output }_i=\text{min}_{j \ldots} \text { data }[j \ldots] where :math:`min` over tuples :math:`j...` such that :math:`segment_ids[j...] == i`. Note: If the segment_id i is absent in the segment_ids, then output[i] will be filled with the maximum value of the input_x's type. The `segment_ids` must be non-negative tensor. Inputs: - **input_x** (Tensor) - The shape is :math:`(x_1, x_2, ..., x_R)`. The data type must be float16, float32 or int32. - **segment_ids** (Tensor) - A `1-D` tensor whose shape is :math:`(x_1)`, the value must be non-negative tensor. The data type must be int32. - **num_segments** (int) - The value specifies the number of distinct `segment_ids`. Outputs: Tensor, set the number of `num_segments` as `N`, the shape is :math:`(N, x_2, ..., x_R)`. Raises: TypeError: If `num_segments` is not an int. ValueError: If length of shape of `segment_ids` is not equal to 1. Supported Platforms: ``Ascend`` ``GPU`` Examples: >>> input_x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [4, 2, 1]]).astype(np.float32)) >>> segment_ids = Tensor(np.array([0, 1, 1]).astype(np.int32)) >>> num_segments = 2 >>> unsorted_segment_min = ops.UnsortedSegmentMin() >>> output = unsorted_segment_min(input_x, segment_ids, num_segments) >>> print(output) [[1. 2. 3.] [4. 2. 1.]] """ @prim_attr_register def __init__(self): """Initialize UnsortedSegmentMin""" self.init_prim_io_names(inputs=['x', 'segment_ids', 'num_segments'], outputs=['y']) def __check__(self, x, segment_ids, num_segments): x_shape = x['shape'] segment_ids_shape = segment_ids['shape'] valid_type = [mstype.float16, mstype.float32, mstype.int32] validator.check_tensor_dtype_valid("x", x['dtype'], valid_type, self.name) validator.check_tensor_dtype_valid("segment_ids", segment_ids['dtype'], [mstype.int32], self.name) validator.check_equal_int(len(segment_ids_shape), 1, "rank of segment_ids_shape", self.name) num_segments_type = num_segments['dtype'] validator.check_subclass("num_segments", num_segments_type, [mstype.number], self.name) if -1 not in x_shape and -1 not in segment_ids_shape: # only validate when both shapes fully known validator.check(f'first shape of input_x', x_shape[0], 'length of segments_id', segment_ids_shape[0], Rel.EQ, self.name) num_segments_v = num_segments['value'] validator.check_value_type('num_segments', num_segments_v, [int], self.name) validator.check_positive_int(num_segments_v, "num_segments", self.name) class UnsortedSegmentMax(PrimitiveWithCheck): r""" Computes the maximum along segments of a tensor. The following figure shows the calculation process of UnsortedSegmentMax: .. image:: api_img/UnsortedSegmentMax.png .. math:: \text { output }_i=\text{max}_{j \ldots} \text { data }[j \ldots] where :math:`max` over tuples :math:`j...` such that :math:`segment\_ids[j...] == i`. Note: If the segment_id i is absent in the segment_ids, then output[i] will be filled with the minimum value of the input_x's type. Inputs: - **input_x** (Tensor) - The shape is :math:`(x_1, x_2, ..., x_R)`. The data type must be float16, float32 or int32. - **segment_ids** (Tensor) - A `1-D` tensor whose shape is :math:`(x_1)`, the value must be non-negative tensor. The data type must be int32. - **num_segments** (int) - The value specifies the number of distinct `segment_ids`. Outputs: Tensor, set the number of `num_segments` as `N`, the shape is :math:`(N, x_2, ..., x_R)`. Raises: TypeError: If `num_segments` is not an int. ValueError: If length of shape of `segment_ids` is not equal to 1. Supported Platforms: ``Ascend`` ``GPU`` Examples: >>> # case 1: Only have two num_segments, where is 0 and 1, and segment_ids=[0, 1, 1] >>> # num_segments = 2 indicates that there are two types of segment_id, >>> # the first number '0' in [0, 1, 1] indicates input_x[0], >>> # the second number '1' in [0, 1, 1] indicates input_x[1], >>> # the third number '1' in [0, 1, 1] indicates input_x[2], >>> # input_x[0], which is [1, 2, 3] will not be compared to other segment_id. >>> # Only the same segment_id will be compared. >>> from mindspore import Tensor >>> from mindspore import ops >>> import numpy as np >>> input_x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [4, 2, 1]]).astype(np.float32)) >>> segment_ids = Tensor(np.array([0, 1, 1]).astype(np.int32)) >>> num_segments = 2 >>> unsorted_segment_max = ops.UnsortedSegmentMax() >>> output = unsorted_segment_max(input_x, segment_ids, num_segments) >>> print(output) [[1. 2. 3.] [4. 5. 6.]] >>> >>> # case 2: The segment_ids=[0, 0, 1, 1]. >>> # [1, 2, 3] will compare with [4, 2, 0], >>> # and [4, 5, 6] will compare with [4, 2, 1]. >>> input_x = Tensor(np.array([[1, 2, 3], [4, 2, 0], [4, 5, 6], [4, 2, 1]]).astype(np.float32)) >>> segment_ids = Tensor(np.array([0, 0, 1, 1]).astype(np.int32)) >>> num_segments = 2 >>> unsorted_segment_max = ops.UnsortedSegmentMax() >>> output = unsorted_segment_max(input_x, segment_ids, num_segments) >>> print(input_x.shape) (4, 3) >>> print(output) [[4. 2. 3.] [4. 5. 6.]] >>> # case 3: If the input_x have three dimensions even more, what will happen? >>> # The shape of input_x is (2, 4, 3), >>> # and the length of segment_ids should be the same as the first dimension of input_x. >>> # Because the segment_ids are different, input_x[0] will not be compared to input_x[1]. >>> input_x = Tensor(np.array([[[1, 2, 3], [4, 2, 0], [4, 5, 6], [4, 2, 1]], ... [[1, 2, 3], [4, 2, 0], [4, 5, 6], [4, 2, 1]]]).astype(np.float32)) >>> segment_ids = Tensor(np.array([0, 1]).astype(np.int32)) >>> num_segments = 2 >>> unsorted_segment_max = ops.UnsortedSegmentMax() >>> output = unsorted_segment_max(input_x, segment_ids, num_segments) >>> print(input_x.shape) (2, 4, 3) >>> print(output) [[[1. 2. 3.] [4. 2. 0.] [4. 5. 6.] [4. 2. 1.]] [[1. 2. 3.] [4. 2. 0.] [4. 5. 6.] [4. 2. 1.]]] >>> # case 4: It has the same input with the 3rd case. >>> # Because num_segments is equal to 2, there are two segment_ids, but currently only one 0 is used. >>> # the segment_id i is absent in the segment_ids, then output[i] will be filled with >>> # the smallest possible value of the input_x's type. >>> segment_ids = Tensor(np.array([0, 0]).astype(np.int32)) >>> output = unsorted_segment_max(input_x, segment_ids, num_segments) >>> print(output) [[[ 1.0000000e+00 2.0000000e+00 3.0000000e+00] [ 4.0000000e+00 2.0000000e+00 0.0000000e+00] [ 4.0000000e+00 5.0000000e+00 6.0000000e+00] [ 4.0000000e+00 2.0000000e+00 1.0000000e+00]] [[-3.4028235e+38 -3.4028235e+38 -3.4028235e+38] [-3.4028235e+38 -3.4028235e+38 -3.4028235e+38] [-3.4028235e+38 -3.4028235e+38 -3.4028235e+38] [-3.4028235e+38 -3.4028235e+38 -3.4028235e+38]]] """ @prim_attr_register def __init__(self): """Initialize UnsortedSegmentMax""" self.init_prim_io_names(inputs=['x', 'segment_ids', 'num_segments'], outputs=['y']) def __check__(self, x, segment_ids, num_segments): x_shape = x['shape'] segment_ids_shape = segment_ids['shape'] valid_type = [mstype.float16, mstype.float32, mstype.int32] validator.check_tensor_dtype_valid("x", x['dtype'], valid_type, self.name) validator.check_tensors_dtypes_same_and_valid({"segment_ids": segment_ids['dtype']}, [mstype.int32, mstype.int64], self.name) validator.check_equal_int(len(segment_ids_shape), 1, "rank of segment_ids_shape", self.name) num_segments_type = num_segments['dtype'] validator.check_subclass("num_segments", num_segments_type, [mstype.number], self.name) if -1 not in x_shape and -1 not in segment_ids_shape: # only validate when both shapes fully known validator.check(f'first shape of input_x', x_shape[0], 'length of segments_id', segment_ids_shape[0], Rel.EQ, self.name) num_segments_v = num_segments['value'] validator.check_value_type('num_segments', num_segments_v, [int], self.name) validator.check_positive_int(num_segments_v, "num_segments", self.name) class UnsortedSegmentProd(PrimitiveWithInfer): """ Computes the product of a tensor along segments. The following figure shows the calculation process of UnsortedSegmentProd: .. image:: api_img/UnsortedSegmentProd.png Inputs: - **input_x** (Tensor) - The shape is :math:`(x_1, x_2, ..., x_R)`. With float16, float32 or int32 data type. - **segment_ids** (Tensor) - A `1-D` tensor whose shape is :math:`(x_1)`, the value must be non-negative tensor. Data type must be int32. - **num_segments** (int) - The value specifies the number of distinct `segment_ids`, must be greater than 0. Outputs: Tensor, set the number of `num_segments` as `N`, the shape is :math:`(N, x_2, ..., x_R)`. Raises: TypeError: If `num_segments` is not an int. ValueError: If length of shape of `segment_ids` is not equal to 1. Supported Platforms: ``Ascend`` Examples: >>> input_x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [4, 2, 1]]).astype(np.float32)) >>> segment_ids = Tensor(np.array([0, 1, 0]).astype(np.int32)) >>> num_segments = 2 >>> unsorted_segment_prod = ops.UnsortedSegmentProd() >>> output = unsorted_segment_prod(input_x, segment_ids, num_segments) >>> print(output) [[4. 4. 3.] [4. 5. 6.]] """ @prim_attr_register def __init__(self): """Initialize UnsortedSegmentProd""" self.init_prim_io_names(inputs=['x', 'segment_ids', 'num_segments'], outputs=['y']) def __infer__(self, x, segment_ids, num_segments): x_type = x['dtype'] x_shape = x['shape'] segment_ids_shape = segment_ids['shape'] validator.check_subclass("input_x", x_type, mstype.tensor, self.name) validator.check_value_type("x_shape", x_shape, [list], self.name) valid_type = [mstype.float16, mstype.float32, mstype.int32] validator.check_tensor_dtype_valid("x", x['dtype'], valid_type, self.name) validator.check_tensor_dtype_valid("segment_ids", segment_ids['dtype'], [mstype.int32], self.name) validator.check_equal_int(len(segment_ids_shape), 1, "rank of segment_ids_shape", self.name) validator.check(f'first shape of input_x', x_shape[0], 'length of segments_id', segment_ids_shape[0], Rel.EQ, self.name) num_segments_v = num_segments['value'] validator.check_value_type('num_segments', num_segments_v, [int], self.name) validator.check_positive_int(num_segments_v, "num_segments", self.name) segment_ids_shape_len = len(segment_ids_shape) out_shape = [num_segments_v] out_shape += x_shape[segment_ids_shape_len:] out = {'shape': out_shape, 'dtype': mstype.tensor_type(x_type.element_type()), 'value': None} return out class Concat(PrimitiveWithInfer): r""" Connect tensor in the specified axis. Connect input tensors along with the given axis. The input data is a tuple of tensors. These tensors have the same rank `R`. Set the given axis as `m`, and :math:`0 \le m < R`. Set the number of input tensors as `N`. For the :math:`i`-th tensor :math:`t_i`, it has the shape of :math:`(x_1, x_2, ..., x_{mi}, ..., x_R)`. :math:`x_{mi}` is the :math:`m`-th dimension of the :math:`i`-th tensor. Then, the shape of the output tensor is .. math:: (x_1, x_2, ..., \sum_{i=1}^Nx_{mi}, ..., x_R) .. warning:: The value range of "axis" is [-dims, dims - 1]. "dims" is the dimension length of "input_x". Args: axis (int): The specified axis. Default: 0. Inputs: - **input_x** (tuple, list) - A tuple or a list of input tensors. Suppose there are two tensors in this tuple or list, namely x1 and x2. To perform `Concat` in the axis 0 direction, except for the 0th axis, all other axes should be equal, that is, :math:`x1.shape[1] == x2.shape[1], x1.shape[2] == x2.shape[2], ..., x1.shape[R] == x2.shape[R]`, where the :math:`R` indicates the last axis. Outputs: - Tensor, the shape is :math:`(x_1, x_2, ..., \sum_{i=1}^Nx_{mi}, ..., x_R)`. The data type is the same with `input_x`. Raises: TypeError: If `axis` is not an int. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x1 = Tensor(np.array([[0, 1], [2, 1]]).astype(np.float32)) >>> input_x2 = Tensor(np.array([[0, 1], [2, 1]]).astype(np.float32)) >>> op = ops.Concat() >>> output = op((input_x1, input_x2)) >>> print(output) [[0. 1.] [2. 1.] [0. 1.] [2. 1.]] >>> op = ops.Concat(1) >>> output = op((input_x1, input_x2)) >>> print(output) [[0. 1. 0. 1.] [2. 1. 2. 1.]] """ @prim_attr_register def __init__(self, axis=0): """Initialize Concat""" validator.check_value_type("axis", axis, [int], self.name) def __infer__(self, input_x): axis = self.axis x_shp = input_x['shape'] x_type = input_x['dtype'] _, all_shp, _ = get_concat_offset(x_shp, x_type, axis, self.name) self.add_prim_attr('inputNums', len(x_shp)) ret_shp = x_shp[0].copy() value = None if input_x['value'] is not None: value = Tensor(np.concatenate([x.asnumpy() for x in input_x['value']], axis=axis)) ret_shp[axis] = all_shp out = {'shape': ret_shp, 'dtype': x_type[0], 'value': value} if -1 in x_shp[0]: x_min_shp = input_x['min_shape'] ret_min_shp = x_min_shp[0].copy() ret_min_shp[axis] = 0 for all_min_shp in x_min_shp: ret_min_shp[axis] += all_min_shp[axis] out['min_shape'] = ret_min_shp x_max_shp = input_x['max_shape'] ret_max_shp = x_max_shp[0].copy() ret_max_shp[axis] = 0 for all_max_shp in x_max_shp: ret_max_shp[axis] += all_max_shp[axis] out['max_shape'] = ret_max_shp return out class ParallelConcat(PrimitiveWithInfer): r""" Concats tensor in the first dimension. Concats input tensors along with the first dimension. The difference between Concat and ParallelConcat is that Concat requires all of the inputs be computed before the operation will begin but doesn't require that the input shapes be known during graph construction. Parallel concat will copy pieces of the input into the output as they become available, in some situations this can provide a performance benefit. Note: The input tensors are all required to have size 1 in the first dimension. Inputs: - **values** (tuple, list) - A tuple or a list of input tensors. The data type and shape of these tensors must be the same. The data type is Number except float64. Outputs: Tensor, data type is the same as `values`. Raises: ValueError: If length of shape of `values` is less than 1. ValueError: The data type and shape of these tensors are not the same. Supported Platforms: ``Ascend`` Examples: >>> data1 = Tensor(np.array([[0, 1]]).astype(np.int32)) >>> data2 = Tensor(np.array([[2, 1]]).astype(np.int32)) >>> op = ops.ParallelConcat() >>> output = op((data1, data2)) >>> print(output) [[0 1] [2 1]] """ @prim_attr_register def __init__(self): """Initialize ParallelConcat""" def __infer__(self, values): x_shp = values['shape'] x_type = values['dtype'] validator.check_int(len(x_shp), 1, Rel.GE, f'x_shp length', self.name) args = {f"x_type[{i}]": elem for i, elem in enumerate(x_type)} validator.check_tensors_dtypes_same_and_valid(args, mstype.number_type + (mstype.bool_,), self.name) first_elem = x_shp[0] for i, elem in enumerate(x_shp[1:]): j = i + 1 validator.check_equal_int(elem[0], 1, f'x_shp[{j}][0]', self.name) validator.check(f"x_shp[0] shape", first_elem, f"x_shp[{j}] shape", elem, Rel.EQ, self.name) ret_shp = x_shp[0].copy() ret_shp[0] = len(x_shp) self.add_prim_attr('shape', ret_shp) self.add_prim_attr('N', len(x_shp)) out = {'shape': ret_shp, 'dtype': x_type[0], 'value': None} return out def _get_stack_shape(x_shape, x_type, axis, prim_name): """for stack output shape""" validator.check_value_type("shape", x_shape, [tuple, list], prim_name) validator.check_int(len(x_shape), 1, Rel.GE, "len of input_x", prim_name) validator.check_subclass("input_x[0]", x_type[0], mstype.tensor, prim_name) rank_base = len(x_shape[0]) n = len(x_shape) out_shape = x_shape[0] validator.check_int_range(axis, -rank_base - 1, rank_base, Rel.INC_BOTH, 'axis', prim_name) if axis < 0: axis = axis + rank_base + 1 for i in range(1, n): validator.check('x_type[%d]' % i, x_type[i], 'base', x_type[0], Rel.EQ, prim_name, TypeError) if x_shape[i] != x_shape[0]: raise ValueError(f"For \'{prim_name}\' element {i} shape in input can not pack with first element") out_shape.insert(axis, n) return out_shape class Pack(PrimitiveWithInfer): """ Same as operator Stack. Pack will be deprecated in the future. Please use Stack instead. """ @deprecated("1.1", "Stack", True) @prim_attr_register def __init__(self, axis=0): """Initialize Pack""" validator.check_value_type("axis", axis, [int], self.name) self.axis = axis def __infer__(self, value): x_shape = value['shape'] x_type = value['dtype'] self.add_prim_attr('num', len(x_shape)) all_shape = _get_stack_shape(x_shape, x_type, self.axis, self.name) out = {'shape': all_shape, 'dtype': x_type[0], 'value': None} return out class Stack(PrimitiveWithInfer): r""" Stacks a list of tensors in specified axis. Stacks the list of input tensors with the same rank `R`, output is a tensor of rank `(R+1)`. Given input tensors of shape :math:`(x_1, x_2, ..., x_R)`. Set the number of input tensors as `N`. If :math:`0 \le axis`, the shape of the output tensor is :math:`(x_1, x_2, ..., x_{axis}, N, x_{axis+1}, ..., x_R)`. Args: axis (int): Dimension to stack. Default: 0. Negative values wrap around. The range is [-(R+1), R+1). Inputs: - **input_x** (Union[tuple, list]) - A Tuple or list of Tensor objects with the same shape and type. Outputs: Tensor. A stacked Tensor with the same type as `input_x`. Raises: TypeError: If the data types of elements in `input_x` are not the same. ValueError: If the length of `input_x` is not greater than 1; or if axis is out of the range [-(R+1), R+1); or if the shapes of elements in input_x are not the same. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> data1 = Tensor(np.array([0, 1]).astype(np.float32)) >>> data2 = Tensor(np.array([2, 3]).astype(np.float32)) >>> stack = ops.Stack() >>> output = stack([data1, data2]) >>> print(output) [[0. 1.] [2. 3.]] """ @prim_attr_register def __init__(self, axis=0): """Initialize Stack""" validator.check_value_type("axis", axis, [int], self.name) self.axis = axis def __infer__(self, value): x_shape = value['shape'] x_type = value['dtype'] self.add_prim_attr('num', len(x_shape)) all_shape = _get_stack_shape(x_shape, x_type, self.axis, self.name) tuple_value = value['value'] input_array = [] infered_value = None if tuple_value is not None: for item in tuple_value: npy_item = item.asnumpy() input_array.append(npy_item) infered_value = Tensor(np.stack(input_array, axis=self.axis)) out = {'shape': all_shape, 'dtype': x_type[0], 'value': infered_value} return out class Unpack(PrimitiveWithInfer): """ Same as operator Unstack. Unpack will be deprecated in the future. Please use Unstack instead. """ @deprecated("1.1", "Unstack", True) @prim_attr_register def __init__(self, axis=0): """Initialize Unpack""" validator.check_value_type("axis", axis, [int], self.name) self.axis = axis def __infer__(self, x): validator.check_subclass("x", x['dtype'], mstype.tensor, self.name) x_shape = list(x['shape']) dim = len(x_shape) validator.check_int_range(self.axis, -dim, dim, Rel.INC_LEFT, 'axis value', self.name) if self.axis < 0: self.axis = self.axis + dim output_num = x_shape[self.axis] validator.check_value_type("num", output_num, [int], self.name) validator.check_positive_int(output_num, "output_num", self.name) self.add_prim_attr('num', output_num) output_valid_check = x_shape[self.axis] - output_num validator.check_int(output_valid_check, 0, Rel.EQ, "The dimension which to unstack divides output_num", self.name) out_shapes = [] out_dtypes = [] out_shape = x_shape[:self.axis] + x_shape[self.axis + 1:] for _ in range(output_num): out_shapes.append(tuple(out_shape)) out_dtypes.append(x['dtype']) out_shapes = tuple(out_shapes) out_dtypes = tuple(out_dtypes) out = {'shape': out_shapes, 'dtype': out_dtypes, 'value': None} return out class Unstack(PrimitiveWithInfer): r""" Unstacks tensor in specified axis. Unstacks a tensor of rank `R` along axis dimension, output tensors will have rank `(R-1)`. Given a tensor of shape :math:`(x_1, x_2, ..., x_R)`. If :math:`0 \le axis`, the shape of tensor in output is :math:`(x_1, x_2, ..., x_{axis}, x_{axis+2}, ..., x_R)`. This is the opposite of pack. Args: axis (int): Dimension along which to pack. Default: 0. Negative values wrap around. The range is [-R, R). Inputs: - **input_x** (Tensor) - The shape is :math:`(x_1, x_2, ..., x_R)`. A tensor to be unstacked and the rank of the tensor must be greater than 0. Outputs: A tuple of tensors, the shape of each objects is the same. Raises: ValueError: If axis is out of the range [-len(input_x.shape), len(input_x.shape)). Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> unstack = ops.Unstack() >>> input_x = Tensor(np.array([[1, 1, 1, 1], [2, 2, 2, 2]])) >>> output = unstack(input_x) >>> print(output) (Tensor(shape=[4], dtype=Int64, value= [1, 1, 1, 1]), Tensor(shape=[4], dtype=Int64, value= [2, 2, 2, 2])) """ @prim_attr_register def __init__(self, axis=0): """Initialize Unstack""" validator.check_value_type("axis", axis, [int], self.name) self.axis = axis def __infer__(self, x): validator.check_subclass("x", x['dtype'], mstype.tensor, self.name) x_shape = list(x['shape']) dim = len(x_shape) validator.check_int_range(self.axis, -dim, dim, Rel.INC_LEFT, 'axis value', self.name) if self.axis < 0: self.axis = self.axis + dim output_num = x_shape[self.axis] validator.check_value_type("num", output_num, [int], self.name) validator.check_positive_int(output_num, "output_num", self.name) self.add_prim_attr('num', output_num) output_valid_check = x_shape[self.axis] - output_num validator.check_int(output_valid_check, 0, Rel.EQ, "The dimension which to unstack divides output_num", self.name) out_shapes = [] out_dtypes = [] out_shape = x_shape[:self.axis] + x_shape[self.axis + 1:] for _ in range(output_num): out_shapes.append(tuple(out_shape)) out_dtypes.append(x['dtype']) out_shapes = tuple(out_shapes) out_dtypes = tuple(out_dtypes) out = {'shape': out_shapes, 'dtype': out_dtypes, 'value': None} return out class Slice(PrimitiveWithInfer): """ Slices a tensor in the specified shape. Slice the tensor `input_x` in shape of `size` and starting at the location specified by `begin`, The slice `begin` represents the offset in each dimension of `input_x`, The slice `size` represents the size of the output tensor. Note that `begin` is zero-based and `size` is one-based. If `size[i]` is -1, all remaining elements in dimension i are included in the slice. This is equivalent to setting :math:`size[i] = input_x.shape(i) - begin[i]`. Inputs: - **input_x** (Tensor): The target tensor. The shape is :math:`(N,*)` where :math:`*` means, any number of additional dimensions. - **begin** (Union[tuple, list]): The beginning of the slice. Only constant value(>=0) is allowed. - **size** (Union[tuple, list]): The size of the slice. Only constant value is allowed. Outputs: Tensor, the shape is : input `size`, the data type is the same as `input_x`. Raises: TypeError: If `begin` or `size` is neither tuple nor list. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> data = Tensor(np.array([[[1, 1, 1], [2, 2, 2]], ... [[3, 3, 3], [4, 4, 4]], ... [[5, 5, 5], [6, 6, 6]]]).astype(np.int32)) >>> slice_op = ops.Slice() >>> output = slice_op(data, (1, 0, 0), (1, 1, 3)) >>> print(output) [[[3 3 3]]] >>> output = slice_op(data, (1, 0, 0), (1, 1, 2)) >>> print(output) [[[3 3]]] >>> output = slice_op(data, (1, 0, 0), (1, 1, 1)) >>> print(output) [[[3]]] >>> output = slice_op(data, (1, 1, 0), (1, 1, 3)) >>> print(output) [[[4 4 4]]] >>> output = slice_op(data, (1, 0, 1), (1, 1, 2)) >>> print(output) [[[3 3]]] """ @prim_attr_register def __init__(self): """Initialize slice""" self.init_prim_io_names(inputs=['x', 'begin', 'size'], outputs=['output']) def __infer__(self, x, begin, size): x_shape = x['shape'] x_shp_len = len(x_shape) begin_v, size_v = begin['value'], size['value'] if begin_v is None or size_v is None: # if size_v is not None and begin_v is None, it should be also a dynamic output shape. if size_v is None: if size['shape'][0] < 0: raise ValueError(f"For '{self.name}', the size shape haven't support dynamic yet.") out_shape = [-1] * size['shape'][0] else: out_shape = [-1] * len(size_v) if 'max_shape' in x: max_shape = x['max_shape'] min_shape = x['min_shape'] else: min_shape = x['shape'] max_shape = x['shape'] return {'shape': out_shape, 'dtype': x['dtype'], 'value': None, 'min_shape': min_shape, 'max_shape': max_shape} validator.check_valid_input('begin', begin['value'], self.name) validator.check_valid_input('size', size['value'], self.name) validator.check_value_type("input begin", begin_v, [tuple, list], self.name) validator.check_value_type("input size", size_v, [tuple, list], self.name) for key, value in zip(('begin', 'size'), (begin_v, size_v)): validator.check(f'len of {key}', len(value), 'len x\'s dim', x_shp_len) size_v = list(size_v) if -1 not in x_shape: for i in range(x_shp_len): if size_v[i] == -1: size_v[i] = x_shape[i] - begin_v[i] validator.check_positive_int(size_v[i], f'input size[{i}]') validator.check_non_negative_int(begin_v[i], f'input begin[{i}]') if x_shape[i] < begin_v[i] + size_v[i]: y = begin_v[i] + size_v[i] raise ValueError(f"For '{self.name}', the sliced shape can not be greater than origin shape, " f"but got sliced shape is {y}, and origin shape is {x_shape}.") return {'shape': size_v, 'dtype': x['dtype'], 'value': None} class ReverseV2(PrimitiveWithInfer): """ Reverses specific dimensions of a tensor. .. warning:: The value range of "axis" is [-dims, dims - 1]. "dims" is the dimension length of "input_x". Args: axis (Union[tuple(int), list(int)): The indices of the dimensions to reverse. Inputs: - **input_x** (Tensor) - The target tensor. The data type is Number except float64. The shape is :math:`(N,*)` where :math:`*` means, any number of additional dimensions. Outputs: Tensor, has the same shape and type as `input_x`. Raises: TypeError: If `axis` is neither list nor tuple. TypeError: If element of `axis` is not an int. Supported Platforms: ``Ascend`` ``GPU`` Examples: >>> input_x = Tensor(np.array([[1, 2, 3, 4], [5, 6, 7, 8]]), mindspore.int32) >>> op = ops.ReverseV2(axis=[1]) >>> output = op(input_x) >>> print(output) [[4 3 2 1] [8 7 6 5]] >>> op = ops.ReverseV2(axis=[1, 0]) >>> output = op(input_x) >>> print(output) [[8 7 6 5] [4 3 2 1]] """ @prim_attr_register def __init__(self, axis): """Initialize ReverseV2.""" validator.check_value_type('axis', axis, [list, tuple], self.name) for i, each in enumerate(axis): validator.check_value_type(f'axis[{i}]', each, [int], self.name) self.axis = axis self.init_prim_io_names(inputs=['x'], outputs=['output']) def infer_shape(self, x_shape): dim = len(x_shape) for i, each in enumerate(self.axis): validator.check_int_range(each, -dim, dim, Rel.INC_LEFT, f'axis[{i}]', self.name) normalized_axis = [] for i, v in enumerate(self.axis): if v < 0: normalized_axis.append(v + dim) else: normalized_axis.append(v) if len(normalized_axis) != len(set(normalized_axis)): duplicated = [item for item, count in Counter(normalized_axis).items() if count > 1] raise ValueError(f"For '{self.name}', the 'axis' cannot contain duplicate dimensions," f" but got duplicated elements {duplicated}.") return x_shape def infer_dtype(self, x_dtype): validator.check_tensor_dtype_valid('x', x_dtype, (mstype.bool_,) + mstype.number_type, self.name) return x_dtype class Rint(Primitive): """ Returns an integer that is closest to x element-wise. Inputs: - **input_x** (Tensor) - The target tensor, which must be one of the following types: float16, float32. The shape is :math:`(N,*)` where :math:`*` means, any number of additional dimensions. Outputs: Tensor, has the same shape and type as `input_x`. Raises: TypeError: If dtype of `input_x` is not in [float16, float32, float64]. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Tensor(np.array([-1.6, -0.1, 1.5, 2.0]), mindspore.float32) >>> op = ops.Rint() >>> output = op(input_x) >>> print(output) [-2. 0. 2. 2.] >>> input_x = Tensor(np.array([[-2.0, -1.9, -1.8, -1.7, -1.6], ... [-2.0, -1.9, -1.8, -1.7, -1.6]]), mindspore.float32) >>> output = op(input_x) >>> print(output) [[-2. -2. -2. -2. -2.] [-2. -2. -2. -2. -2.]] """ @prim_attr_register def __init__(self): """Initialize Rint.""" self.init_prim_io_names(inputs=['x'], outputs=['output']) class Select(Primitive): r""" Returns the selected elements, either from input :math:`x` or input :math:`y`, depending on the `condition`. Given a tensor as input, this operation inserts a dimension of 1 at the dimension, it was invalid when both math: 'x' and math: 'y' are none. Keep in mind that the shape of the output tensor can vary depending on how many true values are in the input. Indexes are output in row-first order. The conditional tensor acts as an optional compensation (mask), which determines whether the corresponding element / row in the output must be selected from :math:`x` (if true) or :math:`y` (if false) based on the value of each element. It can be defined as: .. math:: out_i = \begin{cases} x_i, & \text{if } condition_i \\ y_i, & \text{otherwise} \end{cases} If condition is a vector, then :math:`x` and :math:`y` are higher-dimensional matrices, then it chooses to copy that row (external dimensions) from :math:`x` and :math:`y`. If condition has the same shape as :math:`x` and :math:`y`, you can choose to copy these elements from :math:`x` and :math:`y`. Inputs: - **input_cond** (Tensor[bool]) - The shape is :math:`(x_1, x_2, ..., x_N, ..., x_R)`. The condition tensor, decides which element is chosen. - **input_x** (Tensor) - The shape is :math:`(x_1, x_2, ..., x_N, ..., x_R)`. The first input tensor. - **input_y** (Tensor) - The shape is :math:`(x_1, x_2, ..., x_N, ..., x_R)`. The second input tensor. Outputs: Tensor, has the same shape as `input_x`. The shape is :math:`(x_1, x_2, ..., x_N, ..., x_R)`. Raises: TypeError: If `input_x` or `input_y` is not a Tensor. ValueError: If shape of `input_x` is not equal to shape of `input_y` or shape of `input_cond`. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> select = ops.Select() >>> input_cond = Tensor([True, False]) >>> input_x = Tensor([2,3], mindspore.float32) >>> input_y = Tensor([1,2], mindspore.float32) >>> output = select(input_cond, input_x, input_y) >>> print(output) [2. 2.] """ @prim_attr_register def __init__(self): """Initialize Select.""" self.init_prim_io_names(inputs=['condition', 'x', 'y'], outputs=['output']) def _compute_slicing_length(begin, end, stride, x_shape, i): """Computes the length of the slicing.""" if i >= len(x_shape): raise ValueError(f"For 'StridedSlice', the index must be less than " f"the dimension of 'input_x', but got the dimension of 'input_x': {len(x_shape)} " f"and the index: {i}.") x_dim = x_shape[i] if stride > 0: # When slicing forward, convert begin and end to positive numbers. if begin >= x_dim or end < -x_dim: # When slicing forward, if begin >= x_dim or end < -x_dim, the length of the slicing is 0. slicing_length = 0 else: if -x_dim <= begin < 0: begin += x_dim if begin < -x_dim: # When slicing forward, if begin < -x_dim, set begin = 0, which means start from the 0th element. begin = 0 if -x_dim <= end < 0: end += x_dim if end > x_dim: # When slicing forward, if end > x_dim, set end = x_dims, which means slice to the last element. end = x_dim if begin >= end: # When slicing forward, if begin >= end, the length of the slicing is 0. slicing_length = 0 else: slicing_length = 1 + (end - 1 - begin) // stride else: # When slicing backward, convert begin and end to negative numbers. if begin < -x_dim or end >= x_dim: # When slicing backward, if begin < -x_dim or end >= x_dim, the length of the slicing is 0. slicing_length = 0 else: if 0 <= begin < x_dim: begin += -x_dim if begin >= x_dim: begin = -1 if 0 <= end < x_dim: end += -x_dim if end < -x_dim - 1: # Slicing to the 0th element. end = -x_dim - 1 if begin <= end: slicing_length = 0 else: slicing_length = 1 + (end + 1 - begin) // stride return slicing_length class StridedSlice(PrimitiveWithInfer): r""" Extracts a strided slice of a tensor. Given an input tensor, this operation inserts a dimension of length 1 at the dimension. This operation extracts a fragment of size (end-begin)/stride from the given 'input_tensor'. Starting from the beginning position, the fragment continues adding stride to the index until all dimensions are not less than the ending position. Given a `input_x[m1, m2, ..., mn]`, `begin`, `end` and `strides` will be vectors of length n. In each mask field (`begin_mask`, `end_mask`, `ellipsis_mask`, `new_axis_mask`, `shrink_axis_mask`) the ith bit will correspond to the ith m. If the ith bit of `begin_mask` is set, `begin[i]` is ignored and the fullest possible range in that dimension is used instead. `end_mask` is analogous, except with the end range. As for a 5*6*7 tensor, `x[2:,:3,:]` is equivalent to `x[2:5,0:3,0:7]`. If the ith bit of `ellipsis_mask` is set, as many unspecified dimensions as needed will be inserted between other dimensions. Only one non-zero bit is allowed in `ellipsis_mask`. As for a 5*6*7*8 tensor, `x[2:,...,:6]` is equivalent to `x[2:5,:,:,0:6]`. `x[2:,...]` is equivalent to `x[2:5,:,:,:]`. If the ith bit of `new_axis_mask` is set, `begin`, `end` and `strides` are ignored and a new length 1 dimension is added at the specified position in tthe output tensor. As for a 5*6*7 tensor, `x[:2, newaxis, :6]` will produce a tensor with shape (2, 1, 7). If the ith bit of `shrink_axis_mask` is set, ith size shrinks the dimension by 1, taking on the value at index `begin[i]`, `end[i]` and `strides[i]` are ignored. As for a 5*6*7 tensor, `x[:, 5, :]` will result in `shrink_axis_mask` equal to 4. Note: The stride may be negative value, which causes reverse slicing. The shape of `begin`, `end` and `strides` must be the same. `begin` and `end` are zero-indexed. The element of `strides` must be non-zero. Args: begin_mask (int): Starting index of the slice. Default: 0. end_mask (int): Ending index of the slice. Default: 0. ellipsis_mask (int): An int mask. Default: 0. new_axis_mask (int): An int mask. Default: 0. shrink_axis_mask (int): An int mask. Default: 0. Inputs: - **input_x** (Tensor) - The input Tensor. - **begin** (tuple[int]) - A tuple which represents the location where to start. Only constant value is allowed. - **end** (tuple[int]) - A tuple or which represents the maximum location where to end. Only constant value is allowed. - **strides** (tuple[int]) - A tuple which represents the stride is continuously added before reaching the maximum location. Only constant value is allowed. Outputs: Tensor, The output is explained by following example. In the 0th dimension, begin is 1, end is 2, and strides is 1, because :math:`1+1=2\geq2`, the interval is :math:`[1,2)`. Thus, return the element with :math:`index = 1` in 0th dimension, i.e., [[3, 3, 3], [4, 4, 4]]. In the 1st dimension, similarly, the interval is :math:`[0,1)`. Based on the return value of the 0th dimension, return the element with :math:`index = 0`, i.e., [3, 3, 3]. In the 2nd dimension, similarly, the interval is :math:`[0,3)`. Based on the return value of the 1st dimension, return the element with :math:`index = 0,1,2`, i.e., [3, 3, 3]. Finally, the output is [3, 3, 3]. Raises: TypeError: If `begin_mask`, `end_mask`, `ellipsis_mask`, `new_axis_mask` or `shrink_axis_mask` is not an int. TypeError: If `begin`, `end` or `strides` is not a tuple. ValueError: If `begin_mask`, `end_mask`, `ellipsis_mask`, `new_axis_mask` or `shrink_axis_mask` is less than 0. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Tensor([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]], ... [[5, 5, 5], [6, 6, 6]]], mindspore.float32) >>> # [[[1. 1. 1.] >>> # [2. 2. 2.]] >>> # >>> # [[3. 3. 3.] >>> # [4. 4. 4.]] >>> # >>> # [[5. 5. 5.] >>> # [6. 6. 6.]]] >>> # In order to visually view the multi-dimensional array, write the above as follows: >>> # [ >>> # [ >>> # [1,1,1] >>> # [2,2,2] >>> # ] >>> # [ >>> # [3,3,3] >>> # [4,4,4] >>> # ] >>> # [ >>> # [5,5,5] >>> # [6,6,6] >>> # ] >>> # ] >>> strided_slice = ops.StridedSlice() >>> output = strided_slice(input_x, (1, 0, 2), (3, 1, 3), (1, 1, 1)) >>> # Take this " output = strided_slice(input_x, (1, 0, 2), (3, 1, 3), (1, 1, 1)) " as an example, >>> # start = [1, 0, 2] , end = [3, 1, 3], stride = [1, 1, 1], Find a segment of (start, end), >>> # note that end is an open interval >>> # To facilitate understanding, this operator can be divided into three steps: >>> # Step 1: Calculation of the first dimension: >>> # start = 1, end = 3, stride = 1, So can take 1st, 2nd rows, and then gets the final output at this time. >>> # output_1th = >>> # [ >>> # [ >>> # [3,3,3] >>> # [4,4,4] >>> # ] >>> # [ >>> # [5,5,5] >>> # [6,6,6] >>> # ] >>> # ] >>> # Step 2: Calculation of the second dimension >>> # 2nd dimension, start = 0, end = 1, stride = 1. So only 0th rows can be taken, and the output at this time. >>> # output_2nd = >>> # [ >>> # [ >>> # [3,3,3] >>> # ] >>> # [ >>> # [5,5,5] >>> # ] >>> # ] >>> # Step 3: Calculation of the third dimension >>> # 3nd dimension,start = 2, end = 3, stride = 1, So can take 2th cols, >>> # and you get the final output at this time. >>> # output_3ed = >>> # [ >>> # [ >>> # [3] >>> # ] >>> # [ >>> # [5] >>> # ] >>> # ] >>> # The final output after finishing is: >>> print(output) [[[3.]] [[5.]]] >>> # another example like : >>> output = strided_slice(input_x, (1, 0, 0), (2, 1, 3), (1, 1, 1)) >>> print(output) [[[3. 3. 3.]]] """ @prim_attr_register def __init__(self, begin_mask=0, end_mask=0, ellipsis_mask=0, new_axis_mask=0, shrink_axis_mask=0): """Initialize StridedSlice""" self.init_prim_io_names(inputs=['x', 'begin', 'end', 'strides'], outputs=['output']) validator.check_non_negative_int(begin_mask, 'begin_mask', self.name) validator.check_non_negative_int(end_mask, 'end_mask', self.name) validator.check_non_negative_int(ellipsis_mask, 'ellipsis_mask', self.name) if len(tuple(filter(lambda x: x == '1', bin(ellipsis_mask)[-1:1:-1]))) > 1: raise ValueError(f"For '{self.name}', only support one ellipsis in the index, but got {end_mask}.") validator.check_non_negative_int(new_axis_mask, 'new_axis_mask', self.name) validator.check_non_negative_int(shrink_axis_mask, 'shrink_axis_mask', self.name) def _check_and_get_value(self, slice_input, name): """Check begin, end, strides. Get its length and value.""" slice_value = slice_input['value'] if slice_value is None: validator.check_tensor_dtype_valid(name, slice_input['dtype'], [mstype.int64], self.name) slice_shape = slice_input['shape'] if len(slice_shape) != 1: raise ValueError(f"For '{self.name}', both the 'begins', 'ends', and 'strides' must be 1-D, " f"but got '{name}' shape: {slice_shape}.") # not support scalar return slice_value, slice_shape[0] if isinstance(slice_value, Tensor_): validator.check_tensor_dtype_valid(name, slice_input['dtype'], [mstype.int64], self.name) slice_value = slice_value.asnumpy().tolist() elif not isinstance(slice_value, tuple): raise TypeError(f"For '{self.name}', both the 'begin', 'end', and 'strides' must be a tuple or Tensor, " f"but got '{name}': {slice_value}.") if tuple(filter(lambda x: not isinstance(x, int), slice_value)): raise TypeError(f"For '{self.name}', the elements of 'begin', 'end', and 'strides' must be int, " f"but got {name}: {slice_value}.") return slice_value, len(slice_value) def __infer__(self, x, begin, end, strides): x_shape = x['shape'] if -1 in x_shape: raise ValueError(f"For '{self.name}', input x is currently not support dynamic shape.") begin_v, begin_len = self._check_and_get_value(begin, 'begin') end_v, end_len = self._check_and_get_value(end, 'end') strides_v, strides_len = self._check_and_get_value(strides, 'strides') if strides_v is not None and tuple(filter(lambda x: x == 0, strides_v)): raise ValueError(f"For '{self.name}', the 'strides' cannot contain 0, but got 'strides': {strides_v}.") if begin_len != strides_len or end_len != strides_len: raise ValueError(f"For '{self.name}', 'begin', 'end' and 'strides' must be the same length, but got " f"'begin' length: {begin_len}, 'end' length: {end_len}, 'strides' length: {strides_len}.") if None in (strides_v, begin_v, end_v): ret_shape = self._compute_dynamic_slicing_shape(x_shape, begin_len) ret_min_shape = [1] * len(x_shape) ret_max_shape = x_shape for i, val in enumerate(ret_shape): if val > 0: ret_min_shape[i] = val ret_max_shape[i] = val return {'shape': ret_shape, 'dtype': x['dtype'], 'value': None, 'max_shape': ret_max_shape, 'min_shape': ret_min_shape} ret_shape = self._compute_slicing_shape(x_shape, begin_v, end_v, strides_v) if all(ret_shape): value = None else: init_func = Zero() init_func.__enable_zero_dim__ = True value = Tensor(dtype=x['dtype'].element_type(), shape=ret_shape, init=init_func) if "max_value" in x and "min_value" in x: validator.check_value_type("min_value", x["min_value"], [tuple, list], self.name) validator.check_value_type("max_value", x["max_value"], [tuple, list], self.name) max_value_np = np.array(x["max_value"]) min_value_np = np.array(x["min_value"]) slice_index = [] for begin_i, end_i, strides_i in zip(begin_v, end_v, strides_v): s = slice(begin_i, end_i, strides_i) slice_index.append(s) slice_index = tuple(slice_index) max_value_slice = max_value_np[slice_index] min_value_slice = min_value_np[slice_index] max_value_slice = tuple(max_value_slice.tolist()) min_value_slice = tuple(min_value_slice.tolist()) return {'shape': ret_shape, 'dtype': x['dtype'], 'value': value, 'max_value': max_value_slice, 'min_value': min_value_slice} return {'shape': ret_shape, 'dtype': x['dtype'], 'value': value} def _compute_slicing_shape(self, x_shape, begin_v, end_v, strides_v): """Computes the shape of the slicing.""" x_rank = len(x_shape) slice_len = len(begin_v) # After the integer is converted to binary, it is a str and the first two chars are the flag char '0b'. begin_pos = bin(self.begin_mask)[-1:1:-1] end_pos = bin(self.end_mask)[-1:1:-1] ellipsis_pos = bin(self.ellipsis_mask)[-1:1:-1] new_axis_pos = bin(self.new_axis_mask)[-1:1:-1] shrink_axis_pos = bin(self.shrink_axis_mask)[-1:1:-1] ret_shape = [] i, j = 0, 0 has_ellipsis = False while i < x_rank or j < slice_len: if j < slice_len: begin, end, stride = begin_v[j], end_v[j], strides_v[j] if j < len(ellipsis_pos) and ellipsis_pos[j] == '1': # When there is ellipsis, the latter part of the ellipsis will be processed separately. has_ellipsis = True break if j < len(begin_pos) and begin_pos[j] == '1': begin = -1 if strides_v[j] < 0 else 0 if j < len(end_pos) and end_pos[j] == '1': end = -(x_shape[i] + 1) if strides_v[j] < 0 else x_shape[i] if j < len(new_axis_pos) and new_axis_pos[j] == '1': ret_shape.append(1) j += 1 continue if j < len(shrink_axis_pos) and shrink_axis_pos[j] == '1': if (not -x_shape[i] <= begin < x_shape[i]) or stride < 0: raise IndexError(f"For '{self.name}', the 'strides[{i}]' cannot be negative number and " f"'begin[{i}]' should be in [-{x_shape[i]}, {x_shape[i]}) " f"when 'shrink_axis_mask' is greater than 0, " f"but got 'shrink_axis_mask': {self.shrink_axis_mask}, " f"'strides[{i}]': {stride}, 'begin[{i}]': {begin}.") j += 1 i += 1 continue else: begin, end, stride = 0, x_shape[i], 1 slicing_length = _compute_slicing_length(begin, end, stride, x_shape, i) ret_shape.append(slicing_length) i += 1 j += 1 if has_ellipsis: # When there is ellipsis, handle the second half of the ellipsis split. ellipsis_occupied_dims = x_rank - i - (slice_len - (j + 1)) + \ len(tuple(filter(lambda x: x == '1', new_axis_pos[j + 1:slice_len]))) ret_shape.extend(x_shape[i:i + ellipsis_occupied_dims]) j += 1 i += ellipsis_occupied_dims while i < x_rank or j < slice_len: begin, end, stride = begin_v[j], end_v[j], strides_v[j] if j < len(begin_pos) and begin_pos[j] == '1': begin = -1 if strides_v[j] < 0 else 0 if j < len(end_pos) and end_pos[j] == '1': end = -(x_shape[i] + 1) if strides_v[j] < 0 else x_shape[i] if j < len(new_axis_pos) and new_axis_pos[j] == '1': ret_shape.append(1) j += 1 continue if j < len(shrink_axis_pos) and shrink_axis_pos[j] == '1': if (not -x_shape[i] <= begin < x_shape[i]) or stride < 0: raise IndexError(f"For '{self.name}', the 'strides[{i}]' cannot be negative number and " f"'begin[{i}]' should be in [-{x_shape[i]}, {x_shape[i]}) " f"when 'shrink_axis_mask' is greater than 0, " f"but got 'shrink_axis_mask': {self.shrink_axis_mask}, " f"'strides[{i}]': {stride}, 'begin[{i}]': {begin}.") j += 1 i += 1 continue slicing_length = _compute_slicing_length(begin, end, stride, x_shape, i) ret_shape.append(slicing_length) i += 1 j += 1 return ret_shape def _compute_dynamic_slicing_shape(self, x_shape, slice_len): """Computes the shape of the slicing for dynamic shape, mask is currently not supported.""" x_rank = len(x_shape) if self.begin_mask != 0 or self.end_mask != 0 or self.ellipsis_mask or self.new_axis_mask != 0 \ or self.shrink_axis_mask != 0: raise ValueError("Mask is currently not supported if 'begin', 'end' or 'strides' is not a constant.") ret_shape = [] i, j = 0, 0 while i < x_rank or j < slice_len: slicing_length = -1 if j >= slice_len: if i >= len(x_shape): raise ValueError(f"For 'StridedSlice', the index must be less than or equal to " f"the dimension of 'input_x', but got the dimension of 'input_x': {len(x_shape)} " f"and the index: {i}.") begin, end, stride = 0, x_shape[i], 1 if end > 0: slicing_length = _compute_slicing_length(begin, end, stride, x_shape, i) ret_shape.append(slicing_length) i += 1 j += 1 return ret_shape class Diag(PrimitiveWithInfer): r""" Constructs a diagonal tensor with a given diagonal values. Assume `input_x` has dimensions :math:`[D_1,... D_k]`, the output is a tensor of rank 2k with dimensions :math:`[D_1,..., D_k, D_1,..., D_k]` where: :math:`output[i_1,..., i_k, i_1,..., i_k] = input_x[i_1,..., i_k]` and 0 everywhere else. Inputs: - **input_x** (Tensor) - The input tensor. The input shape must be less than 5d. Outputs: Tensor, has the same dtype as the `input_x`. Raises: TypeError: If `input_x` is not a Tensor. ValueError: If rank of `input_x` is less than 1. Supported Platforms: ``Ascend`` Examples: >>> input_x = Tensor([1, 2, 3, 4]) >>> diag = ops.Diag() >>> output = diag(input_x) >>> print(output) [[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]] """ @prim_attr_register def __init__(self): """Initialize Diag""" def infer_dtype(self, x_type): validator.check_subclass('input_x', x_type, mstype.tensor, self.name) return x_type def infer_shape(self, x_shape): validator.check("x rank", len(x_shape), "", 1, Rel.GE) ret_shape = copy.deepcopy(x_shape) ret_shape = ret_shape + ret_shape return ret_shape def infer_value(self, x): if x is None: return None # do constant-folding only when x rank is 1 if len(x.shape) != 1: return None ret = np.diag(x.asnumpy()) return Tensor(ret) class DiagPart(PrimitiveWithInfer): r""" Extracts the diagonal part from given tensor. Assume input has dimensions :math:`[D_1,..., D_k, D_1,..., D_k]`, the output is a tensor of rank k with dimensions :math:`[D_1,..., D_k]` where: :math:`output[i_1,..., i_k] = input[i_1,..., i_k, i_1,..., i_k]`. Inputs: - **input_x** (Tensor) - The input tensor of rank 2k, k is not zero. Outputs: Tensor, the extracted diagonal has the same dtype as the `input_x`. Raises: TypeError: If `input_x` is not a Tensor. ValueError: If rank of `input_x` is not even or zero. ValueError: If input_shape[i] is not equal to input_shape[i + len(input_shape)/2]. Supported Platforms: ``Ascend`` Examples >>> input_x = Tensor([[1, 0, 0, 0], ... [0, 2, 0, 0], ... [0, 0, 3, 0], ... [0, 0, 0, 4]]) >>> diag_part = ops.DiagPart() >>> output = diag_part(input_x) >>> print(output) [1 2 3 4] """ @prim_attr_register def __init__(self): """Initialize DiagPart""" def infer_dtype(self, x_type): validator.check_subclass('input_x', x_type, mstype.tensor, self.name) return x_type def infer_shape(self, x_shape): if len(x_shape) % 2 != 0 or \ not x_shape: raise ValueError(f"For \'{self.name}\', the dimension of 'input_x' must be non-zero and even, " f"but got dimension {len(x_shape)}, with shapes {x_shape}.") length = len(x_shape) // 2 for i in range(length): validator.check('input_shape[i + len(input_shape)/2]', x_shape[i + length], 'input_shape[i]', x_shape[i], Rel.EQ, self.name) ret_shape = x_shape[0:length] return ret_shape def infer_value(self, x): if x is None: return None # do constant-folding only when x rank is 2 if len(x.shape) != 2: return None ret = np.diag(x.asnumpy()) return Tensor(ret) class Eye(PrimitiveWithInfer): """ Creates a tensor with ones on the diagonal and zeros in the rest. Inputs: - **n** (int) - The number of rows of returned tensor. Constant value only. - **m** (int) - The number of columns of returned tensor. Constant value only. - **t** (mindspore.dtype) - MindSpore's dtype, The data type of the returned tensor. The data type can be Number. Outputs: Tensor, a tensor with ones on the diagonal and the rest of elements are zero. The shape of `output` depends on the user's Inputs `n` and `m`. And the data type depends on Inputs `t`. Raises: TypeError: If `m` or `n` is not an int. ValueError: If `m` or `n` is less than 1. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> eye = ops.Eye() >>> output = eye(2, 2, mindspore.int32) >>> print(output) [[1 0] [0 1]] >>> print(output.dtype) Int32 >>> output = eye(1, 2, mindspore.float64) >>> print(output) [[1. 0.]] >>> print(output.dtype) Float64 >>> # if wants a anti-diagonal >>> anti_diagonal_input = eye(2, 2, mindspore.int32) >>> # Note that ReverseV2 only supports "Ascend" and "GPU" at this time >>> reverse = ops.ReverseV2([1]) >>> anti_diagonal_output = reverse(anti_diagonal_input) >>> print(anti_diagonal_output) [[0 1] [1 0]] """ @prim_attr_register def __init__(self): """Initialize Eye""" def infer_value(self, n, m, t): validator.check_positive_int(n, "n", self.name) validator.check_positive_int(m, "m", self.name) args = {"dtype": t} validator.check_types_same_and_valid(args, mstype.number_type + (mstype.bool_,), self.name) np_type = mstype.dtype_to_nptype(t) ret = np.eye(n, m, dtype=np_type) return Tensor(ret) class ScatterNd(PrimitiveWithInfer): r""" Scatters a tensor into a new tensor depending on the specified indices. Creates an empty tensor with the given `shape`, and set values by scattering the update tensor depending on indices. The empty tensor has rank P and `indices` has rank Q where `Q >= 2`. `indices` has shape :math:`(i_0, i_1, ..., i_{Q-2}, N)` where `N <= P`. The last dimension of `indices` (with length `N` ) indicates slices along the `N` th dimension of the empty tensor. `updates` is a tensor of rank `Q-1+P-N`. Its shape is: :math:`(i_0, i_1, ..., i_{Q-2}, shape_N, ..., shape_{P-1})`. The following figure shows the calculation process of inserting two slices in the first dimension of a rank-3 with two matrices of new values: .. image:: api_img/ScatterNd.png Inputs: - **indices** (Tensor) - The index of scattering in the new tensor with int32 or int64 data type. The rank of indices must be at least 2 and `indices_shape[-1] <= len(shape)`. - **updates** (Tensor) - The source Tensor to be scattered. It has shape `indices_shape[:-1] + shape[indices_shape[-1]:]`. - **shape** (tuple[int]) - Define the shape of the output tensor, has the same data type as indices. The shape of `shape` is :math:`(x_1, x_2, ..., x_R)`, and length of 'shape' is greater than or equal 2. In other words, the shape of `shape` is at least :math:`(x_1, x_2)`. And the value of any element in `shape` must be greater than or equal 1. In other words, :math:`x_1` >= 1, :math:`x_2` >= 1. Outputs: Tensor, the new tensor, has the same type as `update` and the same shape as `shape`. Raises: TypeError: If `shape` is not a tuple. ValueError: If any element of `shape` is less than 1. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> op = ops.ScatterNd() >>> indices = Tensor(np.array([[0], [2]]), mindspore.int32) >>> updates = Tensor(np.array([[[1, 1, 1, 1], [2, 2, 2, 2], ... [3, 3, 3, 3], [4, 4, 4, 4]], ... [[1, 1, 1, 1], [2, 2, 2, 2], ... [3, 3, 3, 3], [4, 4, 4, 4]]]), mindspore.float32) >>> shape = (4, 4, 4) >>> output = op(indices, updates, shape) >>> print(output) [[[1. 1. 1. 1.] [2. 2. 2. 2.] [3. 3. 3. 3.] [4. 4. 4. 4.]] [[0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]] [[1. 1. 1. 1.] [2. 2. 2. 2.] [3. 3. 3. 3.] [4. 4. 4. 4.]] [[0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]]] >>> indices = Tensor(np.array([[0, 1], [1, 1]]), mindspore.int32) >>> updates = Tensor(np.array([3.2, 1.1]), mindspore.float32) >>> shape = (3, 3) >>> output = op(indices, updates, shape) >>> # In order to facilitate understanding, explain the operator pseudo-operation process step by step: >>> # Step 1: Generate an empty Tensor of the specified shape according to the shape >>> # [ >>> # [0. 0. 0.] >>> # [0. 0. 0.] >>> # [0. 0. 0.] >>> # ] >>> # Step 2: Modify the data at the specified location according to the indicators >>> # 0th row of indices is [0, 1], 0th row of updates is 3.2. >>> # means that the empty tensor in the 0th row and 1st col set to 3.2 >>> # [ >>> # [0. 3.2. 0.] >>> # [0. 0. 0.] >>> # [0. 0. 0.] >>> # ] >>> # 1th row of indices is [1, 1], 1th row of updates is 1.1. >>> # means that the empty tensor in the 1th row and 1st col set to 1.1 >>> # [ >>> # [0. 3.2. 0.] >>> # [0. 1.1 0.] >>> # [0. 0. 0.] >>> # ] >>> # The final result is as follows: >>> print(output) [[0. 3.2 0.] [0. 1.1 0.] [0. 0. 0.]] """ @prim_attr_register def __init__(self): """Initialize ScatterNd""" self.init_prim_io_names(inputs=['indices', 'update', 'shape'], outputs=['output']) def __infer__(self, indices, update, shape): shp = shape['value'] validator.check_subclass("update_dtype", update['dtype'], mstype.tensor, self.name) validator.check_tensor_dtype_valid("indices", indices['dtype'], [mstype.int32, mstype.int64], self.name) validator.check_value_type("shape", shp, [tuple], self.name) for i, x in enumerate(shp): validator.check_positive_int(x, f'shape[{i}]', self.name) indices_shape, update_shape = indices["shape"], update["shape"] if indices_shape[0] != update_shape[0]: raise ValueError(f"For '{self.name}', the first shape of 'indices' must be the same as the first shape of " f"'updates', but got the first shape of 'indices': {indices_shape[0]}, " f"the first shape of 'updates': {update_shape[0]}.") return {'shape': shp, 'dtype': update['dtype'], 'value': None} class ResizeNearestNeighbor(Primitive): r""" Resizes the input tensor by using the nearest neighbor algorithm. Resizes the input tensor to a given size by using the nearest neighbor algorithm. The nearest neighbor algorithm selects the value of the nearest point and does not consider the values of neighboring points at all, yielding a piecewise-constant interpolant. Args: size (Union[tuple, list]): The target size. The dimension of size must be 2. align_corners (bool): Whether the centers of the 4 corner pixels of the input and output tensors are aligned. Default: False. Inputs: - **input_x** (Tensor) - The input tensor. The shape of the tensor is :math:`(N, C, H, W)`. Outputs: Tensor, the shape of the output tensor is :math:`(N, C, NEW\_H, NEW\_W)`. The data type is the same as the `input_x`. Raises: TypeError: If `size` is neither tuple nor list. TypeError: If `align_corners` is not a bool. ValueError: If length of `size` is not equal to 2. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_tensor = Tensor(np.array([[[[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]]]), mindspore.float32) >>> resize = ops.ResizeNearestNeighbor((2, 2)) >>> output = resize(input_tensor) >>> print(output) [[[[-0.1 0.3] [ 0.4 0.5]]]] """ @prim_attr_register def __init__(self, size, align_corners=False): """Initialize ResizeNearestNeighbor""" validator.check_value_type("size", size, [tuple, list], self.name) validator.check_value_type("align_corners", align_corners, [bool], self.name) validator.check_equal_int(len(size), 2, "length of size", self.name) for i, value in enumerate(size): validator.check_non_negative_int(value, f'{i}th value of size', self.name) self.init_prim_io_names(inputs=['image_in'], outputs=['image_out']) class GatherNd(Primitive): r""" Gathers slices from a tensor by indices. Using given indices to gather slices from a tensor with a specified shape. `indices` is an K-dimensional integer tensor. Supposes it as a (K-1)-dimensional tensor and each element of it defines a slice of `input_x`: .. math:: output[(i_0, ..., i_{K-2})] = input\_x[indices[(i_0, ..., i_{K-2})]] The last dimension of `indices` can not more than the rank of `input_x`: :math:`indices.shape[-1] <= input\_x.rank`. Inputs: - **input_x** (Tensor) - The target tensor to gather values. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. - **indices** (Tensor) - The index tensor, with int32 or int64 data type. Outputs: Tensor, has the same type as `input_x` and the shape is indices_shape[:-1] + x_shape[indices_shape[-1]:]. Raises: ValueError: If length of shape of `input_x` is less than the last dimension of `indices`. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> op = ops.GatherNd() >>> input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32) >>> indices = Tensor(np.array([[0, 0], [1, 1]]), mindspore.int32) >>> output = op(input_x, indices) >>> print(output) [-0.1 0.5] """ @prim_attr_register def __init__(self): """Initialize GatherNd""" self.init_prim_io_names(inputs=['input_x', 'indices'], outputs=['y']) class TensorScatterUpdate(PrimitiveWithInfer): """ Creates a new tensor by updating the positions in `input_x` indicated by `indices`, with values from `update`. This operation is almost equivalent to using ScatterNd, except that the updates are applied on `input_x` instead of a zero tensor. `indices` must have rank at least 2, the last axis is the depth of each index vectors. For each index vector, there must be a corresponding value in `update`. If the depth of each index tensor matches the rank of `input_x`, then each index vector corresponds to a scalar in `input_x` and each `update` updates a scalar. If the depth of each index tensor is less than the rank of `input_x`, then each index vector corresponds to a slice in `input_x`, and each `update` updates a slice. The order in which updates are applied is nondeterministic, meaning that if there are multiple index vectors in `indices` that correspond to the same position, the value of that position in the output will be nondeterministic. Inputs: - **input_x** (Tensor) - The target tensor. The dimension of input_x must be no less than indices.shape[-1]. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. The data type is Number. - **indices** (Tensor) - The index of input tensor whose data type is int32 or int64. The rank must be at least 2. - **update** (Tensor) - The tensor to update the input tensor, has the same type as input, and :math:`update.shape = indices.shape[:-1]+input_x.shape[indices.shape[-1]:]` Outputs: Tensor, has the same shape and type as `input_x`. Raises: TypeError: If dtype of `indices` is neither int32 nor int64. ValueError: If length of shape of `input_x` is less than the last dimension of shape of `indices`. ValueError: If the value of `input_x` are not match with input `indices`. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32) >>> indices = Tensor(np.array([[0, 0], [1, 1]]), mindspore.int32) >>> update = Tensor(np.array([1.0, 2.2]), mindspore.float32) >>> op = ops.TensorScatterUpdate() >>> output = op(input_x, indices, update) >>> print(output) [[ 1. 0.3 3.6] [ 0.4 2.2 -3.2]] """ @prim_attr_register def __init__(self): self.init_prim_io_names(inputs=['input_x', 'indices', 'updates'], outputs=['y']) def infer_shape(self, input_x_shape, indices_shape, updates_shape): if len(indices_shape) < 2: raise ValueError(f"For '{self.name}', the dimension of 'indices' cannot be less than 2," f" but got {len(indices_shape)}.") if indices_shape[-1] > len(input_x_shape): raise ValueError(f"For '{self.name}', the last dimension of 'indices' must be less than or equal to " f"the dimension of 'input_x', but got the " f"last dimension of 'indices': {indices_shape[-1]} and the dimension of 'input_x': " f"{len(input_x_shape)}.") updates_shape_check = indices_shape[:-1] + input_x_shape[indices_shape[-1]:] if updates_shape_check != updates_shape: raise ValueError(f"For '{self.name}', the shape of 'update' must be equal to updates_shape_check, " f"where updates_shape_check = indices_shape[:-1] + input_x_shape[indices_shape[-1]:] " f"but got the shape of 'update': {updates_shape}, " f"updates_shape_check: {updates_shape_check}, indices_shape: {indices_shape} and " f"input_x_shape: {input_x_shape}. Please check input_x_shape and indices_shape.") return input_x_shape def infer_dtype(self, input_x_dtype, indices_dtype, updates_dtype): validator.check_tensor_dtype_valid('indices', indices_dtype, [mstype.int32, mstype.int64], self.name) args = {"input_x": input_x_dtype, "updates": updates_dtype} validator.check_tensors_dtypes_same_and_valid(args, (mstype.bool_,) + mstype.number_type, self.name) return input_x_dtype class TensorScatterAdd(PrimitiveWithInfer): """ Creates a new tensor by adding the values from the positions in `input_x` indicated by `indices`, with values from `updates`. When multiple values are given for the same index, the updated result will be the sum of all values. This operation is almost equivalent to using ScatterNdAdd, except that the updates are applied on `Tensor` instead of `Parameter`. The last axis of `indices` is the depth of each index vectors. For each index vector, there must be a corresponding value in `updates`. The shape of `updates` should be equal to the shape of `input_x[indices]`. For more details, see use cases. Note: If some values of the `indices` are out of bound, instead of raising an index error, the corresponding `updates` will not be updated to `input_x`. Inputs: - **input_x** (Tensor) - The target tensor. The dimension of input_x must be no less than indices.shape[-1]. - **indices** (Tensor) - The index of input tensor whose data type is int32 or int64. The rank must be at least 2. - **updates** (Tensor) - The tensor to update the input tensor, has the same type as input, and updates.shape should be equal to indices.shape[:-1] + input_x.shape[indices.shape[-1]:]. Outputs: Tensor, has the same shape and type as `input_x`. Raises: TypeError: If dtype of `indices` is neither int32 nor int64. ValueError: If length of shape of `input_x` is less than the last dimension of shape of `indices`. Supported Platforms: ``GPU`` Examples: >>> input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32) >>> indices = Tensor(np.array([[0, 0], [0, 0]]), mindspore.int32) >>> updates = Tensor(np.array([1.0, 2.2]), mindspore.float32) >>> # Next, demonstrate the approximate operation process of this operator: >>> # 1, indices[0] = [0, 0], indices[1] = [0, 0] >>> # 2, And input_x[0, 0] = -0.1 >>> # 3, So input_x[indices] = [-0.1, -0.1] >>> # 4, Satisfy the above formula: input_x[indices].shape=(2) == updates.shape=(2) >>> op = ops.TensorScatterAdd() >>> # 5, Perform the addition operation for the first time: >>> # first_input_x = input_x[0][0] + updates[0] = [[0.9, 0.3, 3.6], [0.4, 0.5, -3.2]] >>> # 6, Perform the addition operation for the second time: >>> # second_input_x = input_x[0][0] + updates[1] = [[3.1, 0.3, 3.6], [0.4, 0.5, -3.2]] >>> output = op(input_x, indices, updates) >>> print(output) [[ 3.1 0.3 3.6] [ 0.4 0.5 -3.2]] """ @prim_attr_register def __init__(self): self.init_prim_io_names(inputs=['input_x', 'indices', 'updates'], outputs=['y']) def infer_shape(self, input_x_shape, indices_shape, updates_shape): if len(indices_shape) < 2: raise ValueError(f"For '{self.name}', the dimension of 'indices' cannot be less than 2," f" but got {len(indices_shape)}.") if indices_shape[-1] > len(input_x_shape): raise ValueError(f"For '{self.name}', the last dimension of 'indices' must be less than or equal to " f"the dimension of 'input_x', but got the " f"last dimension of 'indices': {indices_shape[-1]} and the dimension of 'input_x': " f"{len(input_x_shape)}.") updates_shape_check = indices_shape[:-1] + input_x_shape[indices_shape[-1]:] if updates_shape_check != updates_shape: raise ValueError(f"For '{self.name}', the shape of 'update' must be equal to updates_shape_check, " f"where updates_shape_check = indices_shape[:-1] + input_x_shape[indices_shape[-1]:] " f"but got the shape of 'update': {updates_shape}, " f"updates_shape_check: {updates_shape_check}, indices_shape: {indices_shape} and " f"input_x_shape: {input_x_shape}. Please check input_x_shape and indices_shape.") return input_x_shape def infer_dtype(self, input_x_dtype, indices_dtype, updates_dtype): validator.check_tensor_dtype_valid('indices', indices_dtype, [mstype.int32, mstype.int64], self.name) args = {"input_x": input_x_dtype, "updates": updates_dtype} validator.check_tensors_dtypes_same_and_valid(args, (mstype.bool_,) + mstype.number_type, self.name) return input_x_dtype class ScatterUpdate(_ScatterOpDynamic): r""" Updates tensor values by using input indices and value. Using given values to update tensor value, along with the input indices. for each `i, ..., j` in `indices.shape`: .. math:: \text{input_x}[\text{indices}[i, ..., j], :] = \text{updates}[i, ..., j, :] Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent. If they have different data types, the lower priority data type will be converted to the relatively highest priority data type. Args: use_locking (bool): Whether protect the assignment by a lock. Default: True. Inputs: - **input_x** (Parameter) - The target tensor, with data type of Parameter. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. - **indices** (Tensor) - The index of input tensor. With int32 data type. If there are duplicates in indices, the order for updating is undefined. - **updates** (Tensor) - The tensor to update the input tensor, has the same type as input, and updates.shape = indices.shape + input_x.shape[1:]. Outputs: Tensor, has the same shape and type as `input_x`. Raises: TypeError: If `use_locking` is not a bool. TypeError: If `indices` is not an int32. RuntimeError: If the data type of `input_x` and `updates` conversion of Parameter is required when data type conversion of Parameter is not supported. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> np_x = np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]) >>> input_x = mindspore.Parameter(Tensor(np_x, mindspore.float32), name="x") >>> indices = Tensor(np.array([0, 1]), mindspore.int32) >>> np_updates = np.array([[2.0, 1.2, 1.0], [3.0, 1.2, 1.0]]) >>> updates = Tensor(np_updates, mindspore.float32) >>> op = ops.ScatterUpdate() >>> output = op(input_x, indices, updates) >>> print(output) [[2. 1.2 1.] [3. 1.2 1.]] """ @prim_attr_register def __init__(self, use_locking=True): """Initialize ScatterUpdate""" validator.check_value_type('use_locking', use_locking, [bool], self.name) self.init_prim_io_names(inputs=['x', 'indices', 'updates'], outputs=['y']) self.add_prim_attr('side_effect_mem', True) class ScatterNdUpdate(Primitive): r""" Updates tensor values by using input indices and value. Using given values to update tensor value, along with the input indices. `input_x` has rank P and `indices` has rank Q where `Q >= 2`. `indices` has shape :math:`(i_0, i_1, ..., i_{Q-2}, N)` where `N <= P`. The last dimension of `indices` (with length `N` ) indicates slices along the `N` th dimension of `input_x`. `updates` is a tensor of rank `Q-1+P-N`. Its shape is: :math:`(i_0, i_1, ..., i_{Q-2}, x\_shape_N, ..., x\_shape_{P-1})`. Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent. If they have different data types, the lower priority data type will be converted to the relatively highest priority data type. Args: use_locking (bool): Whether protect the assignment by a lock. Default: True. Inputs: - **input_x** (Parameter) - The target tensor, with data type of Parameter. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. - **indices** (Tensor) - The index of input tensor, with int32 data type. - **updates** (Tensor) - The tensor to be updated to the input tensor, has the same type as input. The shape is `indices_shape[:-1] + x_shape[indices_shape[-1]:]`. Outputs: Tensor, has the same shape and type as `input_x`. Raises: TypeError: If `use_locking` is not a bool. TypeError: If `indices` is not an int32. RuntimeError: If the data type of `input_x` and `updates` conversion of Parameter is required when data type conversion of Parameter is not supported. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> np_x = np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]) >>> input_x = mindspore.Parameter(Tensor(np_x, mindspore.float32), name="x") >>> indices = Tensor(np.array([[0, 0], [1, 1]]), mindspore.int32) >>> updates = Tensor(np.array([1.0, 2.2]), mindspore.float32) >>> op = ops.ScatterNdUpdate() >>> output = op(input_x, indices, updates) >>> print(output) [[1. 0.3 3.6] [0.4 2.2 -3.2]] """ __mindspore_signature__ = ( sig.make_sig('input_x', sig.sig_rw.RW_WRITE, dtype=sig.sig_dtype.T), sig.make_sig('indices', dtype=sig.sig_dtype.T1), sig.make_sig('updates', dtype=sig.sig_dtype.T) ) @prim_attr_register def __init__(self, use_locking=True): """Initialize ScatterNdUpdate""" validator.check_value_type('use_locking', use_locking, [bool], self.name) self.init_prim_io_names(inputs=['input_x', 'indices', 'value'], outputs=['y']) self.add_prim_attr('side_effect_mem', True) class ScatterMax(_ScatterOp): r""" Updates the value of the input tensor through the maximum operation. Using given values to update tensor value through the max operation, along with the input indices. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value. for each `i, ..., j` in `indices.shape`: .. math:: \text{input_x}[\text{indices}[i, ..., j], :] = max(\text{input_x}[\text{indices}[i, ..., j], :], \text{updates}[i, ..., j, :]) Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent. If they have different data types, the lower priority data type will be converted to the relatively highest priority data type. Args: use_locking (bool): Whether protect the assignment by a lock. Default: True. Inputs: - **input_x** (Parameter) - The target tensor, with data type of Parameter. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. - **indices** (Tensor) - The index to do max operation whose data type must be mindspore.int32. - **updates** (Tensor) - The tensor that performs the maximum operation with `input_x`, the data type is the same as `input_x`, the shape is `indices_shape + x_shape[1:]`. Outputs: Tensor, the updated `input_x`, has the same shape and type as `input_x`. Raises: TypeError: If `use_locking` is not a bool. TypeError: If `indices` is not an int32. ValueError: If the shape of `updates` is not equal to `indices_shape + x_shape[1:]`. RuntimeError: If the data type of `input_x` and `updates` conversion of Parameter is required when data type conversion of Parameter is not supported. Supported Platforms: ``Ascend`` ``CPU`` Examples: >>> input_x = Parameter(Tensor(np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]), mindspore.float32), ... name="input_x") >>> indices = Tensor(np.array([[0, 0], [1, 1]]), mindspore.int32) >>> updates = Tensor(np.ones([2, 2, 3]) * 88, mindspore.float32) >>> scatter_max = ops.ScatterMax() >>> output = scatter_max(input_x, indices, updates) >>> print(output) [[88. 88. 88.] [88. 88. 88.]] """ class ScatterMin(_ScatterOp): r""" Updates the value of the input tensor through the minimum operation. Using given values to update tensor value through the min operation, along with the input indices. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value. for each `i, ..., j` in `indices.shape`: .. math:: \text{input_x}[\text{indices}[i, ..., j], :] = min(\text{input_x}[\text{indices}[i, ..., j], :], \text{updates}[i, ..., j, :]) Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent. If they have different data types, the lower priority data type will be converted to the relatively highest priority data type. Args: use_locking (bool): Whether protect the assignment by a lock. Default: False. Inputs: - **input_x** (Parameter) - The target tensor, with data type of Parameter. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. - **indices** (Tensor) - The index to do min operation whose data type must be mindspore.int32. - **updates** (Tensor) - The tensor doing the min operation with `input_x`, the data type is same as `input_x`, the shape is `indices_shape + x_shape[1:]`. Outputs: Tensor, the updated `input_x`, has the same shape and type as `input_x`. Raises: TypeError: If `use_locking` is not a bool. TypeError: If `indices` is not an int32. ValueError: If the shape of `updates` is not equal to `indices_shape + x_shape[1:]`. RuntimeError: If the data type of `input_x` and `updates` conversion of Parameter is required when data type conversion of Parameter is not supported. Supported Platforms: ``Ascend`` ``CPU`` Examples: >>> input_x = Parameter(Tensor(np.array([[0.0, 1.0, 2.0], [0.0, 0.0, 0.0]]), mindspore.float32), ... name="input_x") >>> indices = Tensor(np.array([[0, 0], [1, 1]]), mindspore.int32) >>> update = Tensor(np.ones([2, 2, 3]), mindspore.float32) >>> scatter_min = ops.ScatterMin() >>> output = scatter_min(input_x, indices, update) >>> print(output) [[0. 1. 1.] [0. 0. 0.]] """ class ScatterAdd(_ScatterOpDynamic): r""" Updates the value of the input tensor through the addition operation. Using given values to update tensor value through the add operation, along with the input indices. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value. for each `i, ..., j` in `indices.shape`: .. math:: \text{input_x}[\text{indices}[i, ..., j], :] \mathrel{+}= \text{updates}[i, ..., j, :] Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent. If they have different data types, the lower priority data type will be converted to the relatively highest priority data type. Note: This is an in-place update operator. Therefore, the `input_x` will be updated after the operation is completed. Args: use_locking (bool): Whether protect the assignment by a lock. Default: False. Inputs: - **input_x** (Parameter) - The target tensor, with data type of Parameter. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. - **indices** (Tensor) - The index to do min operation whose data type must be mindspore.int32. - **updates** (Tensor) - The tensor doing the min operation with `input_x`, the data type is same as `input_x`, the shape is `indices_shape + x_shape[1:]`. Outputs: Tensor, the updated `input_x`, has the same shape and type as `input_x`. Raises: TypeError: If `use_locking` is not a bool. TypeError: If `indices` is not an int32. ValueError: If the shape of `updates` is not equal to `indices_shape + x_shape[1:]`. RuntimeError: If the data type of `input_x` and `updates` conversion of Parameter is required when data type conversion of Parameter is not supported. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Parameter(Tensor(np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), mindspore.float32), name="x") >>> indices = Tensor(np.array([[0, 1], [1, 1]]), mindspore.int32) >>> updates = Tensor(np.ones([2, 2, 3]), mindspore.float32) >>> scatter_add = ops.ScatterAdd() >>> output = scatter_add(input_x, indices, updates) >>> print(output) [[1. 1. 1.] [3. 3. 3.]] >>> # for input_x will be updated after the operation is completed. input_x need to be re-initialized. >>> input_x = Parameter(Tensor(np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), mindspore.float32), name="x") >>> # for indices = [[0, 1], [1, 1]] >>> # step 1: [0, 1] >>> # input_x[0] = [0.0, 0.0, 0.0] + [1.0, 1.0, 1.0] = [1.0, 1.0, 1.0] >>> # input_x[1] = [0.0, 0.0, 0.0] + [3.0, 3.0, 3.0] = [3.0, 3.0, 3.0] >>> # step 2: [1, 1] >>> # input_x[1] = [3.0, 3.0, 3.0] + [7.0, 7.0, 7.0] = [10.0, 10.0, 10.0] >>> # input_x[1] = [10.0, 10.0, 10.0] + [9.0, 9.0, 9.0] = [19.0, 19.0, 19.0] >>> indices = Tensor(np.array([[0, 1], [1, 1]]), mindspore.int32) >>> updates = Tensor(np.array([[[1.0, 1.0, 1.0], [3.0, 3.0, 3.0]], ... [[7.0, 7.0, 7.0], [9.0, 9.0, 9.0]]]), mindspore.float32) >>> scatter_add = ops.ScatterAdd() >>> output = scatter_add(input_x, indices, updates) >>> print(output) [[ 1. 1. 1.] [19. 19. 19.]] >>> # for input_x will be updated after the operation is completed. input_x need to be re-initialized. >>> input_x = Parameter(Tensor(np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), mindspore.float32), name="x") >>> # for indices = [[1, 0], [1, 1]] >>> # step 1: [1, 0] >>> # input_x[0] = [0.0, 0.0, 0.0] + [3.0, 3.0, 3.0] = [3.0, 3.0, 3.0] >>> # input_x[1] = [0.0, 0.0, 0.0] + [1.0, 1.0, 1.0] = [1.0, 1.0, 1.0] >>> # step 2: [1, 1] >>> # input_x[1] = [1.0, 1.0, 1.0] + [7.0, 7.0, 7.0] = [8.0, 8.0, 8.0] >>> # input_x[1] = [8.0, 8.0, 8.0] + [9.0, 9.0, 9.0] = [17.0, 17.0, 17.0] >>> indices = Tensor(np.array([[1, 0], [1, 1]]), mindspore.int32) >>> updates = Tensor(np.array([[[1.0, 1.0, 1.0], [3.0, 3.0, 3.0]], ... [[7.0, 7.0, 7.0], [9.0, 9.0, 9.0]]]), mindspore.float32) >>> scatter_add = ops.ScatterAdd() >>> output = scatter_add(input_x, indices, updates) >>> print(output) [[ 3. 3. 3.] [17. 17. 17.]] >>> # for input_x will be updated after the operation is completed. input_x need to be re-initialized. >>> input_x = Parameter(Tensor(np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), mindspore.float32), name="x") >>> # for indices = [[0, 1], [0, 1]] >>> # step 1: [0, 1] >>> # input_x[0] = [0.0, 0.0, 0.0] + [1.0, 1.0, 1.0] = [1.0, 1.0, 1.0] >>> # input_x[1] = [0.0, 0.0, 0.0] + [3.0, 3.0, 3.0] = [3.0, 3.0, 3.0] >>> # step 2: [0, 1] >>> # input_x[0] = [1.0, 1.0, 1.0] + [7.0, 7.0, 7.0] = [8.0, 8.0, 8.0] >>> # input_x[1] = [3.0, 3.0, 3.0] + [9.0, 9.0, 9.0] = [12.0, 12.0, 12.0] >>> indices = Tensor(np.array([[0, 1], [0, 1]]), mindspore.int32) >>> updates = Tensor(np.array([[[1.0, 1.0, 1.0], [3.0, 3.0, 3.0]], ... [[7.0, 7.0, 7.0], [9.0, 9.0, 9.0]]]), mindspore.float32) >>> scatter_add = ops.ScatterAdd() >>> output = scatter_add(input_x, indices, updates) >>> print(output) [[ 8. 8. 8.] [12. 12. 12.]] """ @prim_attr_register def __init__(self, use_locking=False): """Initialize ScatterAdd""" validator.check_value_type('use_locking', use_locking, [bool], self.name) self.init_prim_io_names(inputs=['x', 'indices', 'updates'], outputs=['y']) self.add_prim_attr('side_effect_mem', True) class ScatterSub(_ScatterOpDynamic): r""" Updates the value of the input tensor through the subtraction operation. Using given values to update tensor value through the subtraction operation, along with the input indices. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value. for each `i, ..., j` in `indices.shape`: .. math:: \text{input_x}[\text{indices}[i, ..., j], :] \mathrel{-}= \text{updates}[i, ..., j, :] Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent. If they have different data types, the lower priority data type will be converted to the relatively highest priority data type. Args: use_locking (bool): Whether protect the assignment by a lock. Default: False. Inputs: - **input_x** (Parameter) - The target tensor, with data type of Parameter. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. - **indices** (Tensor) - The index to do min operation whose data type must be mindspore.int32. - **updates** (Tensor) - The tensor doing the min operation with `input_x`, the data type is same as `input_x`, the shape is `indices_shape + x_shape[1:]`. Outputs: Tensor, the updated `input_x`, has the same shape and type as `input_x`. Raises: TypeError: If `use_locking` is not a bool. TypeError: If `indices` is not an int32. ValueError: If the shape of `updates` is not equal to `indices_shape + x_shape[1:]`. RuntimeError: If the data type of `input_x` and `updates` conversion of Parameter is required when data type conversion of Parameter is not supported. Supported Platforms: ``Ascend`` ``CPU`` ``GPU`` Examples: >>> input_x = Parameter(Tensor(np.array([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]), mindspore.float32), name="x") >>> indices = Tensor(np.array([[0, 1]]), mindspore.int32) >>> updates = Tensor(np.array([[[1.0, 1.0, 1.0], [2.0, 2.0, 2.0]]]), mindspore.float32) >>> scatter_sub = ops.ScatterSub() >>> output = scatter_sub(input_x, indices, updates) >>> print(output) [[-1. -1. -1.] [-1. -1. -1.]] >>> # for input_x will be updated after the operation is completed. input_x need to be re-initialized. >>> input_x = Parameter(Tensor(np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), mindspore.float32), name="x") >>> # for indices = [[0, 1], [1, 1]] >>> # step 1: [0, 1] >>> # input_x[0] = [0.0, 0.0, 0.0] - [1.0, 1.0, 1.0] = [-1.0, -1.0, -1.0] >>> # input_x[1] = [0.0, 0.0, 0.0] - [3.0, 3.0, 3.0] = [-3.0, -3.0, -3.0] >>> # step 2: [1, 1] >>> # input_x[1] = [-3.0, -3.0, -3.0] - [7.0, 7.0, 7.0] = [-10.0, -10.0, -10.0] >>> # input_x[1] = [-10.0, -10.0, -10.0] - [9.0, 9.0, 9.0] = [-19.0, -19.0, -19.0] >>> indices = Tensor(np.array([[0, 1], [1, 1]]), mindspore.int32) >>> updates = Tensor(np.array([[[1.0, 1.0, 1.0], [3.0, 3.0, 3.0]], ... [[7.0, 7.0, 7.0], [9.0, 9.0, 9.0]]]), mindspore.float32) >>> scatter_sub = ops.ScatterSub() >>> output = scatter_sub(input_x, indices, updates) >>> print(output) [[ -1. -1. -1.] [-19. -19. -19.]] >>> # for input_x will be updated after the operation is completed. input_x need to be re-initialized. >>> input_x = Parameter(Tensor(np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), mindspore.float32), name="x") >>> # for indices = [[1, 0], [1, 1]] >>> # step 1: [1, 0] >>> # input_x[0] = [0.0, 0.0, 0.0] - [3.0, 3.0, 3.0] = [-3.0, -3.0, -3.0] >>> # input_x[1] = [0.0, 0.0, 0.0] - [1.0, 1.0, 1.0] = [-1.0, -1.0, -1.0] >>> # step 2: [1, 1] >>> # input_x[1] = [-1.0, -1.0, -1.0] - [7.0, 7.0, 7.0] = [-8.0, -8.0, -8.0] >>> # input_x[1] = [-8.0, -8.0, -8.0] - [9.0, 9.0, 9.0] = [-17.0, -17.0, -17.0] >>> indices = Tensor(np.array([[1, 0], [1, 1]]), mindspore.int32) >>> updates = Tensor(np.array([[[1.0, 1.0, 1.0], [3.0, 3.0, 3.0]], ... [[7.0, 7.0, 7.0], [9.0, 9.0, 9.0]]]), mindspore.float32) >>> scatter_sub = ops.ScatterSub() >>> output = scatter_sub(input_x, indices, updates) >>> print(output) [[ -3. -3. -3.] [-17. -17. -17.]] >>> # for input_x will be updated after the operation is completed. input_x need to be re-initialized. >>> input_x = Parameter(Tensor(np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), mindspore.float32), name="x") >>> # for indices = [[0, 1], [0, 1]] >>> # step 1: [0, 1] >>> # input_x[0] = [0.0, 0.0, 0.0] - [1.0, 1.0, 1.0] = [-1.0, -1.0, -1.0] >>> # input_x[1] = [0.0, 0.0, 0.0] - [3.0, 3.0, 3.0] = [-3.0, -3.0, -3.0] >>> # step 2: [0, 1] >>> # input_x[0] = [-1.0, -1.0, -1.0] - [7.0, 7.0, 7.0] = [-8.0, -8.0, -8.0] >>> # input_x[1] = [-3.0, -3.0, -3.0] - [9.0, 9.0, 9.0] = [-12.0, -12.0, -12.0] >>> indices = Tensor(np.array([[0, 1], [0, 1]]), mindspore.int32) >>> updates = Tensor(np.array([[[1.0, 1.0, 1.0], [3.0, 3.0, 3.0]], ... [[7.0, 7.0, 7.0], [9.0, 9.0, 9.0]]]), mindspore.float32) >>> scatter_sub = ops.ScatterSub() >>> output = scatter_sub(input_x, indices, updates) >>> print(output) [[ -8. -8. -8.] [-12. -12. -12.]] """ @prim_attr_register def __init__(self, use_locking=False): """Initialize ScatterSub""" validator.check_value_type('use_locking', use_locking, [bool], self.name) self.init_prim_io_names(inputs=['x', 'indices', 'updates'], outputs=['y']) self.add_prim_attr('side_effect_mem', True) class ScatterMul(_ScatterOp): r""" Updates the value of the input tensor through the multiply operation. Using given values to update tensor value through the mul operation, along with the input indices. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value. for each `i, ..., j` in `indices.shape`: .. math:: \text{input_x}[\text{indices}[i, ..., j], :] \mathrel{*}= \text{updates}[i, ..., j, :] Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent. If they have different data types, the lower priority data type will be converted to the relatively highest priority data type. Args: use_locking (bool): Whether protect the assignment by a lock. Default: False. Inputs: - **input_x** (Parameter) - The target tensor, with data type of Parameter. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. - **indices** (Tensor) - The index to do min operation whose data type must be mindspore.int32. - **updates** (Tensor) - The tensor doing the min operation with `input_x`, the data type is same as `input_x`, the shape is `indices_shape + x_shape[1:]`. Outputs: Tensor, the updated `input_x`, has the same shape and type as `input_x`. Raises: TypeError: If `use_locking` is not a bool. TypeError: If `indices` is not an int32. ValueError: If the shape of `updates` is not equal to `indices_shape + x_shape[1:]`. RuntimeError: If the data type of `input_x` and `updates` conversion of Parameter is required when data type conversion of Parameter is not supported. Supported Platforms: ``Ascend`` ``CPU`` Examples: >>> input_x = Parameter(Tensor(np.array([[1.0, 1.0, 1.0], [2.0, 2.0, 2.0]]), mindspore.float32), name="x") >>> indices = Tensor(np.array([0, 1]), mindspore.int32) >>> updates = Tensor(np.array([[2.0, 2.0, 2.0], [2.0, 2.0, 2.0]]), mindspore.float32) >>> scatter_mul = ops.ScatterMul() >>> output = scatter_mul(input_x, indices, updates) >>> print(output) [[2. 2. 2.] [4. 4. 4.]] >>> # for input_x will be updated after the operation is completed. input_x need to be re-initialized. >>> input_x = Parameter(Tensor(np.array([[1.0, 1.0, 1.0], [2.0, 2.0, 2.0]]), mindspore.float32), name="x") >>> # for indices = [[0, 1], [1, 1]] >>> # step 1: [0, 1] >>> # input_x[0] = [1.0, 1.0, 1.0] * [1.0, 1.0, 1.0] = [1.0, 1.0, 1.0] >>> # input_x[1] = [2.0, 2.0, 2.0] * [3.0, 3.0, 3.0] = [6.0, 6.0, 6.0] >>> # step 2: [1, 1] >>> # input_x[1] = [6.0, 6.0, 6.0] * [7.0, 7.0, 7.0] = [42.0, 42.0, 42.0] >>> # input_x[1] = [42.0, 42.0, 42.0] * [9.0, 9.0, 9.0] = [378.0, 378.0, 378.0] >>> indices = Tensor(np.array([[0, 1], [1, 1]]), mindspore.int32) >>> updates = Tensor(np.array([[[1.0, 1.0, 1.0], [3.0, 3.0, 3.0]], ... [[7.0, 7.0, 7.0], [9.0, 9.0, 9.0]]]), mindspore.float32) >>> scatter_mul = ops.ScatterMul() >>> output = scatter_mul(input_x, indices, updates) >>> print(output) [[ 1. 1. 1.] [378. 378. 378.]] >>> # for input_x will be updated after the operation is completed. input_x need to be re-initialized. >>> input_x = Parameter(Tensor(np.array([[1.0, 1.0, 1.0], [2.0, 2.0, 2.0]]), mindspore.float32), name="x") >>> # for indices = [[1, 0], [1, 1]] >>> # step 1: [1, 0] >>> # input_x[0] = [1.0, 1.0, 1.0] * [3.0, 3.0, 3.0] = [3.0, 3.0, 3.0] >>> # input_x[1] = [2.0, 2.0, 2.0] * [1.0, 1.0, 1.0] = [2.0, 2.0, 2.0] >>> # step 2: [1, 1] >>> # input_x[1] = [2.0, 2.0, 2.0] * [7.0, 7.0, 7.0] = [14.0, 14.0, 14.0] >>> # input_x[1] = [14.0, 14.0, 14.0] * [9.0, 9.0, 9.0] = [126.0, 126.0, 126.0] >>> indices = Tensor(np.array([[1, 0], [1, 1]]), mindspore.int32) >>> updates = Tensor(np.array([[[1.0, 1.0, 1.0], [3.0, 3.0, 3.0]], ... [[7.0, 7.0, 7.0], [9.0, 9.0, 9.0]]]), mindspore.float32) >>> scatter_mul = ops.ScatterMul() >>> output = scatter_mul(input_x, indices, updates) >>> print(output) [[ 3. 3. 3.] [126. 126. 126.]] >>> # for input_x will be updated after the operation is completed. input_x need to be re-initialized. >>> input_x = Parameter(Tensor(np.array([[1.0, 1.0, 1.0], [2.0, 2.0, 2.0]]), mindspore.float32), name="x") >>> # for indices = [[0, 1], [0, 1]] >>> # step 1: [0, 1] >>> # input_x[0] = [1.0, 1.0, 1.0] * [1.0, 1.0, 1.0] = [1.0, 1.0, 1.0] >>> # input_x[1] = [2.0, 2.0, 2.0] * [3.0, 3.0, 3.0] = [6.0, 6.0, 6.0] >>> # step 2: [0, 1] >>> # input_x[0] = [1.0, 1.0, 1.0] * [7.0, 7.0, 7.0] = [7.0, 7.0, 7.0] >>> # input_x[1] = [6.0, 6.0, 6.0] * [9.0, 9.0, 9.0] = [54.0, 54.0, 54.0] >>> indices = Tensor(np.array([[0, 1], [0, 1]]), mindspore.int32) >>> updates = Tensor(np.array([[[1.0, 1.0, 1.0], [3.0, 3.0, 3.0]], ... [[7.0, 7.0, 7.0], [9.0, 9.0, 9.0]]]), mindspore.float32) >>> scatter_mul = ops.ScatterMul() >>> output = scatter_mul(input_x, indices, updates) >>> print(output) [[ 7. 7. 7.] [54. 54. 54.]] """ class ScatterDiv(_ScatterOp): r""" Updates the value of the input tensor through the divide operation. Using given values to update tensor value through the div operation, along with the input indices. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value. for each `i, ..., j` in `indices.shape`: .. math:: \text{input_x}[\text{indices}[i, ..., j], :] \mathrel{/}= \text{updates}[i, ..., j, :] Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent. If they have different data types, the lower priority data type will be converted to the relatively highest priority data type. Args: use_locking (bool): Whether protect the assignment by a lock. Default: False. Inputs: - **input_x** (Parameter) - The target tensor, with data type of Parameter. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. - **indices** (Tensor) - The index to do min operation whose data type must be mindspore.int32. - **updates** (Tensor) - The tensor doing the min operation with `input_x`, the data type is same as `input_x`, the shape is `indices_shape + x_shape[1:]`. Outputs: Tensor, the updated `input_x`, has the same shape and type as `input_x`. Raises: TypeError: If `use_locking` is not a bool. TypeError: If `indices` is not an int32. ValueError: If the shape of `updates` is not equal to `indices_shape + x_shape[1:]`. RuntimeError: If the data type of `input_x` and `updates` conversion of Parameter is required when data type conversion of Parameter is not supported. Supported Platforms: ``Ascend`` ``CPU`` Examples: >>> input_x = Parameter(Tensor(np.array([[6.0, 6.0, 6.0], [2.0, 2.0, 2.0]]), mindspore.float32), name="x") >>> indices = Tensor(np.array([0, 1]), mindspore.int32) >>> updates = Tensor(np.array([[2.0, 2.0, 2.0], [2.0, 2.0, 2.0]]), mindspore.float32) >>> scatter_div = ops.ScatterDiv() >>> output = scatter_div(input_x, indices, updates) >>> print(output) [[3. 3. 3.] [1. 1. 1.]] >>> # for input_x will be updated after the operation is completed. input_x need to be re-initialized. >>> input_x = Parameter(Tensor(np.array([[105.0, 105.0, 105.0], ... [315.0, 315.0, 315.0]]), mindspore.float32), name="x") >>> # for indices = [[0, 1], [1, 1]] >>> # step 1: [0, 1] >>> # input_x[0] = [105.0, 105.0, 105.0] / [1.0, 1.0, 1.0] = [105.0, 105.0, 105.0] >>> # input_x[1] = [315.0, 315.0, 315.0] / [3.0, 3.0, 3.0] = [105.0, 105.0, 105.0] >>> # step 2: [1, 1] >>> # input_x[1] = [105.0, 105.0, 105.0] / [5.0, 5.0, 5.0] = [21.0, 21.0, 21.0] >>> # input_x[1] = [21.0, 21.0, 21.0] / [7.0, 7.0, 7.0] = [3.0, 3.0, 3.0] >>> indices = Tensor(np.array([[0, 1], [1, 1]]), mindspore.int32) >>> updates = Tensor(np.array([[[1.0, 1.0, 1.0], [3.0, 3.0, 3.0]], ... [[5.0, 5.0, 5.0], [7.0, 7.0, 7.0]]]), mindspore.float32) >>> scatter_div = ops.ScatterDiv() >>> output = scatter_div(input_x, indices, updates) >>> print(output) [[105. 105. 105.] [ 3. 3. 3.]] >>> # for input_x will be updated after the operation is completed. input_x need to be re-initialized. >>> input_x = Parameter(Tensor(np.array([[105.0, 105.0, 105.0], ... [315.0, 315.0, 315.0]]), mindspore.float32), name="x") >>> # for indices = [[1, 0], [1, 1]] >>> # step 1: [1, 0] >>> # input_x[0] = [105.0, 105.0, 105.0] / [3.0, 3.0, 3.0] = [35.0, 35.0, 35.0] >>> # input_x[1] = [315.0, 315.0, 315.0] / [1.0, 1.0, 1.0] = [315.0, 315.0, 315.0] >>> # step 2: [1, 1] >>> # input_x[1] = [315.0, 315.0, 315.0] / [5.0, 5.0, 5.0] = [63.0 63.0 63.0] >>> # input_x[1] = [63.0 63.0 63.0] / [7.0, 7.0, 7.0] = [9.0, 9.0, 9.0] >>> indices = Tensor(np.array([[1, 0], [1, 1]]), mindspore.int32) >>> updates = Tensor(np.array([[[1.0, 1.0, 1.0], [3.0, 3.0, 3.0]], ... [[5.0, 5.0, 5.0], [7.0, 7.0, 7.0]]]), mindspore.float32) >>> scatter_div = ops.ScatterDiv() >>> output = scatter_div(input_x, indices, updates) >>> print(output) [[35. 35. 35.] [ 9. 9. 9.]] >>> # for input_x will be updated after the operation is completed. input_x need to be re-initialized. >>> input_x = Parameter(Tensor(np.array([[105.0, 105.0, 105.0], ... [315.0, 315.0, 315.0]]), mindspore.float32), name="x") >>> # for indices = [[0, 1], [0, 1]] >>> # step 1: [0, 1] >>> # input_x[0] = [105.0, 105.0, 105.0] / [1.0, 1.0, 1.0] = [105.0, 105.0, 105.0] >>> # input_x[1] = [315.0, 315.0, 315.0] / [3.0, 3.0, 3.0] = [105.0, 105.0, 105.0] >>> # step 2: [0, 1] >>> # input_x[0] = [105.0, 105.0, 105.0] / [5.0, 5.0, 5.0] = [21.0, 21.0, 21.0] >>> # input_x[1] = [105.0, 105.0, 105.0] / [7.0, 7.0, 7.0] = [15.0, 15.0, 15.0] >>> indices = Tensor(np.array([[0, 1], [0, 1]]), mindspore.int32) >>> updates = Tensor(np.array([[[1.0, 1.0, 1.0], [3.0, 3.0, 3.0]], ... [[5.0, 5.0, 5.0], [7.0, 7.0, 7.0]]]), mindspore.float32) >>> scatter_div = ops.ScatterDiv() >>> output = scatter_div(input_x, indices, updates) >>> print(output) [[21. 21. 21.] [15. 15. 15.]] """ class ScatterNdAdd(Primitive): r""" Applies sparse addition to individual values or slices in a tensor. Using given values to update tensor value through the add operation, along with the input indices. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value. `input_x` has rank P and `indices` has rank Q where `Q >= 2`. `indices` has shape :math:`(i_0, i_1, ..., i_{Q-2}, N)` where `N <= P`. The last dimension of `indices` (with length `N` ) indicates slices along the `N` th dimension of `input_x`. `updates` is a tensor of rank `Q-1+P-N`. Its shape is: :math:`(i_0, i_1, ..., i_{Q-2}, x\_shape_N, ..., x\_shape_{P-1})`. Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent. If they have different data types, the lower priority data type will be converted to the relatively highest priority data type. Args: use_locking (bool): Whether protect the assignment by a lock. Default: False. Inputs: - **input_x** (Parameter) - The target tensor, with data type of Parameter. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. - **indices** (Tensor) - The index to do min operation whose data type must be mindspore.int32. The rank of indices must be at least 2 and `indices_shape[-1] <= len(shape)`. - **updates** (Tensor) - The tensor doing the min operation with `input_x`, the data type is same as `input_x`, the shape is `indices_shape[:-1] + x_shape[indices_shape[-1]:]`. Outputs: Tensor, the updated `input_x`, has the same shape and type as `input_x`. Raises: TypeError: If `use_locking` is not a bool. TypeError: If `indices` is not an int32. ValueError: If the shape of `updates` is not equal to `indices_shape[:-1] + x_shape[indices_shape[-1]:]`. RuntimeError: If the data type of `input_x` and `updates` conversion of Parameter is required when data type conversion of Parameter is not supported. Supported Platforms: ``Ascend`` ``GPU`` Examples: >>> input_x = Parameter(Tensor(np.array([1, 2, 3, 4, 5, 6, 7, 8]), mindspore.float32), name="x") >>> indices = Tensor(np.array([[2], [4], [1], [7]]), mindspore.int32) >>> updates = Tensor(np.array([6, 7, 8, 9]), mindspore.float32) >>> scatter_nd_add = ops.ScatterNdAdd() >>> output = scatter_nd_add(input_x, indices, updates) >>> print(output) [ 1. 10. 9. 4. 12. 6. 7. 17.] >>> input_x = Parameter(Tensor(np.zeros((4, 4, 4)), mindspore.int32)) >>> indices = Tensor(np.array([[0], [2]]), mindspore.int32) >>> updates = Tensor(np.array([[[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]], ... [[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]]]), mindspore.int32) >>> scatter_nd_add = ops.ScatterNdAdd() >>> output = scatter_nd_add(input_x, indices, updates) >>> print(output) [[[1 1 1 1] [2 2 2 2] [3 3 3 3] [4 4 4 4]] [[0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0]] [[5 5 5 5] [6 6 6 6] [7 7 7 7] [8 8 8 8]] [[0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0]]] """ __mindspore_signature__ = ( sig.make_sig('input_x', sig.sig_rw.RW_WRITE, dtype=sig.sig_dtype.T), sig.make_sig('indices', dtype=sig.sig_dtype.T1), sig.make_sig('updates', dtype=sig.sig_dtype.T) ) @prim_attr_register def __init__(self, use_locking=False): """Initialize ScatterNdAdd""" validator.check_value_type('use_locking', use_locking, [bool], self.name) self.init_prim_io_names(inputs=['input_x', 'indices', 'updates'], outputs=['y']) self.add_prim_attr('side_effect_mem', True) class ScatterNdSub(_ScatterNdOp): r""" Applies sparse subtraction to individual values or slices in a tensor. Using given values to update tensor value through the subtraction operation, along with the input indices. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value. `input_x` has rank P and `indices` has rank Q where `Q >= 2`. `indices` has shape :math:`(i_0, i_1, ..., i_{Q-2}, N)` where `N <= P`. The last dimension of `indices` (with length `N` ) indicates slices along the `N` th dimension of `input_x`. `updates` is a tensor of rank `Q-1+P-N`. Its shape is: :math:`(i_0, i_1, ..., i_{Q-2}, x\_shape_N, ..., x\_shape_{P-1})`. Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent. If they have different data types, the lower priority data type will be converted to relatively highest priority data type. Args: use_locking (bool): Whether protect the assignment by a lock. Default: False. Inputs: - **input_x** (Parameter) - The target tensor, with data type of Parameter. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. - **indices** (Tensor) - The index of input tensor, with int32 data type. The rank of indices must be at least 2 and `indices_shape[-1] <= len(shape)`. - **updates** (Tensor) - The tensor to be updated to the input tensor, has the same type as input. The shape is `indices_shape[:-1] + x_shape[indices_shape[-1]:]`. Outputs: Tensor, has the same shape and type as `input_x`. Raises: TypeError: If `use_locking` is not a bool. TypeError: If `indices` is not an int32. ValueError: If the shape of `updates` is not equal to `indices_shape[:-1] + x_shape[indices_shape[-1]:]`. RuntimeError: If the data type of `input_x` and `updates` conversion of Parameter is required when data type conversion of Parameter is not supported. Supported Platforms: ``Ascend`` ``GPU`` Examples: >>> input_x = Parameter(Tensor(np.array([1, 2, 3, 4, 5, 6, 7, 8]), mindspore.float32), name="x") >>> indices = Tensor(np.array([[2], [4], [1], [7]]), mindspore.int32) >>> updates = Tensor(np.array([6, 7, 8, 9]), mindspore.float32) >>> scatter_nd_sub = ops.ScatterNdSub() >>> output = scatter_nd_sub(input_x, indices, updates) >>> print(output) [ 1. -6. -3. 4. -2. 6. 7. -1.] >>> input_x = Parameter(Tensor(np.zeros((4, 4, 4)), mindspore.int32)) >>> indices = Tensor(np.array([[0], [2]]), mindspore.int32) >>> updates = Tensor(np.array([[[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]], ... [[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]]]), mindspore.int32) >>> scatter_nd_sub = ops.ScatterNdSub() >>> output = scatter_nd_sub(input_x, indices, updates) >>> print(output) [[[-1 -1 -1 -1] [-2 -2 -2 -2] [-3 -3 -3 -3] [-4 -4 -4 -4]] [[ 0 0 0 0] [ 0 0 0 0] [ 0 0 0 0] [ 0 0 0 0]] [[-5 -5 -5 -5] [-6 -6 -6 -6] [-7 -7 -7 -7] [-8 -8 -8 -8]] [[ 0 0 0 0] [ 0 0 0 0] [ 0 0 0 0] [ 0 0 0 0]]] """ class ScatterNonAliasingAdd(Primitive): """ Applies sparse addition to the input using individual values or slices. Using given values to update tensor value through the add operation, along with the input indices. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value. Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent. If they have different data types, the lower priority data type will be converted to the relatively highest priority data type. Inputs: - **input_x** (Parameter) - The target parameter. The data type must be float16, float32 or int32. - **indices** (Tensor) - The index to perform the addition operation whose data type must be mindspore.int32. - **updates** (Tensor) - The tensor that performs the addition operation with `input_x`, the data type is the same as `input_x`, the shape is `indices_shape[:-1] + x_shape[indices_shape[-1]:]`. Outputs: Parameter, the updated `input_x`. Raises: TypeError: If dtype of `indices` is not int32. TypeError: If dtype of `input_x` is not one of float16, float32, int32. ValueError: If the shape of `updates` is not equal to `indices_shape[:-1] + x_shape[indices_shape[-1]:]`. RuntimeError: If the data type of `input_x` and `updates` conversion of Parameter is required when data type conversion of Parameter is not supported. Supported Platforms: ``Ascend`` Examples: >>> input_x = Parameter(Tensor(np.array([1, 2, 3, 4, 5, 6, 7, 8]), mindspore.float32), name="x") >>> indices = Tensor(np.array([[2], [4], [1], [7]]), mindspore.int32) >>> updates = Tensor(np.array([6, 7, 8, 9]), mindspore.float32) >>> scatter_non_aliasing_add = ops.ScatterNonAliasingAdd() >>> output = scatter_non_aliasing_add(input_x, indices, updates) >>> print(output) [ 1. 10. 9. 4. 12. 6. 7. 17.] """ __mindspore_signature__ = ( sig.make_sig('input_x', sig.sig_rw.RW_WRITE, dtype=sig.sig_dtype.T), sig.make_sig('indices', dtype=sig.sig_dtype.T1), sig.make_sig('updates', dtype=sig.sig_dtype.T) ) @prim_attr_register def __init__(self): """Initialize ScatterNonAliasingAdd""" self.init_prim_io_names(inputs=['input_x', 'indices', 'updates'], outputs=['y']) self.add_prim_attr('side_effect_mem', True) class SpaceToDepth(PrimitiveWithInfer): r""" Rearrange blocks of spatial data into depth. The output tensor's `height` dimension is :math:`height / block\_size`. The output tensor's `weight` dimension is :math:`weight / block\_size`. The depth of output tensor is :math:`block\_size * block\_size * input\_depth`. The input tensor's height and width must be divisible by `block_size`. The data format is "NCHW". Args: block_size (int): The block size used to divide spatial data. It must be >= 2. Inputs: - **x** (Tensor) - The target tensor. The data type is Number. It must be a 4-D tensor. Outputs: Tensor, the same data type as `x`. It must be a 4-D tensor. Tensor of shape :math:`(N, ( C_{in} * \text{block_size} * 2), H_{in} / \text{block_size}, W_{in} / \text{block_size})`. Raises: TypeError: If `block_size` is not an int. ValueError: If `block_size` is less than 2. ValueError: If length of shape of `x` is not equal to 4. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> x = Tensor(np.random.rand(1,3,2,2), mindspore.float32) >>> block_size = 2 >>> space_to_depth = ops.SpaceToDepth(block_size) >>> output = space_to_depth(x) >>> print(output.shape) (1, 12, 1, 1) """ @prim_attr_register def __init__(self, block_size): """Initialize SpaceToDepth""" self.init_prim_io_names(inputs=['x'], outputs=['y']) validator.check_value_type('block_size', block_size, [int], self.name) validator.check('block_size', block_size, '', 2, Rel.GE) self.block_size = block_size self.add_prim_attr("data_format", "NCHW") def infer_shape(self, x_shape): validator.check('x dimension', len(x_shape), '', 4, Rel.EQ) out_shape = copy.deepcopy(x_shape) for i in range(2): if out_shape[i + 2] % self.block_size != 0: msg_prefix = "2nd" if i + 2 == 2 else "3rd" raise ValueError(f"For '{self.name}', the shape of output with index {i + 2} must be divided " f"exactly by 'block_size', but got the {msg_prefix} dimension " f"of output: {out_shape[i + 2]} and " f"'block_size': {self.block_size}.") out_shape[i + 2] //= self.block_size out_shape[1] *= self.block_size * self.block_size return out_shape def infer_dtype(self, x_dtype): validator.check_subclass("x_dtype", x_dtype, mstype.tensor, self.name) return x_dtype class DepthToSpace(PrimitiveWithInfer): r""" Rearrange blocks of depth data into spatial dimensions. This is the reverse operation of SpaceToDepth. The depth of output tensor is :math:`input\_depth / (block\_size * block\_size)`. The output tensor's `height` dimension is :math:`height * block\_size`. The output tensor's `weight` dimension is :math:`weight * block\_size`. The input tensor's depth must be divisible by `block_size * block_size`. The data format is "NCHW". Args: block_size (int): The block size used to divide depth data. It must be >= 2. Inputs: - **x** (Tensor) - The target tensor. It must be a 4-D tensor with shape :math:`(N, C_{in}, H_{in}, W_{in})`. The data type is Number. Outputs: Tensor of shape :math:`(N, C_{in} / \text{block_size} ^ 2, H_{in} * \text{block_size}, W_{in} * \text{block_size})`. Raises: TypeError: If `block_size` is not an int. ValueError: If `block_size` is less than 2. ValueError: If length of shape of `x` is not equal to 4. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> x = Tensor(np.random.rand(1, 12, 1, 1), mindspore.float32) >>> block_size = 2 >>> depth_to_space = ops.DepthToSpace(block_size) >>> output = depth_to_space(x) >>> print(output.shape) (1, 3, 2, 2) """ @prim_attr_register def __init__(self, block_size): """Initialize DepthToSpace""" self.init_prim_io_names(inputs=['x'], outputs=['y']) validator.check_value_type('block_size', block_size, [int], self.name) validator.check('block_size', block_size, '', 2, Rel.GE, self.name) self.block_size = block_size self.add_prim_attr("data_format", "NCHW") def infer_shape(self, x_shape): validator.check('x dimension', len(x_shape), '', 4, Rel.EQ) out_shape = copy.deepcopy(x_shape) for i in range(2): out_shape[i + 2] *= self.block_size validator.check_int(x_shape[1] % (self.block_size * self.block_size), 0, Rel.EQ, 'x_shape[1] % (block_size*block_size)', self.name) out_shape[1] //= self.block_size * self.block_size return out_shape def infer_dtype(self, x_dtype): validator.check_subclass("x_dtype", x_dtype, mstype.tensor, self.name) return x_dtype class SpaceToBatch(PrimitiveWithInfer): r""" SpaceToBatch is deprecated. Please use :class:`mindspore.ops.SpaceToBatchND` instead. Divides spatial dimensions into blocks and combines the block size with the original batch. This operation will divide spatial dimensions (H, W) into blocks with `block_size`, the output tensor's H and W dimension is the corresponding number of blocks after division. The output tensor's batch dimension is the product of the original batch and the square of block_size. Before division, the spatial dimensions of the input are zero padded according to paddings if necessary. Args: block_size (int): The block size of dividing blocks with value greater than or equal to 2. paddings (Union[tuple, list]): The padding values for H and W dimension, containing 2 subtraction lists. Each subtraction list contains 2 integer value. All values must be greater than 0. paddings[i] specifies the paddings for the spatial dimension i, which corresponds to the input dimension i+2. It is required that input_shape[i+2]+paddings[i][0]+paddings[i][1] is divisible by block_size. Inputs: - **input_x** (Tensor) - The input tensor. It must be a 4-D tensor. The data type is Number. Outputs: Tensor, the output tensor with the same data type as input. Assume input shape is :math:`(n, c, h, w)` with :math:`block\_size` and :math:`paddings`. The shape of the output tensor will be :math:`(n', c', h', w')`, where :math:`n' = n*(block\_size*block\_size)` :math:`c' = c` :math:`h' = (h+paddings[0][0]+paddings[0][1])//block\_size` :math:`w' = (w+paddings[1][0]+paddings[1][1])//block\_size` Raises: TypeError: If `block_size` is not an int. ValueError: If `block_size` is less than 2. Supported Platforms: Deprecated Examples: >>> block_size = 2 >>> paddings = [[0, 0], [0, 0]] >>> space_to_batch = ops.SpaceToBatch(block_size, paddings) >>> input_x = Tensor(np.array([[[[1, 2], [3, 4]]]]), mindspore.float32) >>> output = space_to_batch(input_x) >>> print(output) [[[[1.]]] [[[2.]]] [[[3.]]] [[[4.]]]] """ @prim_attr_register def __init__(self, block_size, paddings): """Initialize SpaceToBatch""" logger.warning("WARN_DEPRECATED: The usage of SpaceToBatch is deprecated." " Please use SpaceToBatchND.") validator.check_value_type('block_size', block_size, [int], self.name) validator.check('block_size', block_size, '', 2, Rel.GE, self.name) self.block_size = block_size validator.check('paddings shape', np.array(paddings).shape, '', (2, 2), Rel.EQ, self.name) for elem in itertools.chain(*paddings): validator.check_non_negative_int(elem, 'paddings element', self.name) validator.check_value_type('paddings element', elem, [int], self.name) self.paddings = paddings def infer_dtype(self, x_dtype): validator.check_tensor_dtype_valid('input_x', x_dtype, mstype.number_type, self.name) return x_dtype def infer_shape(self, x_shape): validator.check_equal_int(len(x_shape), 4, 'rank of input_x', self.name) out_shape = copy.deepcopy(x_shape) for i in range(2): padded = out_shape[i + 2] + self.paddings[i][0] + self.paddings[i][1] if padded % self.block_size != 0: msg_ndim = "2nd" if i + 2 == 2 else "3rd" raise ValueError(f"For '{self.name}', the shape of the output tensor should be " f"divisible by 'block_size', but got the {msg_ndim} dimension of output: {padded} and " f"'block_size': {self.block_size}. Please check the official homepage " f"for more information about the output tensor.") out_shape[i + 2] = padded // self.block_size out_shape[0] *= self.block_size * self.block_size return out_shape class BatchToSpace(PrimitiveWithInfer): r""" Divides batch dimension with blocks and interleaves these blocks back into spatial dimensions. This operation will divide batch dimension N into blocks with block_size, the output tensor's N dimension is the corresponding number of blocks after division. The output tensor's H, W dimension is product of original H, W dimension and block_size with given amount to crop from dimension, respectively. Args: block_size (int): The block size of division, has the value not less than 2. crops (Union[list(int), tuple(int)]): The crop value for H and W dimension, containing 2 subtraction lists. Each list contains 2 integers. All values must be not less than 0. crops[i] specifies the crop values for the spatial dimension i, which corresponds to the input dimension i+2. It is required that :math:`input\_shape[i+2]*block\_size >= crops[i][0]+crops[i][1]` Inputs: - **input_x** (Tensor) - The input tensor. It must be a 4-D tensor, dimension 0 must be divisible by product of `block_shape`. The data type is float16 or float32. Outputs: Tensor, the output tensor with the same type as input. Assume input shape is (n, c, h, w) with block_size and crops. The output shape will be (n', c', h', w'), where :math:`n' = n//(block\_size*block\_size)` :math:`c' = c` :math:`h' = h*block\_size-crops[0][0]-crops[0][1]` :math:`w' = w*block\_size-crops[1][0]-crops[1][1]` Raises: TypeError: If `block_size` or element of `crops` is not an int. TypeError: If `crops` is neither list nor tuple. ValueError: If `block_size` is less than 2. Supported Platforms: ``Ascend`` ``GPU`` Examples: >>> block_size = 2 >>> crops = [[0, 0], [0, 0]] >>> batch_to_space = ops.BatchToSpace(block_size, crops) >>> input_x = Tensor(np.array([[[[1]]], [[[2]]], [[[3]]], [[[4]]]]), mindspore.float32) >>> output = batch_to_space(input_x) >>> print(output) [[[[1. 2.] [3. 4.]]]] """ @prim_attr_register def __init__(self, block_size, crops): """Initialize BatchToSpace""" logger.warning("WARN_DEPRECATED: The usage of BatchToSpace is deprecated." " Please use BatchToSpaceND.") validator.check_value_type('block_size', block_size, [int], self.name) validator.check('block_size', block_size, '', 2, Rel.GE, self.name) self.block_size = block_size validator.check_value_type('crops type', crops, [list, tuple], self.name) validator.check('crops shape', np.array(crops).shape, '', (2, 2)) for elem in itertools.chain(*crops): validator.check_non_negative_int(elem, 'crops element', self.name) validator.check_value_type('crops element', elem, [int], self.name) self.crops = crops def infer_dtype(self, x_dtype): validator.check_tensor_dtype_valid('input_x', x_dtype, mstype.number_type, self.name) return x_dtype def infer_shape(self, x_shape): validator.check('rank of input_x', len(x_shape), '', 4) out_shape = copy.deepcopy(x_shape) for i in range(2): x_block_prod = out_shape[i + 2] * self.block_size crops_sum = self.crops[i][0] + self.crops[i][1] validator.check("x block shape prod", x_block_prod, 'crops sum', crops_sum, Rel.GT, self.name) out_shape[i + 2] = x_block_prod - crops_sum block_size_prod = self.block_size * self.block_size if out_shape[0] % block_size_prod != 0: raise ValueError(f"For '{self.name}', the shape of output with index 0 must be divided exactly " f"by block_size_prod, but got the shape of output: {out_shape} and " f"block_size_prod: {block_size_prod}.") out_shape[0] = out_shape[0] // block_size_prod return out_shape class SpaceToBatchND(PrimitiveWithInfer): r""" Divides spatial dimensions into blocks and combines the block size with the original batch. This operation will divide spatial dimensions (H, W) into blocks with block_shape, the output tensor's H and W dimension is the corresponding number of blocks after division. The output tensor's batch dimension is the product of the original batch and the product of `block_shape`. Before division, the spatial dimensions of the input are zero padded according to paddings if necessary. Args: block_shape (Union[list(int), tuple(int), int]): The block shape of dividing block with all value greater than 1. If `block_shape` is a tuple or list, the length of `block_shape` is M corresponding to the number of spatial dimensions. If `block_shape` is an int, the block size of M dimensions are the same, equal to `block_shape`. M must be 2. paddings (Union[tuple, list]): The padding values for H and W dimension, containing 2 subtraction list. Each contains 2 integer value. All values must be greater than 0. `paddings[i]` specifies the paddings for the spatial dimension i, which corresponds to the input dimension i+2. It is required that input_shape[i+2]+paddings[i][0]+paddings[i][1] is divisible by block_shape[i]. Inputs: - **input_x** (Tensor) - The input tensor. It must be a 4-D tensor. Outputs: Tensor, the output tensor with the same data type as input. Assume input shape is :math:`(n, c, h, w)` with :math:`block\_shape` and :math:`paddings`. The shape of the output tensor will be :math:`(n', c', h', w')`, where :math:`n' = n*(block\_shape[0]*block\_shape[1])` :math:`c' = c` :math:`h' = (h+paddings[0][0]+paddings[0][1])//block\_shape[0]` :math:`w' = (w+paddings[1][0]+paddings[1][1])//block\_shape[1]` Raises: TypeError: If `block_shape` is not one of list, tuple, int. TypeError: If `paddings` is neither list nor tuple. ValueError: If length of shape of `block_shape` is not equal to 1. ValueError: If length of `block_shape` or `paddings` is not equal to 2. Supported Platforms: ``Ascend`` Examples: >>> block_shape = [2, 2] >>> paddings = [[0, 0], [0, 0]] >>> space_to_batch_nd = ops.SpaceToBatchND(block_shape, paddings) >>> input_x = Tensor(np.array([[[[1, 2], [3, 4]]]]), mindspore.float32) >>> output = space_to_batch_nd(input_x) >>> print(output) [[[[1.]]] [[[2.]]] [[[3.]]] [[[4.]]]] """ @prim_attr_register def __init__(self, block_shape, paddings): """Initialize SpaceToBatchND""" if isinstance(block_shape, int): block_shape = (block_shape,) * 2 self.add_prim_attr("block_shape", block_shape) validator.check_value_type('block_shape type', block_shape, [list, tuple], self.name) validator.check('block_shape shape', len(np.array(block_shape).shape), '', 1, Rel.EQ, self.name) block_rank = len(block_shape) validator.check('block_shape length', block_rank, '', 2, Rel.EQ, self.name) for elem in block_shape: validator.check('block_shape element', elem, '', 1, Rel.GE, self.name) validator.check_value_type('block_shape element', elem, [int], self.name) self.block_shape = block_shape validator.check_value_type('paddings type', paddings, [list, tuple], self.name) validator.check('paddings length', len(paddings), '', 2, Rel.EQ, self.name) validator.check('paddings shape', np.array(paddings).shape, '', (block_rank, 2), Rel.EQ, self.name) for elem in itertools.chain(*paddings): validator.check_non_negative_int(elem, 'paddings element', self.name) validator.check_value_type('paddings element', elem, [int], self.name) self.paddings = paddings def infer_dtype(self, x_dtype): validator.check_tensor_dtype_valid('input_x', x_dtype, mstype.number_type, self.name) return x_dtype def infer_shape(self, x_shape): x_rank = len(x_shape) validator.check_equal_int(x_rank, 4, 'x_shape rank', self.name) out_shape = copy.deepcopy(x_shape) block_shape_prod = 1 offset = 2 for i in range(len(self.block_shape)): padded = out_shape[i + offset] + self.paddings[i][0] + \ self.paddings[i][1] if padded % self.block_shape[i] != 0: raise ValueError(f"For '{self.name}', the padded should be divisible by 'block_shape', " f"where padded = input_x_shape[i + 2] + paddings[i][0] + paddings[i][1], " f"but got input_x_shape[{i + 2}]: {out_shape[i + offset]}, " f"paddings[{i}][0]: {self.paddings[i][0]} and paddings[{i}][1]: {self.paddings[i][1]}." f" Please check the official api documents for " f"more information about the output tensor.") out_shape[i + offset] = padded // self.block_shape[i] block_shape_prod = block_shape_prod * self.block_shape[i] out_shape[0] *= block_shape_prod return out_shape class BatchToSpaceND(Primitive): r""" Divides batch dimension with blocks and interleaves these blocks back into spatial dimensions. This operation will divide batch dimension N into blocks with block_shape, the output tensor's N dimension is the corresponding number of blocks after division. The output tensor's H, W dimension is the product of original H, W dimension and block_shape with given amount to crop from dimension, respectively. Args: block_shape (Union[list(int), tuple(int), int]): The block shape of dividing block with all value greater than 1. If `block_shape` is a tuple or list, the length of `block_shape` is M corresponding to the number of spatial dimensions. If `block_shape` is an int, the block size of M dimensions are the same, equal to `block_shape`. M must be 2. crops (Union[list(int), tuple(int)]): The crop value for H and W dimension, containing 2 subtraction list, each containing 2 int value. All values must be >= 0. crops[i] specifies the crop values for spatial dimension i, which corresponds to input dimension i+2. It is required that :math:`input\_shape[i+2]*block\_shape[i] > crops[i][0]+crops[i][1]` Inputs: - **input_x** (Tensor) - The input tensor. It must be a 4-D tensor, dimension 0 must be divisible by product of `block_shape`. The data type is float16 or float32. Outputs: Tensor, the output tensor with the same type as input. Assume input shape is (n, c, h, w) with block_shape and crops. The output shape will be (n', c', h', w'), where :math:`n' = n//(block\_shape[0]*block\_shape[1])` :math:`c' = c` :math:`h' = h*block\_shape[0]-crops[0][0]-crops[0][1]` :math:`w' = w*block\_shape[1]-crops[1][0]-crops[1][1]` Raises: TypeError: If `block_shape` is not one of list, tuple, int. TypeError: If `crops` is neither list nor tuple. ValueError: If length of `block_shape` or `crops` is not equal to 2. Supported Platforms: ``Ascend`` Examples: >>> block_shape = [2, 2] >>> crops = [[0, 0], [0, 0]] >>> batch_to_space_nd = ops.BatchToSpaceND(block_shape, crops) >>> input_x = Tensor(np.array([[[[1]]], [[[2]]], [[[3]]], [[[4]]]]), mindspore.float32) >>> output = batch_to_space_nd(input_x) >>> print(output) [[[[1. 2.] [3. 4.]]]] """ @prim_attr_register def __init__(self, block_shape, crops): """Initialize BatchToSpaceND""" if isinstance(block_shape, int): block_shape = (block_shape,) * 2 self.add_prim_attr("block_shape", block_shape) validator.check_value_type('block_shape type', block_shape, [list, tuple], self.name) validator.check('block_shape shape', len(np.array(block_shape).shape), '', 1, Rel.EQ, self.name) block_rank = len(block_shape) validator.check('block_shape length', block_rank, '', 2, Rel.EQ, self.name) for elem in block_shape: validator.check('block_shape element', elem, '', 1, Rel.GE, self.name) validator.check_value_type('block_shape element', elem, [int], self.name) self.block_shape = block_shape validator.check_value_type('crops type', crops, [list, tuple], self.name) validator.check('crops length', len(crops), '', 2, Rel.EQ, self.name) validator.check('crops shape', np.array(crops).shape, '', (block_rank, 2), Rel.EQ, self.name) for elem in itertools.chain(*crops): validator.check_non_negative_int(elem, 'crops element', self.name) validator.check_value_type('crops element', elem, [int], self.name) self.crops = crops class BroadcastTo(Primitive): """ Broadcasts input tensor to a given shape. Input shape can be broadcast to target shape if for each dimension pair they are either equal or input is one or the target dimension is -1. In case of -1 in target shape, it will be replaced by the input shape's value in that dimension. When input shape is broadcast to target shape, it starts with the trailing dimensions. If there is a -1 in the target shape, the -1 cannot be in a leading, non-existing dimension. Args: shape (tuple): The target shape to broadcast. Can be fully specified, or have -1 in one position where it will be substituted by the input tensor's shape in that position, see example. Inputs: - **input_x** (Tensor) - The input tensor. The data type should be one of the following types: float16, float32, int32, int8, uint8. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. Outputs: Tensor, with the given `shape` and the same data type as `input_x`. Raises: TypeError: If `shape` is not a tuple. ValueError: if the target and input shapes are incompatible, or if a - 1 in the target shape is in an invalid location. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> shape = (2, 3) >>> input_x = Tensor(np.array([1, 2, 3]).astype(np.float32)) >>> broadcast_to = ops.BroadcastTo(shape) >>> output = broadcast_to(input_x) >>> print(output) [[1. 2. 3.] [1. 2. 3.]] >>> shape = (-1, 2) >>> input_x = Tensor(np.array([[1], [2]]).astype(np.float32)) >>> broadcast_to = ops.BroadcastTo(shape) >>> output = broadcast_to(input_x) >>> print(output) [[1. 1.] [2. 2.]] """ @prim_attr_register def __init__(self, shape): """Initialize BroadcastTo""" validator.check_value_type("shape", shape, (tuple), self.name) validator.check("shape length", len(shape), "", 0, Rel.GT, self.name) for ix, i in enumerate(shape): validator.check_value_type('target shape index -> ' + str(ix), i, [int], self.name) validator.check("shape element", i, "shape element min limit", -1, Rel.GE, self.name) self.shape = shape class Meshgrid(PrimitiveWithInfer): """ Generates coordinate matrices from given coordinate tensors. Given N one-dimensional coordinate tensors, returns a tuple outputs of N N-D coordinate tensors for evaluating expressions on an N-D grid. Args: indexing ('xy', 'ij', optional): Cartesian ('xy', default) or matrix ('ij') indexing of output. In the 2-D case with inputs of length `M` and `N`, the outputs are of shape `(N, M)` for 'xy' indexing and `(M, N)` for 'ij' indexing. In the 3-D case with inputs of length `M`, `N` and `P`, outputs are of shape `(N, M, P)` for 'xy' indexing and `(M, N, P)` for 'ij' indexing. Inputs: - **input** (Union[tuple]) - A Tuple of N 1-D Tensor objects. The length of input should be greater than 1. The data type is Number. Outputs: Tensors, A Tuple of N N-D Tensor objects. The data type is the same with the Inputs. Raises: TypeError: If `indexing` is not a str or `input` is not a tuple. ValueError: If `indexing` is neither 'xy' nor 'ij'. Supported Platforms: ``Ascend`` ``GPU`` Examples: >>> x = Tensor(np.array([1, 2, 3, 4]).astype(np.int32)) >>> y = Tensor(np.array([5, 6, 7]).astype(np.int32)) >>> z = Tensor(np.array([8, 9, 0, 1, 2]).astype(np.int32)) >>> inputs = (x, y, z) >>> meshgrid = ops.Meshgrid(indexing="xy") >>> output = meshgrid(inputs) >>> print(output) (Tensor(shape=[3, 4, 5], dtype=Int32, value= [[[1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [4, 4, 4, 4, 4]], [[1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [4, 4, 4, 4, 4]], [[1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [4, 4, 4, 4, 4]]]), Tensor(shape=[3, 4, 5], dtype=Int32, value= [[[5, 5, 5, 5, 5], [5, 5, 5, 5, 5], [5, 5, 5, 5, 5], [5, 5, 5, 5, 5]], [[6, 6, 6, 6, 6], [6, 6, 6, 6, 6], [6, 6, 6, 6, 6], [6, 6, 6, 6, 6]], [[7, 7, 7, 7, 7], [7, 7, 7, 7, 7], [7, 7, 7, 7, 7], [7, 7, 7, 7, 7]]]), Tensor(shape=[3, 4, 5], dtype=Int32, value= [[[8, 9, 0, 1, 2], [8, 9, 0, 1, 2], [8, 9, 0, 1, 2], [8, 9, 0, 1, 2]], [[8, 9, 0, 1, 2], [8, 9, 0, 1, 2], [8, 9, 0, 1, 2], [8, 9, 0, 1, 2]], [[8, 9, 0, 1, 2], [8, 9, 0, 1, 2], [8, 9, 0, 1, 2], [8, 9, 0, 1, 2]]])) """ @prim_attr_register def __init__(self, indexing="xy"): """Initialize Meshgrid.""" validator.check_value_type("indexing", indexing, (str), self.name) validator.check_string(indexing.lower(), ["xy", "ij"], "indexing", self.name) self.indexing = indexing def infer_shape(self, x_shape): validator.check_value_type("shape", x_shape, [tuple], self.name) validator.check_int(len(x_shape), 2, Rel.GE, "len of input", self.name) n = len(x_shape) shape_0 = [] for s in x_shape: validator.check_int(len(s), 1, Rel.EQ, 'each input rank', self.name) shape_0.append(s[0]) if self.indexing == "xy": shape_0[0], shape_0[1] = shape_0[1], shape_0[0] out_shape = tuple(tuple(shape_0) for _ in range(n)) return out_shape def infer_dtype(self, x_type): validator.check_subclass("input[0]", x_type[0], mstype.tensor, self.name) n = len(x_type) for i in range(1, n): validator.check('x_type[%d]' % i, x_type[i], 'base', x_type[0], Rel.EQ, self.name, TypeError) return x_type class InplaceUpdate(PrimitiveWithInfer): r""" Updates specified rows with values in `v`. Args: indices (Union[int, tuple]): Indices into the left-most dimension of `x`, and determines which rows of x to update with v. It is an int or tuple, whose value is in [0, the first dimension size of x). Inputs: - **x** (Tensor) - A tensor which to be inplace updated. It can be one of the following data types: float32, float16 and int32. - **v** (Tensor) - A tensor with the same type as `x` and the same dimension size as `x` except the first dimension, which must be the same as the size of `indices`. Outputs: Tensor, with the same type and shape as the input `x`. Raises: TypeError: If `indices` is neither int nor tuple. TypeError: If `indices` is a tuple and its element is not an int. Supported Platforms: ``Ascend`` Examples: >>> indices = (0, 1) >>> x = Tensor(np.array([[1, 2], [3, 4], [5, 6]]), mindspore.float32) >>> v = Tensor(np.array([[0.5, 1.0], [1.0, 1.5]]), mindspore.float32) >>> inplace_update = ops.InplaceUpdate(indices) >>> output = inplace_update(x, v) >>> print(output) [[0.5 1. ] [1. 1.5] [5. 6. ]] """ @prim_attr_register def __init__(self, indices): """Initialize InplaceUpdate""" self.init_prim_io_names(inputs=['x', 'v'], outputs=['y']) self.indices = indices validator.check_value_type("indices", indices, [int, tuple], self.name) if isinstance(indices, int): self.indices = (indices,) for item in self.indices: validator.check_value_type("item of indices", item, [int], self.name) def infer_dtype(self, x_dtype, v_dtype): args = {'x': x_dtype, 'v': v_dtype} valid_type = [mstype.int32, mstype.float16, mstype.float32] validator.check_tensors_dtypes_same_and_valid(args, valid_type, self.name) return x_dtype def infer_shape(self, x_shape, v_shape): validator.check("x", len(x_shape), "v", len(v_shape), Rel.EQ, self.name) validator.check("size of indices", len(self.indices), "v's first dimension", v_shape[0], Rel.EQ, self.name) for i in self.indices: if i < 0 or i >= x_shape[0]: raise ValueError(f"For '{self.name}', the value of indices must be in [0, {x_shape[0]}), " f"but got {i}.") x_rank = len(x_shape) for idx in range(x_rank)[1:]: validator.check('v dim %d' % idx, v_shape[idx], "x dim %d" % idx, x_shape[idx], Rel.EQ, self.name) return x_shape class ReverseSequence(PrimitiveWithInfer): """ Reverses variable length slices. Args: seq_dim (int): The dimension where reversal is performed. Required. batch_dim (int): The input is sliced in this dimension. Default: 0. Inputs: - **x** (Tensor) - The input to reverse, supporting all number types including bool. - **seq_lengths** (Tensor) - Must be a 1-D vector with int32 or int64 types. Outputs: Reversed tensor with the same shape and data type as input. Raises: TypeError: If `seq_dim` or `batch_dim` is not an int. Supported Platforms: ``Ascend`` ``GPU`` Examples: >>> x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), mindspore.float32) >>> seq_lengths = Tensor(np.array([1, 2, 3])) >>> reverse_sequence = ops.ReverseSequence(seq_dim=1) >>> output = reverse_sequence(x, seq_lengths) >>> print(output) [[1. 2. 3.] [5. 4. 6.] [9. 8. 7.]] >>> x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), mindspore.float32) >>> seq_lengths = Tensor(np.array([1, 2, 3])) >>> reverse_sequence = ops.ReverseSequence(seq_dim=0, batch_dim=1) >>> output = reverse_sequence(x, seq_lengths) >>> print(output) [[1. 5. 9.] [4. 2. 6.] [7. 8. 3.]] >>> x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), mindspore.float32) >>> seq_lengths = Tensor(np.array([2, 2, 3])) >>> reverse_sequence = ops.ReverseSequence(seq_dim=1) >>> output = reverse_sequence(x, seq_lengths) >>> print(output) [[2. 1. 3.] [5. 4. 6.] [9. 8. 7.]] >>> x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), mindspore.float32) >>> seq_lengths = Tensor(np.array([3, 2, 3])) >>> reverse_sequence = ops.ReverseSequence(seq_dim=1) >>> output = reverse_sequence(x, seq_lengths) >>> print(output) [[3. 2. 1.] [5. 4. 6.] [9. 8. 7.]] >>> x = Tensor(np.array([[1, 2, 3, 4], [5, 6, 7, 8]]), mindspore.float32) >>> seq_lengths = Tensor(np.array([4, 4])) >>> reverse_sequence = ops.ReverseSequence(seq_dim=1) >>> output = reverse_sequence(x, seq_lengths) >>> print(output) [[4. 3. 2. 1.] [8. 7. 6. 5.]] """ @prim_attr_register def __init__(self, seq_dim, batch_dim=0): """Initialize ReverseSequence""" self.init_prim_io_names(inputs=['x', 'seq_lengths'], outputs=['y']) validator.check_value_type("seq_dim", seq_dim, [int], self.name) self.seq_dim_ = seq_dim validator.check_value_type("batch_dim", batch_dim, [int], self.name) self.batch_dim_ = batch_dim def infer_shape(self, x, seq_lengths): validator.check("seq_dim", self.seq_dim_, "x rank", len(x), Rel.LE, self.name) validator.check("batch_dim", self.batch_dim_, "x rank", len(x), Rel.LE, self.name) validator.check("batch_dim", self.batch_dim_, "seq_dim", self.seq_dim_, Rel.NE, self.name) validator.check("seq_lengths rank", len(seq_lengths), "expected", 1, Rel.EQ, self.name) validator.check("seq_lengths vector size", seq_lengths[0], "input size along batch_dim", x[self.batch_dim_], Rel.EQ, self.name) return x def infer_dtype(self, x, seq_lengths): validator.check_tensor_dtype_valid("x_dtype", x, mstype.number_type + (mstype.bool_,), self.name) validator.check_tensor_dtype_valid("seq_lengths_dtype", seq_lengths, [mstype.int32, mstype.int64], self.name) return x class EditDistance(PrimitiveWithInfer): r""" Computes the Levenshtein Edit Distance. It is used to measure the similarity of two sequences. The inputs are variable-length sequences provided by SparseTensors (hypothesis_indices, hypothesis_values, hypothesis_shape) and (truth_indices, truth_values, truth_shape). .. math:: \operatorname{lev}_{a, b}(i, j)=\left\{\begin{array}{ll} \max (i, j) \qquad \qquad \qquad \qquad \qquad \quad \ \text { if } \min (i, j)=0 \\ \min \left\{\begin{array}{ll} \operatorname{lev}_{a, b}(i-1, j)+1 & \\ \operatorname{lev}_{a, b}(i, j-1)+1 & \text { otherwise. } \\ \operatorname{lev}_{a, b}(i-1, j-1)+1_{\left(a_{i} \neq b_{j}\right)} \end{array}\right. & \end{array}\right. Where the :math:`a` indicates the hypothesis and the :math:`a` indicates the truth. For ease of understanding, i and j here in may be considered as lengths of a and b. Args: normalize (bool): If true, edit distances are normalized by length of truth. Default: True. Inputs: - **hypothesis_indices** (Tensor) - The indices of the hypothesis list SparseTensor. With int64 data type. The shape of tensor is :math:`(N, R)`. - **hypothesis_values** (Tensor) - The values of the hypothesis list SparseTensor. With float32 data type. Must be 1-D vector with length of N. - **hypothesis_shape** (Tensor) - The shape of the hypothesis list SparseTensor. Must be R-length vector with int64 data type. Only constant value is allowed. - **truth_indices** (Tensor) - The indices of the truth list SparseTensor. With int64 data type. The shape of tensor is :math:`(M, R)`. - **truth_values** (Tensor) - The values of the truth list SparseTensor. Must be 1-D vector with length of M. With float32 data type. - **truth_shape** (Tensor) - The shape of the truth list SparseTensor. Must be R-length vector with int64 data type. Only constant value is allowed. Outputs: Tensor, a dense tensor with rank `R-1` and float32 data type. Raises: TypeError: If `normalize` is not a bool. Supported Platforms: ``Ascend`` Examples: >>> import numpy as np >>> from mindspore import context >>> from mindspore import Tensor >>> import mindspore.nn as nn >>> import mindspore.ops as ops >>> class EditDistance(nn.Cell): ... def __init__(self, hypothesis_shape, truth_shape, normalize=True): ... super(EditDistance, self).__init__() ... self.edit_distance = ops.EditDistance(normalize) ... self.hypothesis_shape = hypothesis_shape ... self.truth_shape = truth_shape ... ... def construct(self, hypothesis_indices, hypothesis_values, truth_indices, truth_values): ... return self.edit_distance(hypothesis_indices, hypothesis_values, self.hypothesis_shape, ... truth_indices, truth_values, self.truth_shape) ... >>> hypothesis_indices = Tensor(np.array([[0, 0, 0], [1, 0, 1], [1, 1, 1]]).astype(np.int64)) >>> hypothesis_values = Tensor(np.array([1, 2, 3]).astype(np.float32)) >>> hypothesis_shape = Tensor(np.array([1, 1, 2]).astype(np.int64)) >>> truth_indices = Tensor(np.array([[0, 1, 0], [0, 0, 1], [1, 1, 0], [1, 0, 1]]).astype(np.int64)) >>> truth_values = Tensor(np.array([1, 3, 2, 1]).astype(np.float32)) >>> truth_shape = Tensor(np.array([2, 2, 2]).astype(np.int64)) >>> edit_distance = EditDistance(hypothesis_shape, truth_shape) >>> output = edit_distance(hypothesis_indices, hypothesis_values, truth_indices, truth_values) >>> print(output) [[1. 1.] [1. 1.]] """ @prim_attr_register def __init__(self, normalize=True): """Initialize EditDistance""" self.normalize = validator.check_value_type("normalize", normalize, [bool], self.name) self.set_const_input_indexes([2, 5]) def __infer__(self, h_indices, h_values, h_shape, truth_indices, truth_values, truth_shape): validator.check_valid_input('hypothesis_shape', h_shape['value'], self.name) validator.check_valid_input('truth_shape', truth_shape['value'], self.name) args_int = {"hypothesis_indices": h_indices['dtype'], "hypothesis_shape": h_shape['dtype'], "truth_indices": truth_indices['dtype'], "truth_shape": truth_shape['dtype']} validator.check_tensors_dtypes_same_and_valid(args_int, [mstype.int64], self.name) args = {"hypothesis_values": h_values['dtype'], "truth_values": truth_values['dtype']} validator.check_tensors_dtypes_same_and_valid(args, mstype.number_type, self.name) hypothesis_indices_shp, truth_indices_shp = h_indices['shape'], truth_indices['shape'] validator.check("hypothesis_indices rank", len(hypothesis_indices_shp), "expected", 2, Rel.EQ, self.name) validator.check("truth_indices rank", len(truth_indices_shp), "expected", 2, Rel.EQ, self.name) validator.check("hypothesis_values rank", len(h_values['shape']), "expected", 1, Rel.EQ, self.name) validator.check("hypothesis_shape rank", len(h_shape['shape']), "expected", 1, Rel.EQ, self.name) validator.check("truth_values rank", len(truth_values['shape']), "expected", 1, Rel.EQ, self.name) validator.check("truth_shape rank", len(truth_shape['shape']), "expected", 1, Rel.EQ, self.name) validator.check("hypothesis_values shape", h_values['shape'][0], "hypothesis_indices shape[0]", hypothesis_indices_shp[0], Rel.EQ, self.name) validator.check("hypothesis_shape", h_shape['shape'][0], "hypothesis_indices shape[1]", hypothesis_indices_shp[1], Rel.EQ, self.name) validator.check("truth_values shape", truth_values['shape'][0], "truth_indices shape[0]", truth_indices_shp[0], Rel.EQ, self.name) validator.check("hypothesis_shape", h_shape['shape'][0], "truth_shape", truth_shape['shape'][0], Rel.EQ, self.name) hypothesis_shape_v = h_shape['value'].asnumpy() truth_shape_v = truth_shape['value'].asnumpy() out_shape_rank = len(hypothesis_shape_v) - 1 out_shape = [] for i in range(out_shape_rank): out_shape.append(max(hypothesis_shape_v[i], truth_shape_v[i])) return {'shape': tuple(out_shape), 'dtype': mstype.tensor_type(mstype.float32), 'value': None} class TransShape(PrimitiveWithInfer): """ Transforms the shape of input tensor to target shape. Inputs: - **input_x** (Tensor) - A input tensor. - **out_shape** (tuple[int]) - The shape of output data. Outputs: Tensor, a tensor whose data type is same as 'input_x', and the shape is the same as the `out_shape`. """ @prim_attr_register def __init__(self): """Initialize TransShape.""" self.__setattr_flag__ = True def __infer__(self, x, shape): shp = shape['value'] dtype = x['dtype'] validator.check_tensor_dtype_valid('x', dtype, mstype.number_type + (mstype.bool_,), self.name) self.add_prim_attr('out_shape', tuple(shp)) return {'shape': shp, 'dtype': dtype, 'value': None} class Sort(Primitive): """ Sorts the elements of the input tensor along a given dimension in ascending order by value. Args: axis (int): The dimension to sort along. Default: -1. descending (bool): Controls the sorting order. If descending is True then the elements are sorted in descending order by value. Default: False. .. warning:: Currently, only the data type of Float16 is supported. If use Float32, it may cause loss of accuracy. Inputs: - **x** (Tensor) - The input to sort, with float16 or float32 data type. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. Outputs: - **y1** (Tensor) - A tensor whose values are the sorted values, with the same shape and data type as input. - **y2** (Tensor) - The indices of the elements in the original input tensor. Data type is int32. Raises: TypeError: If `axis` is not an int. TypeError: If `descending` is not a bool. TypeError: If dtype of `x` is neither float16 nor float32. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> x = Tensor(np.array([[8, 2, 1], [5, 9, 3], [4, 6, 7]]), mindspore.float16) >>> sort = ops.Sort() >>> output = sort(x) >>> print(output) (Tensor(shape=[3, 3], dtype=Float16, value= [[ 1.0000e+00, 2.0000e+00, 8.0000e+00], [ 3.0000e+00, 5.0000e+00, 9.0000e+00], [ 4.0000e+00, 6.0000e+00, 7.0000e+00]]), Tensor(shape=[3, 3], dtype=Int32, value= [[2, 1, 0], [2, 0, 1], [0, 1, 2]])) """ @prim_attr_register def __init__(self, axis=-1, descending=False): """Initialize Sort""" self.axis = validator.check_value_type("axis", axis, [int], self.name) self.descending = validator.check_value_type("descending", descending, [bool], self.name) self.init_prim_io_names(inputs=['x'], outputs=['y1', 'y2']) class EmbeddingLookup(PrimitiveWithCheck): """ Returns a slice of input tensor based on the specified indices. This Primitive has the similar functionality as GatherV2 operating on `axis = 0`, but has one more inputs: `offset`. Inputs: - **input_params** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. This represents a Tensor slice, instead of the entire Tensor. Currently, the dimension is restricted to be 2. - **input_indices** (Tensor) - The shape of tensor is :math:`(y_1, y_2, ..., y_S)`. Specifies the indices of elements of the original Tensor. Values can be out of range of `input_params`, and the exceeding part will be filled with 0 in the output. Values do not support negative and the result is undefined if values are negative. The data type should be int32 or int64. - **offset** (int) - Specifies the offset value of this `input_params` slice. Thus the real indices are equal to `input_indices` minus `offset`. Outputs: Tensor, the shape of tensor is :math:`(z_1, z_2, ..., z_N)`. The data type is the same with `input_params`. Raises: TypeError: If dtype of `input_indices` is not int. ValueError: If length of shape of `input_params` is greater than 2. Supported Platforms: ``Ascend`` ``CPU`` ``GPU`` Examples: >>> input_params = Tensor(np.array([[8, 9], [10, 11], [12, 13], [14, 15]]), mindspore.float32) >>> input_indices = Tensor(np.array([[5, 2], [8, 5]]), mindspore.int32) >>> offset = 4 >>> output = ops.EmbeddingLookup()(input_params, input_indices, offset) >>> print(output) [[[10. 11.] [ 0. 0.]] [[ 0. 0.] [10. 11.]]] """ @prim_attr_register def __init__(self): """Initialize EmbeddingLookup.""" self.__setattr_flag__ = True self.init_prim_io_names(inputs=['params', 'indices', 'offset'], outputs=['output']) def __check__(self, params, indices, offset): validator.check_subclass("params", params['dtype'], mstype.tensor, self.name) validator.check_tensor_dtype_valid("indices", indices['dtype'], mstype.int_type, self.name) validator.check_subclass("offset", offset['dtype'], mstype.int_, self.name) indices_shp = indices['shape'] if not indices_shp: raise ValueError(f"For '{self.name}', the dimension of 'input_indices' should not " f"be zero, but got {len(indices_shp)}.") params_shp = params['shape'] if len(params_shp) > 2: raise ValueError(f"For '{self.name}', the dimension of 'input_params' must <= 2, " f"but got {len(params_shp)}.") class GatherD(Primitive): """ Gathers values along an axis specified by dim. For a 3-D tensor, the output is: .. code-block:: output[i][j][k] = x[index[i][j][k]][j][k] # if dim == 0 output[i][j][k] = x[i][index[i][j][k]][k] # if dim == 1 output[i][j][k] = x[i][j][index[i][j][k]] # if dim == 2 If `x` is an n-D tensor with shape :math:`(z_0, z_1, ..., z_i, ..., z_{n-1})` and `dim` = i, the `index` must be an n-D tensor with shape :math:`(z_0, z_1, ..., y, ..., z_{n-1})` where `y`>=1 and the output will have the same shape as `index`. Inputs: - **x** (Tensor) - The source tensor. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. - **dim** (int) - The axis along which to index. It must be int32 or int64. Only constant value is allowed. - **index** (Tensor) - The indices of elements to gather. It can be one of the following data types: int32, int64. The value range of each index element is [-x_rank[dim], x_rank[dim]). Outputs: Tensor, the shape of tensor is :math:`(z_1, z_2, ..., z_N)`, has the same data type with `x`. Raises: TypeError: If dtype of `dim` or `index` is neither int32 nor int64. ValueError: If length of shape of `x` is not equal to length of shape of `index`. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> x = Tensor(np.array([[1, 2], [3, 4]]), mindspore.int32) >>> index = Tensor(np.array([[0, 0], [1, 0]]), mindspore.int32) >>> dim = 1 >>> output = ops.GatherD()(x, dim, index) >>> print(output) [[1 1] [4 3]] """ @prim_attr_register def __init__(self): """Initialize GatherD""" self.init_prim_io_names(inputs=['x', 'dim', 'index'], outputs=['output']) class Identity(PrimitiveWithInfer): """ Returns a Tensor with the same shape and contents as input. Inputs: - **x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. The data type is Number. Outputs: Tensor, the shape of tensor and the data type are the same as `input_x`, :math:`(x_1, x_2, ..., x_R)`. Raises: TypeError: If `x` is not a Tensor. Supported Platforms: ``Ascend`` ``CPU`` ``GPU`` Examples: >>> x = Tensor(np.array([1, 2, 3, 4]), mindspore.int64) >>> output = ops.Identity()(x) >>> print(output) [1 2 3 4] """ # Side effect is identity with input. side_effect_propagate = 1 @prim_attr_register def __init__(self): """Initialize identity""" self.add_prim_attr('side_effect_propagate', 1) def __infer__(self, x): validator.check_subclass("x", x['dtype'], mstype.tensor, self.name) validator.check_tensor_dtype_valid('x', x['dtype'], mstype.number_type + (mstype.bool_,), self.name) out = {'shape': x['shape'], 'dtype': x['dtype'], 'value': None} return out class Range(PrimitiveWithCheck): r""" Creates a sequence of numbers that begins at `start` and extends by increments of `delta` up to but not including `limit`. The types of all 3 inputs must be the same. The type of the resulting tensor is the same as the type of the inputs. Args: maxlen (int): Memory that can fit `maxlen` many elements will be allocated for the output. Optional, must be positive, defaults to 1000000. If the output has more than `maxlen` elements, a runtime error will occur. Inputs: - **start** (Tensor) - A scalar Tensor. The first number in the sequence. Must have type: int32 or float32 - **limit** (Tensor) - A scalar Tensor. Upper limit of the sequence, exclusive. Must have type: int32 or float32 - **delta** (Tensor) - A scalar Tensor. Number that increments `start`. Must have type: int32 or float32 Outputs: A 1-D Tensor, with the same type as the inputs. Supported Platforms: ``GPU`` Examples: >>> start = Tensor(0, mstype.int32) >>> limit = Tensor(10, mstype.int32) >>> delta = Tensor(4, mstype.int32) >>> output = ops.Range()(start, limit, delta) >>> print(output) [0, 4, 8] """ @prim_attr_register def __init__(self, maxlen=1000000): self.init_prim_io_names(inputs=['start', 'limit', 'delta'], outputs=['output']) validator.check_value_type("maxlen", maxlen, [int], self.name) validator.check_positive_int(maxlen, "maxlen", self.name) self.maxlen = maxlen self.add_prim_attr('maxlen', maxlen) def check_shape(self, start_shape, limit_shape, delta_shape): validator.check("start_shape", len(start_shape), "", 0, Rel.EQ, self.name) validator.check("limit_shape", len(limit_shape), "", 0, Rel.EQ, self.name) validator.check("delta_shape", len(delta_shape), "", 0, Rel.EQ, self.name) def check_dtype(self, start_dtype, limit_dtype, delta_dtype): valid_dtypes = [mstype.int32, mstype.float32] inputs = {"start": start_dtype, "limit": limit_dtype, "delta": delta_dtype} validator.check_tensors_dtypes_same_and_valid(inputs, valid_dtypes, self.name) def infer_value(self, start_value, limit_value, delat_value): """Infer the value of input for Range.""" if start_value is not None and limit_value is not None and delat_value is not None: start = np.asscalar(start_value.asnumpy()) limit = np.asscalar(limit_value.asnumpy()) delat = np.asscalar(delat_value.asnumpy()) return Tensor(np.arange(start, limit, delat), dtype=start_value.dtype) return None class MaskedFill(Primitive): """ Fills elements of self tensor with value where mask is True. The shapes of `input` and `mask` need to be the same or broadcast. Inputs: - **input** (Tensor) - The source tensor whose data type is one of float16, float32, int8, int32. - **mask** (Tensor[bool]) - The boolean mask. - **value** (Union[float, Tensor]) – The value to fill in with, which only supports a 0-dimensional tensor or a float number. Outputs: Tensor, has the same type and shape as `input`. Raises: TypeError: If `input` or `mask` is not a tensor. TypeError: If `value` is neither float number nor tensor. TypeError: If dtype of `input` or `value` is not one of float16, float32, int8, int32. TypeError: If dtype of `value` is different from that of `input`. TypeError: If dtype of `mask` is not bool. ValueError: If the shapes of `input` and `mask` could not be broadcast. Supported Platforms: ``Ascend`` Examples: >>> input = Tensor(np.array([1., 2., 3., 4.]), mindspore.float32) >>> mask = Tensor(np.array([True, True, False, True]), mindspore.bool_) >>> output = ops.MaskedFill()(input, mask, 0.5) >>> print(output) [0.5 0.5 3. 0.5] """ @prim_attr_register def __init__(self): self.init_prim_io_names(inputs=['input', 'mask', 'value'], outputs=['output']) class MaskedSelect(PrimitiveWithCheck): """ Returns a new 1-D Tensor which indexes the input tensor according to the boolean mask. The shapes of the mask tensor and the input tensor don't need to match, but they must be broadcastable. Inputs: - **x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. - **mask** (Tensor[bool]) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. Outputs: A 1-D Tensor, with the same type as x. Raises: TypeError: If `x` is not a Tensor. Supported Platforms: ``Ascend`` ``CPU`` Examples: >>> x = Tensor(np.array([1, 2, 3, 4]), mindspore.int64) >>> mask = Tensor(np.array([1, 0, 1, 0]), mindspore.bool_) >>> output = ops.MaskedSelect()(x, mask) >>> print(output) [1 3] """ @prim_attr_register def __init__(self): self.init_prim_io_names(inputs=['x', 'mask'], outputs=['output']) def check_shape(self, x_shape, mask_shape): get_broadcast_shape(x_shape, mask_shape, self.name, arg_name1="x", arg_name2="mask") def check_dtype(self, x_dtype, mask_dtype): validator.check_tensor_dtype_valid('mask', mask_dtype, [mstype.bool_], self.name) validator.check_tensor_dtype_valid('x', x_dtype, mstype.number_type, self.name) class SearchSorted(PrimitiveWithInfer): """ Find the indices from the innermost dimension of `sequence` such that the order of the innermost dimension within `sequence` would be preserved when the corresponding values in `values` were inserted before the indices. Args: out_int32 (bool): Output datatype. Optional. If True, the output datatype will be int32; if False, the output datatype will be int64. Default is False. right (bool): Search Strategy. Optional. If True, return the last suitable index found. If False, return the first such index. Default is False. Inputs: - **sequence** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R-1, x_R)` or `(x_1)`. It must contain monitonically increasing sequence on the innermost dimension. - **values** (Tensor) - The shape of tensor is : math:`(x_1, x_2, ..., x_R-1, x_S)`. Outputs: Tensor containing the indices from the innermost dimension of the input sequence such that, if insert the corresponding value in the values tensor, the order of the tensor sequence would be preserved. The shape of tensor is :math:`(x_1, x_2, ..., x_R-1, x_S)`, whose datatype is int32 if out_int32 is True, otherwise int64, and shape is the same as the shape of values. Raises: ValueError: If `sequence` and `values` do not have proper shapes. Supported Platforms: ``CPU`` Examples: >>> sequence = Tensor(np.array([[0, 1, 3, 5, 7], [2, 4, 6, 8, 10]]), mindspore.float32) >>> values = Tensor(np.array([[3, 6, 9], [3, 6, 9]]), mindspore.float32) >>> output = ops.SearchSorted()(sequence, values) >>> print(output) [[2 4 5] [1 2 4]] """ @prim_attr_register def __init__(self, out_int32=False, right=False): """Initialize SearchSorted""" self.out_int32 = validator.check_value_type("out_int32", out_int32, [bool], self.name) self.right = validator.check_value_type("right", right, [bool], self.name) self.init_prim_io_names(inputs=['sequence', 'values'], outputs=['positions']) def infer_shape(self, sequence_shape, values_shape): if len(sequence_shape) != 1 and sequence_shape[:-1] != values_shape[:-1]: raise ValueError(f"For '{self.name}', the 'sequence' should be 1 dimensional or " f"all dimensions except the last dimension of 'sequence' " f"must be the same as all dimensions except the last dimension of 'values'. " f"but got shape of 'sequence': {sequence_shape} " f"and shape of 'values': {values_shape}.") return values_shape def infer_dtype(self, sequence_dtype, values_dtype): args = {"sequence_dtype": sequence_dtype, "values_dtype": values_dtype} validator.check_tensors_dtypes_same_and_valid(args, mstype.number_type, self.name) return mstype.tensor_type(mstype.int32) if self.out_int32 else mstype.tensor_type(mstype.int64) class TensorScatterMax(PrimitiveWithInfer): """ By comparing the value at the position indicated by the index in input_x with the value in the update, the value at the index will eventually be equal to the largest one to create a new tensor. The last axis of the index is the depth of each index vector. For each index vector, there must be a corresponding value in `updates`. The shape of `updates` should be equal to the shape of input_x[indices]. For more details, see use cases. Note: If some values of the `indices` are out of bound, instead of raising an index error, the corresponding `updates` will not be updated to `input_x`. Inputs: - **input_x** (Tensor) - The target tensor. The dimension of input_x must be no less than indices.shape[-1]. - **indices** (Tensor) - The index of input tensor whose data type is int32 or int64. The rank must be at least 2. - **updates** (Tensor) - The tensor to update the input tensor, has the same type as input, and updates.shape should be equal to indices.shape[:-1] + input_x.shape[indices.shape[-1]:]. Outputs: Tensor, has the same shape and type as `input_x`. Raises: TypeError: If dtype of `indices` is neither int32 nor int64. ValueError: If length of shape of `input_x` is less than the last dimension of shape of `indices`. Supported Platforms: ``GPU`` Examples: >>> input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32) >>> indices = Tensor(np.array([[0, 0], [0, 0]]), mindspore.int32) >>> updates = Tensor(np.array([1.0, 2.2]), mindspore.float32) >>> # Next, demonstrate the approximate operation process of this operator: >>> # 1, indices[0] = [0, 0], indices[1] = [0, 0] >>> # 2, And input_x[0, 0] = -0.1 >>> # 3, So input_x[indices] = [-0.1, -0.1] >>> # 4, Satisfy the above formula: input_x[indices].shape=(2) == updates.shape=(2) >>> op = ops.TensorScatterMax() >>> # 5, Perform the max operation for the first time: >>> # first_input_x = Max(input_x[0][0], updates[0]) = [[2.2, 0.3, 3.6], [0.4, 0.5, -3.2]] >>> # 6, Perform the max operation for the second time: >>> # second_input_x = Max(input_x[0][0], updates[0]) = [[2.2, 0.3, 3.6], [0.4, 0.5, -3.2]] >>> output = op(input_x, indices, updates) >>> print(output) [[ 2.2 0.3 3.6] [ 0.4 0.5 -3.2]] """ @prim_attr_register def __init__(self): self.init_prim_io_names(inputs=['input_x', 'indices', 'updates'], outputs=['y']) def infer_shape(self, input_x_shape, indices_shape, updates_shape): if len(indices_shape) < 2: raise ValueError(f"For '{self.name}', the dimension of 'indices' cannot be less than 2," f" but got {len(indices_shape)}.") if indices_shape[-1] > len(input_x_shape): raise ValueError(f"For '{self.name}', the last dimension of 'indices' must be less than or equal to " f"the dimension of 'input_x', but got the " f"last dimension of 'indices': {indices_shape[-1]} and the dimension of 'input_x': " f"{len(input_x_shape)}.") updates_shape_check = indices_shape[:-1] + input_x_shape[indices_shape[-1]:] if updates_shape_check != updates_shape: raise ValueError(f"For '{self.name}', the shape of 'update' must be equal to updates_shape_check, " f"where updates_shape_check = indices_shape[:-1] + input_x_shape[indices_shape[-1]:] " f"but got the shape of 'update': {updates_shape}, " f"updates_shape_check: {updates_shape_check}, indices_shape: {indices_shape} and " f"input_x_shape: {input_x_shape}. Please check input_x_shape and indices_shape.") return input_x_shape def infer_dtype(self, input_x_dtype, indices_dtype, updates_dtype): validator.check_tensor_dtype_valid('indices', indices_dtype, [mstype.int32, mstype.int64], self.name) args = {"input_x": input_x_dtype, "updates": updates_dtype} valid_input_types = (mstype.float16, mstype.float32, mstype.int8, mstype.uint8, mstype.int32) validator.check_tensors_dtypes_same_and_valid(args, valid_input_types, self.name) return input_x_dtype class TensorScatterMin(PrimitiveWithInfer): """ By comparing the value at the position indicated by the index in input_x with the value in the `updates`, the value at the index will eventually be equal to the smallest one to create a new tensor. The last axis of the index is the depth of each index vector. For each index vector, there must be a corresponding value in `updates`. The shape of `updates` should be equal to the shape of input_x[indices]. For more details, see use cases. Note: If some values of the `indices` are out of bound, instead of raising an index error, the corresponding `updates` will not be updated to `input_x`. Inputs: - **input_x** (Tensor) - The target tensor. The dimension of input_x must be no less than indices.shape[-1]. - **indices** (Tensor) - The index of input tensor whose data type is int32 or int64. The rank must be at least 2. - **updates** (Tensor) - The tensor to update the input tensor, has the same type as input, and updates.shape should be equal to indices.shape[:-1] + input_x.shape[indices.shape[-1]:]. Outputs: Tensor, has the same shape and type as `input_x`. Raises: TypeError: If dtype of `indices` is neither int32 nor int64. ValueError: If length of shape of `input_x` is less than the last dimension of shape of `indices`. Supported Platforms: ``GPU`` Examples: >>> input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32) >>> indices = Tensor(np.array([[0, 0], [0, 0]]), mindspore.int32) >>> updates = Tensor(np.array([1.0, 2.2]), mindspore.float32) >>> # Next, demonstrate the approximate operation process of this operator: >>> # 1, indices[0] = [0, 0], indices[1] = [0, 0] >>> # 2, And input_x[0, 0] = -0.1 >>> # 3, So input_x[indices] = [-0.1, -0.1] >>> # 4, Satisfy the above formula: input_x[indices].shape=(2) == updates.shape=(2) >>> op = ops.TensorScatterMin() >>> # 5, Perform the min operation for the first time: >>> # first_input_x = Min(input_x[0][0], updates[0]) = [[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]] >>> # 6, Perform the min operation for the second time: >>> # second_input_x = Min(input_x[0][0], updates[1]) = [[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]] >>> output = op(input_x, indices, updates) >>> print(output) [[ -0.1 0.3 3.6] [ 0.4 0.5 -3.2]] """ @prim_attr_register def __init__(self): self.init_prim_io_names(inputs=['input_x', 'indices', 'updates'], outputs=['y']) def infer_shape(self, input_x_shape, indices_shape, updates_shape): if len(indices_shape) < 2: raise ValueError(f"For '{self.name}', the dimension of 'indices' cannot be less than 2," f" but got {len(indices_shape)}.") if indices_shape[-1] > len(input_x_shape): raise ValueError(f"For '{self.name}', the last dimension of 'indices' must be less than or equal to " f"the dimension of 'input_x', but got the " f"last dimension of 'indices': {indices_shape[-1]} and the dimension of 'input_x': " f"{len(input_x_shape)}.") updates_shape_check = indices_shape[:-1] + input_x_shape[indices_shape[-1]:] if updates_shape_check != updates_shape: raise ValueError(f"For '{self.name}', the shape of 'update' must be equal to updates_shape_check, " f"where updates_shape_check = indices_shape[:-1] + input_x_shape[indices_shape[-1]:] " f"but got the shape of 'update': {updates_shape}, " f"updates_shape_check: {updates_shape_check}, indices_shape: {indices_shape} and " f"input_x_shape: {input_x_shape}. Please check input_x_shape and indices_shape.") return input_x_shape def infer_dtype(self, input_x_dtype, indices_dtype, updates_dtype): validator.check_tensor_dtype_valid('indices', indices_dtype, [mstype.int32, mstype.int64], self.name) args = {"input_x": input_x_dtype, "updates": updates_dtype} valid_input_types = (mstype.float16, mstype.float32, mstype.int8, mstype.uint8, mstype.int32) validator.check_tensors_dtypes_same_and_valid(args, valid_input_types, self.name) return input_x_dtype class TensorScatterSub(PrimitiveWithInfer): """ Creates a new tensor by subtracting the values from the positions in `input_x` indicated by `indices`, with values from `updates`. When multiple values are provided for the same index, the result of the update will be to subtract these values respectively. This operation is almost equivalent to using ScatterNdSub, except that the updates are applied on `Tensor` instead of `Parameter`. The last axis of `indices` is the depth of each index vectors. For each index vector, there must be a corresponding value in `updates`. The shape of `updates` should be equal to the shape of `input_x[indices]`. For more details, see use cases. Note: If some values of the `indices` are out of bound, instead of raising an index error, the corresponding `updates` will not be updated to `input_x`. Inputs: - **input_x** (Tensor) - The target tensor. The dimension of input_x must be no less than indices.shape[-1]. - **indices** (Tensor) - The index of input tensor whose data type is int32 or int64. The rank must be at least 2. - **updates** (Tensor) - The tensor to update the input tensor, has the same type as input, and updates.shape should be equal to indices.shape[:-1] + input_x.shape[indices.shape[-1]:]. Outputs: Tensor, has the same shape and type as `input_x`. Raises: TypeError: If dtype of `indices` is neither int32 nor int64. ValueError: If length of shape of `input_x` is less than the last dimension of shape of `indices`. Supported Platforms: ``GPU`` Examples: >>> input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32) >>> indices = Tensor(np.array([[0, 0], [0, 0]]), mindspore.int32) >>> updates = Tensor(np.array([1.0, 2.2]), mindspore.float32) >>> # Next, demonstrate the approximate operation process of this operator: >>> # 1, indices[0] = [0, 0], indices[1] = [0, 0] >>> # 2, And input_x[0, 0] = -0.1 >>> # 3, So input_x[indices] = [-0.1, -0.1] >>> # 4, Satisfy the above formula: input_x[indices].shape=(2) == updates.shape=(2) >>> op = ops.TensorScatterSub() >>> # 5, Perform the subtract operation for the first time: >>> # first_input_x = input_x[0][0] - updates[0] = [[-1.1, 0.3, 3.6], [0.4, 0.5, -3.2]] >>> # 6, Perform the subtract operation for the second time: >>> # second_input_x = input_x[0][0] - updates[1] = [[-3.3, 0.3, 3.6], [0.4, 0.5, -3.2]] >>> output = op(input_x, indices, updates) >>> print(output) [[-3.3000002 0.3 3.6 ] [ 0.4 0.5 -3.2 ]] """ @prim_attr_register def __init__(self): self.init_prim_io_names(inputs=['input_x', 'indices', 'updates'], outputs=['y']) def infer_shape(self, input_x_shape, indices_shape, updates_shape): if len(indices_shape) < 2: raise ValueError(f"For '{self.name}', the dimension of 'indices' cannot be less than 2," f" but got {len(indices_shape)}.") if indices_shape[-1] > len(input_x_shape): raise ValueError(f"For '{self.name}', the last dimension of 'indices' must be less than or equal to " f"the dimension of 'input_x', but got the " f"last dimension of 'indices': {indices_shape[-1]} and the dimension of 'input_x': " f"{len(input_x_shape)}.") updates_shape_check = indices_shape[:-1] + input_x_shape[indices_shape[-1]:] if updates_shape_check != updates_shape: raise ValueError(f"For '{self.name}', the shape of 'update' must be equal to updates_shape_check, " f"where updates_shape_check = indices_shape[:-1] + input_x_shape[indices_shape[-1]:] " f"but got the shape of 'update': {updates_shape}, " f"updates_shape_check: {updates_shape_check}, indices_shape: {indices_shape} and " f"input_x_shape: {input_x_shape}. Please check input_x_shape and indices_shape.") return input_x_shape def infer_dtype(self, input_x_dtype, indices_dtype, updates_dtype): validator.check_tensor_dtype_valid('indices', indices_dtype, [mstype.int32, mstype.int64], self.name) args = {"input_x": input_x_dtype, "updates": updates_dtype} valid_input_types = (mstype.float16, mstype.float32, mstype.int8, mstype.uint8, mstype.int32) validator.check_tensors_dtypes_same_and_valid(args, valid_input_types, self.name) return input_x_dtype class SplitV(Primitive): r""" Splits the input tensor into num_split tensors along the given dimension. The `input_x` tensor will be split into sub-tensors with individual shapes given by `size_splits` along the split dimension. This requires that `input_x.shape(split_dim)` is equal to the sum of `size_splits`. The shape of `input_x` is :math:`(x_1, x_2, ..., x_M, ..., x_R)`. The rank of `input_x` is `R`. Set the given `split_dim` as M, and :math:`-R \le M < R`. Set the given `num_split` as `N`, the given `size_splits` as :math:`(x_{m_1}, x_{m_2}, ..., x_{m_N})`, :math:`x_M=\sum_{i=1}^Nx_{m_i}`. The output is a list of tensor objects, for the :math:`i`-th tensor, it has the shape of :math:`(x_1, x_2, ..., x_{m_i}, ..., x_R)`. :math:`x_{m_i}` is the :math:`M`-th dimension of the :math:`i`-th tensor. Then, the shape of the output tensor is .. math:: ((x_1, x_2, ..., x_{m_1}, ..., x_R), (x_1, x_2, ..., x_{m_2}, ..., x_R), ..., (x_1, x_2, ..., x_{m_N}, ..., x_R)) Args: size_splits (Union[tuple, list]): The list containing the sizes of each output tensor along the split dimension. Must sum to the dimension of value along `split_dim`. Can contain one -1 indicating that dimension is to be inferred. split_dim (int): The dimension along which to split. Must be in the range [-len(input_x.shape), len(input_x.shape)). num_split (int): The number of output tensors. Must be positive int. Inputs: - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ...,x_M ..., x_R)`. Outputs: Tensor, a list of `num_split` Tensor objects with the shape :math:`((x_1, x_2, ..., x_{m_1}, ..., x_R), (x_1, x_2, ..., x_{m_2}, ..., x_R), ..., (x_1, x_2, ..., x_{m_N}, ..., x_R))`, :math:`x_M=\sum_{i=1}^Nx_{m_i}`. The data type is the same with `input_x`. Raises: TypeError: If `input_x` is not a Tensor. TypeError: If `size_splits` is not a tuple or a list. TypeError: If element of `size_splits` is not an int. TypeError: If `split_dim` or `num_split` is not an int. ValueError: If rank of the `size_splits` is not equal to `num_split`. ValueError: If sum of the `size_splits` is not equal to the dimension of value along `split_dim`. ValueError: If `split_dim` is out of the range [-len(input_x.shape), len(input_x.shape)). ValueError: If the `num_split` is less than or equal to 0. Supported Platforms: ``Ascend`` Examples: >>> input_x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), mindspore.int32) >>> op = ops.SplitV(size_splits=[1, -1], split_dim=1, num_split=2) >>> output = op(input_x) >>> print(output) (Tensor(shape=[3, 1], dtype=Int32, value= [[1], [4], [7]]), Tensor(shape=[3, 2], dtype=Int32, value= [[2, 3], [5, 6], [8, 9]])) >>> input_x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), mindspore.int32) >>> op = ops.SplitV(size_splits=[2, 1], split_dim=0, num_split=2) >>> output = op(input_x) >>> print(output) (Tensor(shape=[2, 3], dtype=Int32, value= [[1, 2, 3], [4, 5, 6]]), Tensor(shape=[1, 3], dtype=Int32, value= [[7, 8, 9]])) """ @prim_attr_register def __init__(self, size_splits, split_dim, num_split): """Initialize SplitV""" validator.check_value_type("size_splits", size_splits, [tuple, list], self.name) for elements_of_size_splits in size_splits: validator.check_value_type("elements of size_splits", elements_of_size_splits, [int], self.name) if elements_of_size_splits != -1 and elements_of_size_splits < 1: raise ValueError(f"For \'{self.name}\', all elements of size_splits must be positive (except at most " f"one default value -1), but got: {elements_of_size_splits}.") validator.check_value_type("split_dim", split_dim, [int], self.name) validator.check_value_type("num_split", num_split, [int], self.name) validator.check_positive_int(num_split, "num_split", self.name) self.init_prim_io_names(inputs=['input_x'], outputs=['output']) class ScatterElements(Primitive): """ ScatterElements takes three inputs data, updates, and indices of the same rank r >= 1 and an optional attribute axis that identifies an axis of data (default is 0). The output of the operation is produced by creating a copy of the input data, and then updating its value to values specified by updates at specific index positions specified by indices. Args: axis (int): which axis to scatter, default is 0. Inputs: - **data** (Tensor) - The target tensor. c - **indices** (Tensor) - The index of input tensor whose data type is int32 or int64. - **update** (Tensor) - The tensor to update the input tensor, has the same type as input, and update.shape should be equal to indices.shape. Outputs: Tensor, has the same shape and type as `data`. Raises: TypeError: If dtype of `indices` is neither int32 nor int64. Supported Platforms: ``Ascend`` Examples: >>> op = ops.ScatterElements(0) >>> data = Tensor(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), mindspore.float32) >>> indices = Tensor(np.array([[1, 0, 2], [0, 2, 1]]), mindspore.int32) >>> updates = Tensor(np.array([[0, 0, 0], [0, 0, 0]]), mindspore.float32) >>> output = op(data, indices, updates) >>> print(output) [[ 0.0 0.0 3.0] [ 0.0 5.0 0.0] [ 7.0 0.0 0.0]] >>> op = ops.ScatterElements(1) >>> data = Tensor(np.array([[1, 2, 3, 4, 5]), mindspore.int32) >>> indices = Tensor(np.array([[2, 4]), mindspore.int32) >>> updates = Tensor(np.array([[8, 8]]), mindspore.int32) >>> output = op(data, indices, updates) >>> print(output) [[ 1 2 8 4 8]] """ @prim_attr_register def __init__(self, axis=0): """Initialize ScatterElements""" validator.check_value_type("axis", axis, [int], self.name) self.init_prim_io_names(inputs=['data', 'indices', 'updates'], outputs=['y']) class ExtractVolumePatches(Primitive): """ Extract patches from input and put them in the "depth" output dimension. 3D extension of extract_image_patches. Args: kernel_size (Union[int, tuple[int], list[int]]): A list of ints which's length is 3 or 5. The size of the sliding window for each dimension of input. Must be: [1, 1, k_d, k_h, k_w] or [k_d, k_h, k_w]. If k_d = k_h = k_w, you can enter an integer. strides (Union[int, tuple[int], list[int]]): A list of ints which's length is 3 or 5. How far the centers of two consecutive patches are in input. Must be: [1, 1, s_d, s_h, s_w] or [s_d, s_h, s_w]. If s_d = s_h = s_w, you can enter an integer. padding (str): A string from: "SAME", "VALID". The type of padding algorithm to use. Inputs: - **input_x** (Tensor) - A Tensor. Must be one of the following types: float16, float32. 5-D Tensor with shape :math:`(x_n, x_c, x_d, x_h, x_w)`. Outputs: Tensor, has the same type as input. If padding is VALID, the shape is :math:`(x_n, k_d * k_h * k_w * x_c, 1 + (x_d - k_d) / s_d, 1 + (x_h - k_h) / s_h, 1 + (x_w - k_w) / s_w)`; if padding is SAME, the shape is :math:`( x_n, k_d * k_h * k_w * x_c, (x_d + s_d - 1) / s_d, (x_h + s_h - 1) / s_h, (x_w + s_w - 1) / s_w)`. Raises: TypeError: If dtype of input_x is neither float16 nor float32. TypeError: If kernel_size or strides is not a list, a tuple or an int. TypeError: If input_x is not a tensor. TypeError: If padding is not str. ValueError: If the length of kernel_size is neither 3 nor 5 and kernel_size is not an integer. ValueError: If the length of strides is neither 3 nor 5 and strides is not an integer. ValueError: If padding is neither "VALID" nor "SAME". ValueError: If elements of kernel_size or strides are not positive integer. ValueError: If input_x is not a tensor in dimension 5. ValueError: If input_x's shape has zero. ValueError: If one of kernel_size or strides' first two numbers is not 1. ValueError: If padding = "VALID" and input - kernel_size is less than 0 in d, h or w dimension. ValueError: If padding = "SAME" and :math:`padding_needed = ((input_x + strides - 1) / strides - 1) * strides + kernel_size - input` is less than 0 in d, h or w dimension. ValueError: If x_h is not 1 or x_w is not 1 and x_w + padding_needed - k_w - s_w is less than 0. ValueError: If x_d * x_h * x_w is greater than 2048. Supported Platforms: ``Ascend`` Example: >>> kernel_size = (1, 1, 2, 2, 2) >>> strides = (1, 1, 1, 1, 1) >>> padding = "VALID" >>> input_x = P.Reshape()(Tensor(np.arange(1, 28), mstype.float16), (1, 1, 3, 3, 3)) >>> output_y = P.ExtractVolumePatches(kernel_size, strides, padding)(input_x) >>> print(output_y.shape) (1, 8, 2, 2, 2) """ @prim_attr_register def __init__(self, kernel_size, strides, padding): validator.check_value_type("kernel_size", kernel_size, (int, list, tuple), self.name) validator.check_value_type("strides", strides, (int, list, tuple), self.name) if isinstance(kernel_size, (list, tuple)): kernel_size = tuple(kernel_size) if len(kernel_size) == 5: validator.check_int(kernel_size[0], 1, Rel.EQ, "kernel_size[0]", self.name) validator.check_int(kernel_size[1], 1, Rel.EQ, "kernel_size[1]", self.name) if isinstance(strides, (list, tuple)): strides = tuple(strides) if len(strides) == 5: validator.check_int(strides[0], 1, Rel.EQ, "strides[0]", self.name) validator.check_int(strides[1], 1, Rel.EQ, "strides[1]", self.name) self.kernel_size = _check_3d_int_or_tuple("kernel_size", kernel_size, self.name, allow_five=True, ret_five=True, greater_zero=True) self.strides = _check_3d_int_or_tuple("strides", strides, self.name, allow_five=True, ret_five=True, greater_zero=True) self.add_prim_attr("kernel_size", self.kernel_size) self.add_prim_attr("strides", self.strides) validator.check_value_type("padding_dtype", padding, (str), self.name) self.padding = validator.check_string(padding.upper(), ['VALID', 'SAME'], 'padding', self.name) self.add_prim_attr("padding", self.padding)
# coding: utf-8 # Copyright 2020-2021 Huawei Technologies Co., Ltd # # 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. # ============================================================================ """Operators for array.""" import copy import functools import itertools import numbers from collections import Counter import numpy as np from mindspore import log as logger from mindspore.common.initializer import Zero from .. import signature as sig from .._utils import get_broadcast_shape, is_shape_unknown from .._utils import get_concat_offset from ..operations.math_ops import _infer_shape_reduce from ..primitive import Primitive, PrimitiveWithInfer, PrimitiveWithCheck, prim_attr_register, _run_op from ..._checkparam import Rel from ..._checkparam import Validator as validator from ..._checkparam import _check_3d_int_or_tuple from ...common import dtype as mstype from ...common._decorator import deprecated from ...common.parameter import Parameter from ...common.tensor import Tensor from ..._c_expression import Tensor as Tensor_ class _ScatterOp(PrimitiveWithInfer): """ Defines Scatter operators """ __mindspore_signature__ = ( sig.make_sig('x', sig.sig_rw.RW_WRITE, dtype=sig.sig_dtype.T), sig.make_sig('indices', dtype=sig.sig_dtype.T1), sig.make_sig('updates', dtype=sig.sig_dtype.T) ) def _check_scatter_shape(self, x_shape, indices_shape, updates_shape, prim_name): if indices_shape != [-1] and updates_shape and updates_shape != indices_shape + x_shape[1:]: raise ValueError(f"For '{prim_name}', " f"updates_shape = indices_shape + x_shape[1:], but got x_shape: {x_shape}, " f"indices_shape: {indices_shape}, updates_shape: {updates_shape}.") @prim_attr_register def __init__(self, use_locking=False): """Initialize _ScatterOp""" validator.check_value_type('use_locking', use_locking, [bool], self.name) self.init_prim_io_names(inputs=['x', 'indices', 'updates'], outputs=['y']) self.add_prim_attr('side_effect_mem', True) def infer_shape(self, x_shape, indices_shape, updates_shape): self._check_scatter_shape(x_shape, indices_shape, updates_shape, self.name) return x_shape def infer_dtype(self, x_dtype, indices_dtype, updates_dtype): validator.check_tensor_dtype_valid('indices', indices_dtype, [mstype.int32], self.name) args = {"x": x_dtype, "updates": updates_dtype} validator.check_tensors_dtypes_same_and_valid(args, mstype.number_type, self.name) return x_dtype class _ScatterOpDynamic(PrimitiveWithCheck): """ Defines Scatter operators with dynamic shape """ __mindspore_signature__ = ( sig.make_sig('x', sig.sig_rw.RW_WRITE, dtype=sig.sig_dtype.T), sig.make_sig('indices', dtype=sig.sig_dtype.T1), sig.make_sig('updates', dtype=sig.sig_dtype.T) ) def _check_scatter_shape(self, x_shape, indices_shape, updates_shape, prim_name): # x_shape cannot be dynamic if np.any(np.array(x_shape) == -1): raise ValueError(f"For '{prim_name}', the 'input_x' does not support dynamic shape, " f"but got the shape of 'input_x' is {x_shape}.") # support indices and updates dynamic if np.any(np.array(indices_shape) == -1) or np.any(np.array(updates_shape) == -1): pass elif indices_shape != [-1] and updates_shape and updates_shape != indices_shape + x_shape[1:]: raise ValueError(f"For '{prim_name}', " f"updates_shape = indices_shape + x_shape[1:], but got x_shape: {x_shape}, " f"indices_shape: {indices_shape}, updates_shape: {updates_shape}.") @prim_attr_register def __init__(self, use_locking=False): """Initialize _ScatterOpDynamic""" validator.check_value_type('use_locking', use_locking, [bool], self.name) self.init_prim_io_names(inputs=['x', 'indices', 'updates'], outputs=['y']) self.add_prim_attr('side_effect_mem', True) def check_shape(self, x_shape, indices_shape, updates_shape): self._check_scatter_shape(x_shape, indices_shape, updates_shape, self.name) def check_dtype(self, x_dtype, indices_dtype, updates_dtype): validator.check_tensor_dtype_valid('indices', indices_dtype, [mstype.int32], self.name) args = {"x": x_dtype, "updates": updates_dtype} validator.check_tensors_dtypes_same_and_valid(args, mstype.number_type, self.name) class _ScatterNdOp(_ScatterOp): """ Defines _ScatterNd operators """ def _check_scatter_shape(self, x_shape, indices_shape, updates_shape, prim_name): validator.check('the dimension of x', len(x_shape), 'the dimension of indices', indices_shape[-1], Rel.GE) if indices_shape[:-1] + x_shape[indices_shape[-1]:] != updates_shape: raise ValueError(f"For '{prim_name}', updates_shape = " f"indices_shape[:-1] + x_shape[indices_shape[-1]:], but got x_shape: {x_shape}, " f"indices_shape: {indices_shape}, updates_shape: {updates_shape}.") def _check_infer_attr_reduce(axis, keep_dims, prim_name): validator.check_value_type('keep_dims', keep_dims, [bool], prim_name) validator.check_value_type('axis', axis, [int, tuple], prim_name) if isinstance(axis, tuple): for index, value in enumerate(axis): validator.check_value_type('axis[%d]' % index, value, [int], prim_name) class ExpandDims(PrimitiveWithInfer): """ Adds an additional dimension to `input_x` at the given axis. Note: If the specified axis is a negative number, the index is counted backward from the end and starts at 1. Inputs: - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. - **axis** (int) - Specifies the dimension index at which to expand the shape of `input_x`. The value of axis must be in the range `[-input_x.ndim-1, input_x.ndim]`. Only constant value is allowed. Outputs: Tensor, the shape of tensor is :math:`(1, x_1, x_2, ..., x_R)` if the value of `axis` is 0. It has the same data type as `input_x`. Raises: ValueError: If `axis` is not an int or not in the valid range. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_tensor = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32) >>> expand_dims = ops.ExpandDims() >>> output = expand_dims(input_tensor, 0) >>> print(output) [[[2. 2.] [2. 2.]]] """ @prim_attr_register def __init__(self): """Initialize ExpandDims""" self.init_prim_io_names(inputs=['x', 'axis'], outputs=['output']) def __infer__(self, x, axis): validator.check_subclass("x", x['dtype'], mstype.tensor, self.name) x_shape = list(x['shape']) axis_v = axis['value'] rank = len(x_shape) validator.check_int_range(axis_v, -rank - 1, rank, Rel.INC_BOTH, 'axis', self.name) value = None if x['value'] is not None: value = x['value'].asnumpy() value = np.expand_dims(value, axis_v) value = Tensor(value) if axis_v < 0: axis_v = rank + 1 + axis_v x_shape.insert(axis_v, 1) out = {'shape': x_shape, 'dtype': x['dtype'], 'value': value} if 'min_shape' in x and 'max_shape' in x: out['min_shape'] = x['min_shape'] out['min_shape'].insert(axis_v, 1) out['max_shape'] = x['max_shape'] out['max_shape'].insert(axis_v, 1) return out class DType(Primitive): """ Returns the data type of the input tensor as mindspore.dtype. Inputs: - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. Outputs: mindspore.dtype, the data type of a tensor. Raises: TypeError: If `input_x` is not a Tensor. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_tensor = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32) >>> output = ops.DType()(input_tensor) >>> print(output) Float32 """ @prim_attr_register def __init__(self): """Initialize DType""" class SameTypeShape(PrimitiveWithInfer): """ Checks whether the data type and shape of two tensors are the same. Inputs: - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. - **input_y** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_S)`. Outputs: Tensor, the shape of tensor is :math:`(x_1, x_2, ..., x_R)`, if data type and shape of `input_x` and `input_y` are the same. Raises: TypeError: If the data types of `input_x` and `input_y` are not the same. ValueError: If the shapes of `input_x` and `input_y` are not the same. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32) >>> input_y = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32) >>> output = ops.SameTypeShape()(input_x, input_y) >>> print(output) [[2. 2.] [2. 2.]] """ @prim_attr_register def __init__(self): """Initialize Same""" def __call__(self, x, y): """run in PyNative mode""" validator.check_value_type('x', x, Tensor, self.name) validator.check_value_type('y', y, Tensor, self.name) validator.check('x dtype', x.dtype, 'y dtype', y.dtype, Rel.EQ, self.name, TypeError) validator.check('x shape', x.shape, 'y shape', y.shape, Rel.EQ, self.name) return x def __infer__(self, x, y): validator.check_subclass('x', x['dtype'], mstype.tensor, self.name) validator.check_subclass('y', y['dtype'], mstype.tensor, self.name) validator.check('x dtype', x['dtype'], 'y dtype', y['dtype'], Rel.EQ, self.name, TypeError) validator.check('x shape', x['shape'], 'y shape', y['shape'], Rel.EQ, self.name) return x class Cast(PrimitiveWithInfer): """ Returns a tensor with the new specified data type. Inputs: - **input_x** (Union[Tensor, Number]) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. The tensor to be cast. - **type** (dtype.Number) - The valid data type of the output tensor. Only constant value is allowed. Outputs: Tensor, the shape of tensor is the same as `input_x`, :math:`(x_1, x_2, ..., x_R)`. Raises: TypeError: If `input_x` is neither Tensor nor Number. TypeError: If `type` is not a Number. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_np = np.random.randn(2, 3, 4, 5).astype(np.float32) >>> input_x = Tensor(input_np) >>> type_dst = mindspore.int32 >>> cast = ops.Cast() >>> output = cast(input_x, type_dst) >>> print(output.dtype) Int32 >>> print(output.shape) (2, 3, 4, 5) """ @prim_attr_register def __init__(self): # if primitive need setattr in __infer__ need add this flag """Initialize Cast""" self.init_prim_io_names(inputs=['x', 'dst_type'], outputs=['output']) def check_elim(self, x, dtype): if isinstance(x, (Tensor, numbers.Number, Parameter)): if isinstance(x, Parameter): data = x.data if data.dtype == dtype: return (True, x) if isinstance(x, Tensor) and x.dtype == dtype: x = Tensor(x) x.set_cast_dtype() return (True, x) if isinstance(x, numbers.Number): return (True, Tensor(x, dtype=dtype)) return (False, None) def __infer__(self, x, t): src_type = x['dtype'] dst_type = t['value'] validator.check_subclass("input_x", src_type, [mstype.tensor, mstype.number], self.name) validator.check_subclass("type", dst_type, mstype.number, self.name) if isinstance(src_type, type(mstype.tensor)): src_type = x['dtype'].element_type() if isinstance(dst_type, type(mstype.tensor)): dst_type = dst_type.element_type() self.add_prim_attr('DstT', dst_type) self.add_prim_attr('SrcT', src_type) self.add_prim_attr('dst_type', dst_type) value = None if x['value'] is not None: np_dst_type = mstype.dtype_to_nptype(dst_type) if isinstance(x['value'], (int, float)): value = Tensor(np.array(x['value']).astype(np_dst_type)) else: value = Tensor(x['value'].asnumpy().astype(np_dst_type)) out = {'shape': x['shape'], 'dtype': mstype.tensor_type(t['value']), 'value': value} if 'min_shape' in x and 'max_shape' in x: out['min_shape'] = x['min_shape'] out['max_shape'] = x['max_shape'] return out class IsSubClass(PrimitiveWithInfer): """ Checks whether this type is a sub-class of another type. Inputs: - **sub_type** (mindspore.dtype) - The type to be checked. Only constant value is allowed. - **type_** (mindspore.dtype) - The target type. Only constant value is allowed. Outputs: bool, the check result. Raises: TypeError: If `sub_type` or `type_` is not a Type. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> output = ops.IsSubClass()(mindspore.int32, mindspore.intc) >>> print(output) True """ @prim_attr_register def __init__(self): pass def __infer__(self, sub_type, type_): sub_type_t = sub_type['value'] type_v = type_['value'] validator.check_value_type("sub_type", sub_type_t, [mstype.Type], self.name) validator.check_value_type("type_", type_v, [mstype.Type], self.name) value = mstype.issubclass_(sub_type_t, type_v) out = {'shape': (), 'dtype': mstype.type_type, 'value': value} return out class IsInstance(PrimitiveWithInfer): """ Checks whether an object is an instance of a target type. Inputs: - **inst** (Any Object) - The instance to be checked. Only constant value is allowed. - **type_** (mindspore.dtype) - The target type. Only constant value is allowed. Outputs: bool, the check result. Raises: TypeError: If `type_` is not a Type. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> inst = 1 >>> output = ops.IsInstance()(inst, mindspore.int32) >>> print(output) False """ @prim_attr_register def __init__(self): pass def __infer__(self, inst, type_): sub_type_t = inst['dtype'] type_v = type_['value'] validator.check_value_type("type_", type_v, [mstype.Type], self.name) if type_v == mstype.list_: value = isinstance(sub_type_t, list) elif type_v == mstype.tuple_: value = isinstance(sub_type_t, tuple) else: value = mstype.issubclass_(sub_type_t, type_v) out = {'shape': (), 'dtype': mstype.type_type, 'value': value} return out class Reshape(PrimitiveWithInfer): """ Reshapes the input tensor with the same values based on a given shape tuple. The 'input_shape' can only have one -1 at most, in which case it’s inferred from the remaining dimensions and the number of elements in the input. Inputs: - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. - **input_shape** (tuple[int]) - The input tuple is constructed by multiple integers, i.e., :math:`(y_1, y_2, ..., y_S)`. Only constant value is allowed. Outputs: Tensor, the shape of tensor is :math:`(y_1, y_2, ..., y_S)`. Raises: ValueError: Given a shape tuple, if it has several -1; or if the product of its elements is less than or equal to 0 or cannot be divided by the product of the input tensor shape; or if it does not match the input's array size. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32) >>> reshape = ops.Reshape() >>> output = reshape(input_x, (3, 2)) >>> print(output) [[-0.1 0.3] [ 3.6 0.4] [ 0.5 -3.2]] """ @prim_attr_register def __init__(self): """Initialize Reshape""" self.init_prim_io_names(inputs=['tensor', 'shape'], outputs=['output']) def _get_shape_and_range(self, x, shape): """ get min and max shape when output shape is dynamic""" min_shape = None max_shape = None x_shp = x['shape'] if is_shape_unknown(shape['shape']): out_shape = [-2] return out_shape, min_shape, max_shape shape_rank = shape['shape'][0] if not x_shp: # x is a scalar, output shape fixed out_shape = [1] * shape_rank return out_shape, min_shape, max_shape out_shape = [-1] * shape_rank if "max_value" in shape and "min_value" in shape: min_shape = shape["min_value"] max_shape = shape["max_value"] if len(min_shape) != shape_rank or len(max_shape) != shape_rank: raise RuntimeError("The primitive[Reshape]'s input[shape] min or max value not math the shape rank.") for i in range(shape_rank): if min_shape[i] == max_shape[i]: out_shape[i] = min_shape[i] elif is_shape_unknown(x_shp) and "max_shape" in x: # when dynamic memory allocation is supported, max_shape can be left out min_shape = [1] * shape_rank max_shape = [int(np.prod(x["max_shape"]))] * shape_rank return out_shape, min_shape, max_shape def __infer__(self, x, shape): shape_v = shape['value'] x_shp = x['shape'] validator.check_subclass("x", x['dtype'], mstype.tensor, self.name) # for shape is not constant if shape_v is None: out_shape, min_shape, max_shape = self._get_shape_and_range(x, shape) if is_shape_unknown(out_shape): # `min_shape` and `max_shape` can't be None before dynamic memory allocation is supported shape_shp = shape['shape'] shape_rank = 1 if is_shape_unknown(shape_shp) else shape_shp[0] min_shape = [1] * shape_rank if min_shape is None else min_shape max_shape = [1] * shape_rank if max_shape is None else max_shape return { 'shape': out_shape, 'dtype': x['dtype'], 'value': None, 'max_shape': max_shape, 'min_shape': min_shape } if isinstance(shape_v, Tensor_): validator.check_tensor_dtype_valid("shape", shape['dtype'], [mstype.int64], self.name) shape_v = shape_v.asnumpy().tolist() else: validator.check_value_type("shape", shape_v, [tuple], self.name) shape_v = list(shape_v) neg_index = -1 dim_prod = 1 for i, shp_i in enumerate(shape_v): validator.check_value_type("shape[%d]" % i, shp_i, [int], self.name) if shp_i == -1: if neg_index != -1: raise ValueError(f"For '{self.name}', there can be at most one '-1' in 'input_shape', " f"but got {shape_v}.") neg_index = i else: dim_prod *= shp_i if is_shape_unknown(x_shp): if 'max_shape' in x: x_max_shape = x['max_shape'] else: x_max_shape = x['shape'] if 'min_shape' in x: x_min_shape = x['min_shape'] else: x_min_shape = x['shape'] max_arr_prod = np.prod(x_max_shape) min_arr_prod = np.prod(x_min_shape) max_shape = list(shape_v) min_shape = list(shape_v) if neg_index != -1: max_shape[neg_index] = int(max_arr_prod / dim_prod) min_shape[neg_index] = int(min_arr_prod / dim_prod) out = {'shape': shape_v, 'dtype': x['dtype'], 'value': None, 'max_shape': tuple(max_shape), 'min_shape': tuple(min_shape)} else: arr_prod = np.prod(x_shp) if dim_prod <= 0: raise ValueError(f"For '{self.name}', the shape of 'input_x' is {x_shp}, " f"the value of 'input_shape' is {shape_v}. " f"The product of 'input_shape' should > 0, but got {dim_prod}.") if neg_index != -1: shape_v[neg_index] = int(arr_prod / dim_prod) dim_prod *= shape_v[neg_index] if dim_prod != arr_prod: raise ValueError(f"For '{self.name}', the shape of 'input_x' is {x_shp}, " f"the value of 'input_shape' value is {shape_v}. " f"The product of the shape of 'input_x' should be equal to product of 'input_shape', " f"but product of the shape of 'input_x' is {arr_prod}, " f"product of 'input_shape' is {dim_prod}.") value = None if x['value'] is not None: value = Tensor(x['value'].asnumpy().reshape(shape_v)) out = {'shape': tuple(shape_v), 'dtype': x['dtype'], 'value': value} return out class Shape(Primitive): """ Returns the shape of the input tensor. And it used to be static shape. static shape: A shape that can be obtained without running the graph. It is an inherent property of tensor and may be unknown. The static shape information can be completed by artificial setting. No matter what the input of the graph is, the static shape is not affected. Inputs: - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. Outputs: tuple[int], the output tuple is constructed by multiple integers, :math:`(x_1, x_2, ..., x_R)`. Raises: TypeError: If `input_x` is not a Tensor. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Tensor(np.ones(shape=[3, 2, 1]), mindspore.float32) >>> shape = ops.Shape() >>> output = shape(input_x) >>> print(output) (3, 2, 1) """ @prim_attr_register def __init__(self): """Initialize Shape""" class DynamicShape(Primitive): """ Returns the shape of the input tensor. And it used to be dynamic shape. Note: Dynamic shape: After the graph is running, as the tensor flows in the graph, the specific shape of the tensor on each node on the graph can be inferred according to the structure of the graph. This shape is called a dynamic shape. As the input shape of the graph is different, the dynamic shape of the tensor in the graph will change. Inputs: - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. Outputs: Tensor[int], 1-dim Tensor of type int32 Raises: TypeError: If `input_x` is not a Tensor. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Tensor(np.ones(shape=[3, 2, 1]), mindspore.float32) >>> shape = ops.DynamicShape() >>> output = shape(input_x) >>> print(output) [3 2 1] """ @prim_attr_register def __init__(self): """init Shape""" self.init_prim_io_names(inputs=['tensor'], outputs=['output']) self.add_prim_attr('is_dynamic_shape', True) class Squeeze(PrimitiveWithInfer): """ Returns a tensor with the same data type but dimensions of 1 are removed based on `axis`. If `axis` is specified, it will remove the dimensions of size 1 in the given `axis`. It `axis` is None, it will remove all the dimensions of size 1. For example, if input is of shape: (A×1×B×C×1×D), then the out tensor will be of shape: (A×B×C×D); When dim is given, a squeeze operation is done only in the given dimension. If input is of shape: (A×1×B), squeeze(input, 0) leaves the tensor unchanged, but squeeze(input, 1) will squeeze the tensor to the shape (A×B). Please note that in dynamic graph mode, the output Tensor will share data with the input Tensor, and there is no Tensor data copy process. Note: The dimension index starts at 0 and must be in the range `[-input.ndim, input.ndim]`. Args: axis (Union[int, tuple(int)]): Specifies the dimension indexes of shape to be removed, which will remove all the dimensions that are equal to 1. If specified, it must be int32 or int64. Default: (), an empty tuple. Inputs: - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. Outputs: Tensor, the shape of tensor is :math:`(x_1, x_2, ..., x_S)`. Raises: TypeError: If `axis` is neither an int nor tuple. TypeError: If `axis` is a tuple whose elements are not all int. ValueError: If the corresponding dimension of the specified axis isn't equal to 1. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Tensor(np.ones(shape=[3, 2, 1]), mindspore.float32) >>> squeeze = ops.Squeeze(2) >>> output = squeeze(input_x) >>> print(output) [[1. 1.] [1. 1.] [1. 1.]] """ @prim_attr_register def __init__(self, axis=()): """Initialize Squeeze""" self.init_prim_io_names(inputs=['x'], outputs=['output']) validator.check_value_type('axis', axis, [int, tuple], self.name) if isinstance(axis, tuple): for idx, item in enumerate(axis): validator.check_value_type("axis[%d]" % idx, item, [int], self.name) else: self.axis = (axis,) self.add_prim_attr("axis", (axis,)) class Transpose(Primitive): """ Permutes the dimensions of the input tensor according to input permutation. For a 1-D array this has no effect, as a transposed vector is simply the same vector. To convert a 1-D array into a 2D column vecto please refer the class: mindspore.ops.ExpandDims. For a 2-D array, this is a standard matrix transpose. For an n-D array, if axes are given, their order indicates how the axes are permuted (see Examples). If axes are not provided and a.shape = (i[0], i[1], ... i[n-2], i[n-1]), then a.transpose().shape = (i[n-1], i[n-2], ... i[1], i[0]). Inputs: - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. - **input_perm** (tuple[int]) - The permutation to be converted. The elements in `input_perm` are composed of the indexes of each dimension of `input_x`. The length of `input_perm` and the shape of `input_x` must be the same. Only constant value is allowed. Must be in the range [0, rank(input_x)). Outputs: Tensor, the type of output tensor is the same as `input_x` and the shape of output tensor is decided by the shape of `input_x` and the value of `input_perm`. Raises: TypeError: If `input_perm` is not a tuple. ValueError: If length of shape of `input_x` is not equal to length of shape of `input_perm`. ValueError: If the same element exists in `input_perm`. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Tensor(np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]), mindspore.float32) >>> input_perm = (0, 2, 1) >>> transpose = ops.Transpose() >>> output = transpose(input_x, input_perm) >>> print(output) [[[ 1. 4.] [ 2. 5.] [ 3. 6.]] [[ 7. 10.] [ 8. 11.] [ 9. 12.]]] """ @prim_attr_register def __init__(self): """Initialize Transpose""" self.init_prim_io_names(inputs=['x', 'perm'], outputs=['output']) class Unique(Primitive): """ Returns the unique elements of input tensor and also return a tensor containing the index of each value of input tensor corresponding to the output unique tensor. The output contains Tensor `y` and Tensor `idx`, the format is probably similar to (`y`, `idx`). The shape of Tensor `y` and Tensor `idx` is different in most cases, because Tensor `y` will be deduplicated, and the shape of Tensor `idx` is consistent with the input. To get the same shape between `idx` and `y`, please ref to 'UniqueWithPad' operator. Inputs: - **input_x** (Tensor) - The input tensor. The shape is :math:`(N,*)` where :math:`*` means, any number of additional dimensions. Outputs: Tuple, containing Tensor objects (`y`, `idx`), `y` is a tensor with the same type as `input_x`, and contains the unique elements in `x`, sorted in ascending order. `idx` is a tensor containing indices of elements in the input corresponding to the output tensor. Raises: TypeError: If `input_x` is not a Tensor. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Tensor(np.array([1, 2, 5, 2]), mindspore.int32) >>> output = ops.Unique()(input_x) >>> print(output) (Tensor(shape=[3], dtype=Int32, value= [1, 2, 5]), Tensor(shape=[4], dtype=Int32, value= [0, 1, 2, 1])) >>> y = output[0] >>> print(y) [1 2 5] >>> idx = output[1] >>> print(idx) [0 1 2 1] >>> # As can be seen from the above, y and idx shape >>> # note that for GPU, this operator must be wrapped inside a model, and executed in graph mode. >>> class UniqueNet(nn.Cell): ... def __init__(self): ... super(UniqueNet, self).__init__() ... self.unique_op = ops.Unique() ... ... def construct(self, x): ... output, indices = self.unique_op(x) ... return output, indices ... >>> input_x = Tensor(np.array([1, 2, 5, 2]), mindspore.int32) >>> net = UniqueNet() >>> output = net(input_x) >>> print(output) (Tensor(shape=[3], dtype=Int32, value= [1, 2, 5]), Tensor(shape=[4], dtype=Int32, value= [0, 1, 2, 1])) """ @prim_attr_register def __init__(self): self.init_prim_io_names(inputs=['x'], outputs=['output']) class Gather(Primitive): r""" Returns a slice of the input tensor based on the specified indices and axis. Slices the input tensor base on the indices at specified axis. See the following example for more clear. Inputs: - **input_params** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. The original Tensor. - **input_indices** (Tensor) - The shape of tensor is :math:`(y_1, y_2, ..., y_S)`. Specifies the indices of elements of the original Tensor. Must be in the range `[0, input_param.shape[axis])` which are only validated on CPU. The data type can be int32 or int64. - **axis** (int) - Specifies the dimension index to gather indices. Outputs: Tensor, the shape of tensor is :math:`input\_params.shape[:axis] + input\_indices.shape + input\_params.shape[axis + 1:]`. Raises: TypeError: If `axis` is not an int. TypeError: If `input_indices` is not an int. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_params = Tensor(np.array([[1, 2, 7, 42], [3, 4, 54, 22], [2, 2, 55, 3]]), mindspore.float32) >>> input_indices = Tensor(np.array([1, 2]), mindspore.int32) >>> axis = 1 >>> output = ops.Gather()(input_params, input_indices, axis) >>> print(output) [[ 2. 7.] [ 4. 54.] [ 2. 55.]] >>> axis = 0 >>> output = ops.Gather()(input_params, input_indices, axis) >>> print(output) [[3. 4. 54. 22.] [2. 2. 55. 3.]] """ @prim_attr_register def __init__(self): """Initialize Gather""" self.init_prim_io_names(inputs=['params', 'indices', 'axis'], outputs=['output']) class GatherV2(PrimitiveWithCheck): """ Same as operator Gather. GatherV2 will be deprecated in the future. Please use Gather instead. """ @deprecated("1.1", "Gather", True) @prim_attr_register def __init__(self): """Initialize GatherV2""" self.init_prim_io_names(inputs=['params', 'indices', 'axis'], outputs=['output']) def __check__(self, params, indices, axis): validator.check_subclass("params", params['dtype'], mstype.tensor, self.name) validator.check_tensor_dtype_valid("indices", indices['dtype'], mstype.int_type, self.name) validator.check_subclass("axis", axis['dtype'], [mstype.number], self.name) axis_v = axis['value'] validator.check_value_type('axis', axis_v, [int], self.name) rank = len(params['shape']) validator.check_int_range(axis_v, -rank, rank, Rel.INC_LEFT, "axis", self.name) class SparseGatherV2(PrimitiveWithCheck): """ Returns a slice of input tensor based on the specified indices and axis. Inputs: - **input_params** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. - **input_indices** (Tensor) - The shape of tensor is :math:`(y_1, y_2, ..., y_S)`. Specifies the indices of elements of the original Tensor, must be in the range `[0, input_param.shape[axis])`. - **axis** (int) - Specifies the dimension index to gather indices. Outputs: Tensor, the shape of tensor is :math:`(z_1, z_2, ..., z_N)`. Raises: TypeError: If `axis` is not an int. Supported Platforms: ``Ascend`` ``GPU`` Examples: >>> input_params = Tensor(np.array([[1, 2, 7, 42], [3, 4, 54, 22], [2, 2, 55, 3]]), mindspore.float32) >>> input_indices = Tensor(np.array([1, 2]), mindspore.int32) >>> axis = 1 >>> out = ops.SparseGatherV2()(input_params, input_indices, axis) >>> print(out) [[2. 7.] [4. 54.] [2. 55.]] """ @prim_attr_register def __init__(self): """Initialize SparseGatherV2""" self.init_prim_io_names(inputs=['params', 'indices', 'axis'], outputs=['output']) def __check__(self, params, indices, axis): validator.check_subclass("params", params['dtype'], mstype.tensor, self.name) validator.check_tensor_dtype_valid("indices", indices['dtype'], mstype.int_type, self.name) validator.check_subclass("axis", axis['dtype'], [mstype.number], self.name) axis_v = axis['value'] validator.check_value_type('axis', axis_v, [int], self.name) rank = len(params['shape']) validator.check_int_range(axis_v, -rank, rank, Rel.INC_LEFT, "axis", self.name) class Padding(PrimitiveWithInfer): """ Extends the last dimension of the input tensor from 1 to pad_dim_size, by filling with 0. Args: pad_dim_size (int): The value of the last dimension of `x` to be extended, which must be positive. Default: 8. Inputs: - **x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. The rank of `x` must be at least 2. The last dimension of `x` must be 1. The data type is Number. Outputs: Tensor, the shape of tensor is :math:`(z_1, z_2, ..., z_N)`. Raises: TypeError: If `pad_dim_size` is not an int. ValueError: If `pad_dim_size` is less than 1. ValueError: If last dim of `x` is not equal 1. Supported Platforms: ``Ascend`` Examples: >>> x = Tensor(np.array([[8], [10]]), mindspore.float32) >>> pad_dim_size = 4 >>> output = ops.Padding(pad_dim_size)(x) >>> print(output) [[ 8. 0. 0. 0.] [10. 0. 0. 0.]] """ @prim_attr_register def __init__(self, pad_dim_size=8): """Initialize padding""" validator.check_value_type("pad_dim_size", pad_dim_size, [int], self.name) validator.check_positive_int(pad_dim_size, "pad_dim_size", self.name) self.pad_dim_size = pad_dim_size def __infer__(self, x): validator.check_subclass("x", x['dtype'], mstype.tensor, self.name) x_shape = list(x['shape']) validator.check_int(len(x_shape), 1, Rel.GT, "rank of x", self.name) validator.check_int(x_shape[-1], 1, Rel.EQ, "last dim of x", self.name) out_shape = x_shape out_shape[-1] = self.pad_dim_size out = {'shape': out_shape, 'dtype': x['dtype'], 'value': None} return out class UniqueWithPad(PrimitiveWithInfer): """ Returns unique elements and relative indexes in 1-D tensor, filled with padding num. The basic function is the same as the Unique operator, but the UniqueWithPad operator adds a Pad function. The returned tuple(`y`, `idx`) after the input Tensor `x` is processed by the unique operator, in which the shapes of `y` and `idx` are mostly not equal. Therefore, in order to solve the above situation, the UniqueWithPad operator will fill the `y` Tensor with the `pad_num` specified by the user to make it have the same shape as the Tensor `idx`. Inputs: - **x** (Tensor) - The tensor need to be unique. Must be 1-D vector with types: int32, int64. - **pad_num** (int) - Pad num. The data type is an int. Outputs: tuple(Tensor), tuple of 2 tensors, `y` and `idx`. - y (Tensor) - The unique elements filled with pad_num, the shape and data type same as `x`. - idx (Tensor) - The index of each value of `x` in the unique output `y`, the shape and data type same as `x`. Raises: TypeError: If dtype of `x` is neither int32 nor int64. ValueError: If length of shape of `x` is not equal to 1. Supported Platforms: ``Ascend`` ``CPU`` Examples: >>> x = Tensor(np.array([1, 1, 5, 5, 4, 4, 3, 3, 2, 2,]), mindspore.int32) >>> pad_num = 8 >>> output = ops.UniqueWithPad()(x, pad_num) >>> print(output) (Tensor(shape=[10], dtype=Int32, value= [1, 5, 4, 3, 2, 8, 8, 8, 8, 8]), Tensor(shape=[10], dtype=Int32, value= [0, 0, 1, 1, 2, 2, 3, 3, 4, 4])) """ @prim_attr_register def __init__(self): """init UniqueWithPad""" def __infer__(self, x, pad_num): validator.check_tensor_dtype_valid("x", x['dtype'], [mstype.int32, mstype.int64], self.name) validator.check_subclass("pad_num", pad_num['dtype'], [mstype.int32, mstype.int64], self.name) x_shape = list(x['shape']) validator.check("rank of x", len(x_shape), "expected", 1, Rel.EQ, self.name) out_shape = x_shape out = {'shape': (out_shape, out_shape), 'dtype': (x['dtype'], x['dtype']), 'value': None} return out class Split(PrimitiveWithCheck): """ Splits the input tensor into output_num of tensors along the given axis and output numbers. The `input_x` tensor will be split into equally sized sub-tensors. This requires that `input_x.shape(axis)` is divisible by `output_num`. Args: axis (int): Index of the split position. Default: 0. output_num (int): The number of output tensors. Must be positive int. Default: 1. Inputs: - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. Outputs: tuple[Tensor], the shape of each output tensor is the same, which is :math:`(y_1, y_2, ..., y_S)`. And the data type is the same with `input_x`. Raises: TypeError: If `axis` or `output_num` is not an int. ValueError: If `axis` is out of the range [-len(`input_x.shape`), len(`input_x.shape`)), or if the `output_num` is less than or equal to 0. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> split = ops.Split(1, 2) >>> x = Tensor(np.array([[1, 1, 1, 1], [2, 2, 2, 2]]), mindspore.int32) >>> print(x) [[1 1 1 1] [2 2 2 2]] >>> output = split(x) >>> print(output) (Tensor(shape=[2, 2], dtype=Int32, value= [[1, 1], [2, 2]]), Tensor(shape=[2, 2], dtype=Int32, value= [[1, 1], [2, 2]])) >>> split = ops.Split(1, 4) >>> output = split(x) >>> print(output) (Tensor(shape=[2, 1], dtype=Int32, value= [[1], [2]]), Tensor(shape=[2, 1], dtype=Int32, value= [[1], [2]]), Tensor(shape=[2, 1], dtype=Int32, value= [[1], [2]]), Tensor(shape=[2, 1], dtype=Int32, value= [[1], [2]])) """ @prim_attr_register def __init__(self, axis=0, output_num=1): """Initialize Split""" validator.check_value_type("axis", axis, [int], self.name) validator.check_value_type("output_num", output_num, [int], self.name) validator.check_positive_int(output_num, "output_num", self.name) self.axis = axis self.output_num = output_num def __check__(self, x): validator.check_subclass("x", x['dtype'], mstype.tensor, self.name) x_shape = list(x['shape']) dim = len(x_shape) validator.check_int_range(self.axis, -dim, dim, Rel.INC_LEFT, 'axis value', self.name) if -1 not in x_shape: # only validate when shape fully known output_valid_check = x_shape[self.axis] % self.output_num if output_valid_check != 0: raise ValueError(f"For '{self.name}', the specified axis of 'input_x' should be divided exactly by " f"'output_num', but got the shape of 'input_x' in 'axis' {self.axis} is " f"{x_shape[self.axis]}, 'output_num': {self.output_num}.") size_splits = [x_shape[self.axis] // self.output_num] * self.output_num self.add_prim_attr('size_splits', size_splits) class Rank(PrimitiveWithInfer): """ Returns the rank of a tensor. Returns a 0-D int32 Tensor representing the rank of input; the rank of a tensor is the number of indices required to uniquely select each element of the tensor. Inputs: - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. The data type is Number. Outputs: Tensor. 0-D int32 Tensor representing the rank of input, i.e., :math:`R`. The data type is an int. Raises: TypeError: If `input_x` is not a Tensor. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_tensor = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32) >>> rank = ops.Rank() >>> output = rank(input_tensor) >>> print(output) 2 >>> print(type(output)) <class 'int'> """ @prim_attr_register def __init__(self): """Initialize Rank""" def __infer__(self, x): validator.check_subclass("x", x['dtype'], mstype.tensor, self.name) out = {'shape': None, 'dtype': None, 'value': len(x['shape'])} return out class TruncatedNormal(PrimitiveWithInfer): """ Returns a tensor of the specified shape filled with truncated normal values. The generated values follow a normal distribution. Args: seed (int): A integer number used to create random seed. Default: 0. dtype (:class:`mindspore.dtype`): Data type. Default: mindspore.float32. Inputs: - **shape** (tuple[int]) - The shape of the output tensor, is a tuple of positive integer. Outputs: Tensor, the data type of output tensor is the same as attribute `dtype`. Examples: >>> shape = (1, 2, 3) >>> truncated_normal = ops.TruncatedNormal() >>> output = truncated_normal(shape) """ @prim_attr_register def __init__(self, seed=0, dtype=mstype.float32): """Initialize TruncatedNormal""" validator.check_value_type('seed', seed, [int], self.name) validator.check_types_same_and_valid({'dtype': dtype}, mstype.number_type, self.name) def __infer__(self, shape): shape_value = shape['value'] validator.check_value_type("shape", shape_value, [tuple], self.name) for i, value in enumerate(shape_value): validator.check_positive_int(value, f'{i}th value of shape', self.name) out = {'shape': shape_value, 'dtype': mstype.tensor_type(self.dtype), 'value': None} return out class Size(PrimitiveWithInfer): r""" Returns the size of a Tensor. Returns an int scalar representing the elements' size of input, the total number of elements in the tensor. Inputs: - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. The data type is Number. Outputs: int. A scalar representing the elements' size of `input_x`, tensor is the number of elements in a tensor, :math:`size=x_1*x_2*...x_R`. The data type is an int. Raises: TypeError: If `input_x` is not a Tensor. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32) >>> size = ops.Size() >>> output = size(input_x) >>> print(output) 4 """ @prim_attr_register def __init__(self): """Initialize Size""" def __infer__(self, x): size = 1 validator.check_subclass("x", x['dtype'], mstype.tensor, self.name) shp = x['shape'] if not shp: size = 0 else: size = functools.reduce(lambda x, y: x * y, x['shape']) out = {'shape': None, 'dtype': mstype.int64, 'value': size} return out class Fill(PrimitiveWithInfer): """ Creates a tensor filled with a scalar value. Creates a tensor with shape described by the first argument and fills it with values in the second argument. Inputs: - **type** (mindspore.dtype) - The specified type of output tensor. Only constant value is allowed. - **shape** (tuple) - The specified shape of output tensor. Only constant value is allowed. - **value** (scalar) - Value to fill the returned tensor. Only constant value is allowed. Outputs: Tensor, has the same type and shape as input value. Raises: TypeError: If `shape` is not a tuple. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> fill = ops.Fill() >>> output = fill(mindspore.float32, (2, 2), 1) >>> print(output) [[1. 1.] [1. 1.]] >>> output = fill(mindspore.float32, (3, 3), 0) >>> print(output) [[0. 0. 0.] [0. 0. 0.] [0. 0. 0.]] """ @prim_attr_register def __init__(self): """Initialize Fill""" def __infer__(self, dtype, dims, x): validator.check_value_type("shape", dims['value'], [tuple], self.name) validator.check_value_type("value", x['value'], [numbers.Number, bool], self.name) for i, item in enumerate(dims['value']): validator.check_positive_int(item, f'dims[{i}]', self.name) valid_dtypes = [mstype.bool_, mstype.int8, mstype.int16, mstype.int32, mstype.int64, mstype.uint8, mstype.uint16, mstype.uint32, mstype.uint64, mstype.float16, mstype.float32, mstype.float64, mstype.complex64, mstype.complex128] validator.check_types_same_and_valid({"value": dtype['value']}, valid_dtypes, self.name) x_nptype = mstype.dtype_to_nptype(dtype['value']) ret = np.full(dims['value'], x['value'], x_nptype) out = { 'value': Tensor(ret), 'shape': dims['value'], 'dtype': x['dtype'], } return out class Ones(Primitive): r""" Creates a tensor filled with value ones. Creates a tensor with shape described by the first argument and fills it with value ones in type of the second argument. Inputs: - **shape** (Union[tuple[int], int]) - The specified shape of output tensor. Only constant positive int is allowed. - **type** (mindspore.dtype) - The specified type of output tensor. Only constant value is allowed. Outputs: Tensor, has the same type and shape as input shape value. Raises: TypeError: If `shape` is neither tuple nor int. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> ones = ops.Ones() >>> output = ones((2, 2), mindspore.float32) >>> print(output) [[1. 1.] [1. 1.]] >>> output = ones((3, 3), mindspore.float32) >>> print(output) [[1. 1. 1.] [1. 1. 1.] [1. 1. 1.]] """ @prim_attr_register def __init__(self): """Initialize Ones""" class Zeros(Primitive): r""" Creates a tensor filled with value zeros. Creates a tensor with shape described by the first argument and fills it with value zeros in type of the second argument. Inputs: - **shape** (Union[tuple[int], int]) - The specified shape of output tensor. Only constant positive int is allowed. - **type** (mindspore.dtype) - The specified type of output tensor. Only constant value is allowed. Outputs: Tensor, has the same type and shape as input shape value. Raises: TypeError: If `shape` is neither int nor tuple. TypeError: If `shape` is a tuple whose elements are not all int. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> zeros = ops.Zeros() >>> output = zeros((2, 2), mindspore.float32) >>> print(output) [[0. 0.] [0. 0.]] """ @prim_attr_register def __init__(self): """Initialize Zeros""" class OnesLike(Primitive): """ Creates a new tensor. The values of all elements are 1. Returns a tensor of ones with the same shape and type as the input. Inputs: - **input_x** (Tensor) - Input tensor. The shape is :math:`(N,*)` where :math:`*` means, any number of additional dimensions. Outputs: Tensor, has the same shape and type as `input_x` but filled with ones. Raises: TypeError: If `input_x` is not a Tensor. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> oneslike = ops.OnesLike() >>> input_x = Tensor(np.array([[0, 1], [2, 1]]).astype(np.int32)) >>> output = oneslike(input_x) >>> print(output) [[1 1] [1 1]] """ @prim_attr_register def __init__(self): """Initialize OnesLike""" class ZerosLike(Primitive): """ Creates a new tensor. All elements value are 0. Returns a tensor of zeros with the same shape and data type as the input tensor. Inputs: - **input_x** (Tensor) - Input tensor. The data type is int32, int64, float16 or float32. The shape is :math:`(N,*)` where :math:`*` means, any number of additional dimensions. Outputs: Tensor, has the same shape and data type as `input_x` but filled with zeros. Raises: TypeError: If `input_x` is not a Tensor. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> zeroslike = ops.ZerosLike() >>> input_x = Tensor(np.array([[0, 1], [2, 1]]).astype(np.float32)) >>> output = zeroslike(input_x) >>> print(output) [[0. 0.] [0. 0.]] """ @prim_attr_register def __init__(self): """Initialize ZerosLike""" self.init_prim_io_names(inputs=['x'], outputs=['y']) class TupleToArray(PrimitiveWithInfer): """ Converts a tuple to a tensor. If the type of the first number in the tuple is integer, the data type of the output tensor is int. Otherwise, the data type of the output tensor is float. Inputs: - **input_x** (tuple) - A tuple of numbers. These numbers have the same type. Only constant value is allowed. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. Outputs: Tensor, if the input tuple contains `N` numbers, then the shape of the output tensor is (N,). Raises: TypeError: If `input_x` is not a tuple. ValueError: If length of `input_x` is less than or equal to 0. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = (1,2,3) >>> print(type(input_x)) <class 'tuple'> >>> output = ops.TupleToArray()(input_x) >>> print(type(output)) <class 'mindspore.common.tensor.Tensor'> >>> print(output) [1 2 3] """ @prim_attr_register def __init__(self): """Initialize TupleToArray""" def infer_value(self, x): validator.check_value_type("x", x, [tuple], self.name) validator.check("size of x", len(x), '', 0, Rel.GT, self.name) dtype = type(x[0]) for i, item in enumerate(x): validator.check_value_type(f"x[{i}]", item, [numbers.Number], self.name) if not all(isinstance(item, dtype) for item in x): raise TypeError(f"For \'{self.name}\', all elements of 'input_x' must be have same type.") if isinstance(x[0], int): ret = np.array(x, np.int32) else: ret = np.array(x, np.float32) return Tensor(ret) def __call__(self, x): args = list() if isinstance(x, range): args.append(tuple(x)) else: args.append(x) return _run_op(self, self.name, args) class ScalarToArray(PrimitiveWithInfer): """ Converts a scalar to a `Tensor`. Inputs: - **input_x** (Union[int, float]) - The input is a scalar. Only constant value is allowed. Outputs: Tensor. 0-D Tensor and the content is the input. Raises: TypeError: If `input_x` is neither int nor float. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> op = ops.ScalarToArray() >>> input_x = 1.0 >>> print(type(input_x)) <class 'float'> >>> output = op(input_x) >>> print(type(output)) <class 'mindspore.common.tensor.Tensor'> >>> print(output) 1.0 """ @prim_attr_register def __init__(self): pass def infer_value(self, x): validator.check_value_type("x", x, [int, float], self.name) if isinstance(x, int): ret = np.array(x, np.int32) else: ret = np.array(x, np.float32) return Tensor(ret) class ScalarToTensor(PrimitiveWithInfer): """ Converts a scalar to a `Tensor`, and converts the data type to the specified type. Inputs: - **input_x** (Union[int, float]) - The input is a scalar. Only constant value is allowed. - **dtype** (mindspore.dtype) - The target data type. Default: mindspore.float32. Only constant value is allowed. Outputs: Tensor. 0-D Tensor and the content is the input. Raises: TypeError: If `input_x` is neither int nor float. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> op = ops.ScalarToTensor() >>> data = 1 >>> output = op(data, mindspore.float32) >>> print(output) 1.0 """ @prim_attr_register def __init__(self): pass def infer_value(self, x, dtype=mstype.float32): validator.check_value_type("x", x, [int, float], self.name) validator.check_subclass("dtype", dtype, mstype.number, self.name) data_type = mstype.dtype_to_nptype(dtype) return Tensor(np.array(x, data_type)) class InvertPermutation(PrimitiveWithInfer): r""" Computes the inverse of an index permutation. This operator is mainly used to calculate the inverse of index permutation. It requires a 1-dimensional integer tensor x, which represents the index of a zero-based array, and exchanges each value with its index position. In other words, For output tensor y and input tensor x, this operation calculates the following values: :math:`y[x[i]] = i, \quad i \in [0, 1, \ldots, \text{len}(x)-1]`. Note: These values must include 0. There must be no duplicate values and the values can not be negative. Inputs: - **input_x** (Union(tuple[int], list[int])) - The input is constructed by multiple integers, i.e., :math:`(y_1, y_2, ..., y_S)` representing the indices. The values must include 0. There can be no duplicate values or negative values. Only constant value is allowed. The maximum value must be equal to length of input_x. Outputs: tuple[int]. It has the same length as the input. Raises: TypeError: If `input_x` is neither tuple nor list. TypeError: If element of `input_x` is not an int. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> invert = ops.InvertPermutation() >>> input_data = (3, 4, 0, 2, 1) >>> output = invert(input_data) >>> print(output) (2, 4, 3, 0, 1) """ @prim_attr_register def __init__(self): """Initialize InvertPermutation""" self.set_const_prim(True) def __infer__(self, x): x_shp = x['shape'] x_value = x['value'] if mstype.issubclass_(x['dtype'], mstype.tensor): raise ValueError(f"For \'{self.name}\', the value of 'input_x' must be non-Tensor, but got {x['dtype']}") if x_value is None: raise ValueError(f"For '{self.name}', the value of 'input_x' can not be None, but got {x_value}.") validator.check_value_type("shape", x_shp, [tuple, list], self.name) for shp in x_shp: if shp: x_rank = len(np.array(x_value, np.int64).shape) raise ValueError(f"For \'{self.name}\', the dimension of 'input_x' must be 1, but got {x_rank}.") for i, value in enumerate(x_value): validator.check_value_type("input[%d]" % i, value, [int], self.name) z = [x_value[i] for i in range(len(x_value))] z.sort() for i in range(1, len(z)): if z[i - 1] == z[i]: raise ValueError(f"For '{self.name}', the 'input_x' can not contain duplicate values, " f"but got duplicated {z[i]} in the 'input_x'.") validator.check(f'value min', min(x_value), '', 0, Rel.EQ, self.name) validator.check(f'value max', max(x_value), '', len(x_value) - 1, Rel.EQ, self.name) y = [None] * len(x_value) for i, value in enumerate(x_value): validator.check_value_type("input[%d]" % i, value, [int], self.name) validator.check(f'value', z[i], f'index', i, Rel.EQ, self.name) y[value] = i z.append(value) return {'shape': x_shp, 'dtype': x['dtype'], 'value': tuple(y)} class Argmax(PrimitiveWithInfer): """ Returns the indices of the maximum value of a tensor across the axis. If the shape of input tensor is :math:`(x_1, ..., x_N)`, the shape of the output tensor will be :math:`(x_1, ..., x_{axis-1}, x_{axis+1}, ..., x_N)`. Args: axis (int): Axis where the Argmax operation applies to. Default: -1. output_type (:class:`mindspore.dtype`): An optional data type of `mindspore.dtype.int32`. Default: `mindspore.dtype.int32`. Inputs: - **input_x** (Tensor) - Input tensor. :math:`(N,*)` where :math:`*` means, any number of additional dimensions. Support data type list as follows: - Ascend: Float16, Float32. - GPU: Float16, Float32. - CPU: Float16, Float32, Float64. Outputs: Tensor, indices of the max value of input tensor across the axis. Raises: TypeError: If `axis` is not an int. TypeError: If `output_type` is neither int32 nor int64. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Tensor(np.array([[1, 20, 5], [67, 8, 9], [130, 24, 15]]).astype(np.float32)) >>> output = ops.Argmax(output_type=mindspore.int32)(input_x) >>> print(output) [1 0 0] """ @prim_attr_register def __init__(self, axis=-1, output_type=mstype.int32): """Initialize Argmax""" self.init_prim_io_names(inputs=['x'], outputs=['output']) validator.check_value_type("axis", axis, [int], self.name) validator.check_types_same_and_valid({'output': output_type}, [mstype.int32], self.name) self.axis = axis self.add_prim_attr('output_type', output_type) def infer_shape(self, x_shape): axis = self.axis if axis is None: axis = 0 x_rank = len(x_shape) validator.check_int_range(axis, -x_rank, x_rank, Rel.INC_LEFT, "axis", self.name) axis = axis + x_rank if axis < 0 else axis ouput_shape = [x_shape[i] for i in range(x_rank) if i != axis] return ouput_shape def infer_dtype(self, x_dtype): validator.check_tensor_dtype_valid("input_x", x_dtype, [mstype.float16, mstype.float32, mstype.float64], self.name) return mstype.tensor_type(self.output_type) class Argmin(PrimitiveWithInfer): """ Returns the indices of the minimum value of a tensor across the axis. If the shape of input tensor is :math:`(x_1, ..., x_N)`, the shape of the output tensor is :math:`(x_1, ..., x_{axis-1}, x_{axis+1}, ..., x_N)`. Args: axis (int): Axis where the Argmin operation applies to. Default: -1. output_type (:class:`mindspore.dtype`): An optional data type of `mindspore.dtype.int32`. Default: `mindspore.dtype.int32`. Inputs: - **input_x** (Tensor) - Input tensor. The shape is :math:`(N,*)` where :math:`*` means, any number of additional dimensions. Outputs: Tensor, indices of the min value of input tensor across the axis. Raises: TypeError: If `axis` is not an int. TypeError: If `output_type` is neither int32 nor int64. Supported Platforms: ``Ascend`` Examples: >>> input_x = Tensor(np.array([2.0, 3.1, 1.2]), mindspore.float32) >>> index = ops.Argmin()(input_x) >>> print(index) 2 """ @prim_attr_register def __init__(self, axis=-1, output_type=mstype.int32): """Initialize Argmin""" self.init_prim_io_names(inputs=['x'], outputs=['output']) validator.check_value_type("axis", axis, [int], self.name) validator.check_type_name("output_type", output_type, [mstype.int32, mstype.int64], self.name) self.axis = axis self.add_prim_attr('output_type', output_type) def infer_shape(self, x_shape): axis = self.axis if axis is None: axis = 0 x_rank = len(x_shape) validator.check_int_range(axis, -x_rank, x_rank, Rel.INC_LEFT, "axis", self.name) axis = axis + x_rank if axis < 0 else axis ouput_shape = [x_shape[i] for i in range(x_rank) if i != axis] return ouput_shape def infer_dtype(self, x_dtype): validator.check_subclass("input_x", x_dtype, mstype.tensor, self.name) return mstype.tensor_type(self.output_type) class ArgMaxWithValue(PrimitiveWithInfer): """ Calculates the maximum value with the corresponding index. Calculates the maximum value along with the given axis for the input tensor. It returns the maximum values and indices. Note: In auto_parallel and semi_auto_parallel mode, the first output index can not be used. .. warning:: - If there are multiple maximum values, the index of the first maximum value is used. - The value range of "axis" is [-dims, dims - 1]. "dims" is the dimension length of "input_x". Args: axis (int): The dimension to reduce. Default: 0. keep_dims (bool): Whether to reduce dimension, if true, the output will keep same dimension with the input, the output will reduce dimension if false. Default: False. Inputs: - **input_x** (Tensor) - The input tensor, can be any dimension. Set the shape of input tensor as :math:`(x_1, x_2, ..., x_N)`. And the data type only support mindspore.float16 or float32. Outputs: tuple (Tensor), tuple of 2 tensors, containing the corresponding index and the maximum value of the input tensor. - index (Tensor) - The index for the maximum value of the input tensor. If `keep_dims` is true, the shape of output tensors is :math:`(x_1, x_2, ..., x_{axis-1}, 1, x_{axis+1}, ..., x_N)`. Otherwise, the shape is :math:`(x_1, x_2, ..., x_{axis-1}, x_{axis+1}, ..., x_N)`. - output_x (Tensor) - The maximum value of input tensor, with the same shape as index. Raises: TypeError: If `keep_dims` is not a bool. TypeError: If `axis` is not an int. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Tensor(np.array([0.0, 0.4, 0.6, 0.7, 0.1]), mindspore.float32) >>> index, output = ops.ArgMaxWithValue()(input_x) >>> print(index, output) 3 0.7 >>> index, output = ops.ArgMaxWithValue(keep_dims=True)(input_x) >>> print(index, output) [3] [0.7] """ @prim_attr_register def __init__(self, axis=0, keep_dims=False): """Initialize ArgMaxWithValue""" self.axis = axis self.keep_dims = keep_dims validator.check_value_type('keep_dims', keep_dims, [bool], self.name) validator.check_value_type('axis', axis, [int], self.name) def infer_shape(self, x_shape): axis = self.axis x_rank = len(x_shape) validator.check_int_range(axis, -x_rank, x_rank, Rel.INC_LEFT, "axis", self.name) ouput_shape = _infer_shape_reduce(x_shape, self.axis, self.keep_dims, self.name) return ouput_shape, ouput_shape def infer_dtype(self, x_dtype): validator.check_subclass("input_x", x_dtype, mstype.tensor, self.name) return mstype.tensor_type(mstype.int32), x_dtype class ArgMinWithValue(PrimitiveWithInfer): """ Calculates the minimum value with corresponding index, and returns indices and values. Calculates the minimum value along with the given axis for the input tensor. It returns the minimum values and indices. Note: In auto_parallel and semi_auto_parallel mode, the first output index can not be used. .. warning:: - If there are multiple minimum values, the index of the first minimum value is used. - The value range of "axis" is [-dims, dims - 1]. "dims" is the dimension length of "input_x". Args: axis (int): The dimension to reduce. Default: 0. keep_dims (bool): Whether to reduce dimension, if true the output will keep the same dimension as the input, the output will reduce dimension if false. Default: False. Inputs: - **input_x** (Tensor) - The input tensor, can be any dimension. Set the shape of input tensor as :math:`(x_1, x_2, ..., x_N)`. Outputs: tuple (Tensor), tuple of 2 tensors, containing the corresponding index and the minimum value of the input tensor. - index (Tensor) - The index for the minimum value of the input tensor. If `keep_dims` is true, the shape of output tensors is :math:`(x_1, x_2, ..., x_{axis-1}, 1, x_{axis+1}, ..., x_N)`. Otherwise, the shape is :math:`(x_1, x_2, ..., x_{axis-1}, x_{axis+1}, ..., x_N)`. - output_x (Tensor) - The minimum value of input tensor, with the same shape as index. Raises: TypeError: If `keep_dims` is not a bool. TypeError: If `axis` is not an int. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Tensor(np.array([0.0, 0.4, 0.6, 0.7, 0.1]), mindspore.float32) >>> output = ops.ArgMinWithValue()(input_x) >>> print(output) (Tensor(shape=[], dtype=Int32, value= 0), Tensor(shape=[], dtype=Float32, value= 0)) >>> output = ops.ArgMinWithValue(keep_dims=True)(input_x) >>> print(output) (Tensor(shape=[1], dtype=Int32, value= [0]), Tensor(shape=[1], dtype=Float32, value= [ 0.00000000e+00])) """ @prim_attr_register def __init__(self, axis=0, keep_dims=False): """Initialize ArgMinWithValue""" self.axis = axis self.keep_dims = keep_dims validator.check_value_type('keep_dims', keep_dims, [bool], self.name) validator.check_value_type('axis', axis, [int], self.name) def infer_shape(self, x_shape): axis = self.axis x_rank = len(x_shape) validator.check_int_range(axis, -x_rank, x_rank, Rel.INC_LEFT, "axis", self.name) ouput_shape = _infer_shape_reduce(x_shape, self.axis, self.keep_dims, self.name) return ouput_shape, ouput_shape def infer_dtype(self, x_dtype): validator.check_subclass("input_x", x_dtype, mstype.tensor, self.name) return mstype.tensor_type(mstype.int32), x_dtype class Tile(PrimitiveWithInfer): r""" Replicates a tensor with given multiples times. Creates a new tensor by replicating `input_x` `multiples` times. The i'th dimension of output tensor has `input_x.shape(i) * multiples[i]` elements, and the values of `input_x` are replicated `multiples[i]` times along the i'th dimension. Note: The length of `multiples` must be greater or equal to the length of dimension in `input_x`. Inputs: - **input_x** (Tensor) - 1-D or higher Tensor. Set the shape of input tensor as :math:`(x_1, x_2, ..., x_S)`. - **multiples** (tuple[int]) - The input tuple is constructed by multiple integers, i.e., :math:`(y_1, y_2, ..., y_S)`. The length of `multiples` cannot be smaller than the length of the shape of `input_x`. Only constant value is allowed. Outputs: Tensor, has the same data type as the `input_x`. - If the length of `multiples` is the same as the length of shape of `input_x`, then the shape of their corresponding positions can be multiplied, and the shape of Outputs is :math:`(x_1*y_1, x_2*y_2, ..., x_S*y_R)`. - If the length of `multiples` is larger than the length of shape of `input_x`, fill in multiple 1 in the length of the shape of `input_x` until their lengths are consistent. Such as set the shape of `input_x` as :math:`(1, ..., x_1, x_2, ..., x_S)`, then the shape of their corresponding positions can be multiplied, and the shape of Outputs is :math:`(1*y_1, ..., x_S*y_R)`. Raises: TypeError: If `multiples` is not a tuple or its elements are not all int. ValueError: If the elements of `multiples` are not all greater than 0. ValueError: If the length of `multiples` are smaller than the length of dimension in `input_x`. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> tile = ops.Tile() >>> input_x = Tensor(np.array([[1, 2], [3, 4]]), mindspore.float32) >>> multiples = (2, 3) >>> output = tile(input_x, multiples) >>> print(output) [[1. 2. 1. 2. 1. 2.] [3. 4. 3. 4. 3. 4.] [1. 2. 1. 2. 1. 2.] [3. 4. 3. 4. 3. 4.]] >>> multiples = (2, 3, 2) >>> output = tile(input_x, multiples) >>> print(output) [[[1. 2. 1. 2.] [3. 4. 3. 4.] [1. 2. 1. 2.] [3. 4. 3. 4.] [1. 2. 1. 2.] [3. 4. 3. 4.]] [[1. 2. 1. 2.] [3. 4. 3. 4.] [1. 2. 1. 2.] [3. 4. 3. 4.] [1. 2. 1. 2.] [3. 4. 3. 4.]]] """ @prim_attr_register def __init__(self): """Initialize Tile""" self.init_prim_io_names(inputs=['x', 'multiples'], outputs=['output']) def check_elim(self, base_tensor, multiplier): if not isinstance(base_tensor, Tensor): raise TypeError(f"For '{self.name}', the type of 'input_x' should be Tensor, " f"but got {type(base_tensor).__name__}.") if all(v == 1 for v in multiplier) and len(base_tensor.shape) >= len(multiplier): return (True, base_tensor) return (False, None) def __infer__(self, x, multiples): multiples_v = multiples['value'] if multiples_v is None: if len(multiples['shape']) != 1: raise ValueError(f'For \'{self.name}\' the dim of multiples must be 1.') rank = max(len(x['shape']), multiples['shape'][0]) out_shape = [-1] * rank # tile can't infer min/max shape if multiples_v is None return {'shape': out_shape, 'dtype': x['dtype'], 'value': None, 'min_shape': [1] * rank, 'max_shape': [1] * rank } x_shp = x['shape'] validator.check_value_type( "multiples", multiples_v, [tuple], self.name) for i, multiple in enumerate(multiples_v): validator.check_positive_int( multiple, "multiples[%d]" % i, self.name) validator.check_value_type( "x[\'dtype\']", x["dtype"], mstype.tensor_type, self.name) len_sub = len(multiples_v) - len(x_shp) multiples_w = None if len_sub == 0: multiples_w = multiples_v if len_sub > 0: for i in range(0, len_sub): x_shp.insert(0, 1) multiples_w = multiples_v elif len_sub < 0: raise ValueError(f"For '{self.name}', the length of 'multiples' can not be smaller than " f"the dimension of 'input_x', but got length of 'multiples': {len(multiples_v)} " f"and dimension of 'input_x': {len(x_shp)}.") for i, a in enumerate(multiples_w): x_shp[i] *= a value = None if x['value'] is not None: value = Tensor(np.tile(x['value'].asnumpy(), multiples_w)) return {'shape': x_shp, 'dtype': x['dtype'], 'value': value} class UnsortedSegmentSum(PrimitiveWithInfer): r""" Computes the sum of a tensor along segments. Calculates a tensor such that :math:`\text{output}[i] = \sum_{segment\_ids[j] == i} \text{data}[j, \ldots]`, where :math:`j` is a tuple describing the index of element in data. `segment_ids` selects which elements in data to sum up. Segment_ids does not need to be sorted, and it does not need to cover all values in the entire valid value range. The following figure shows the calculation process of UnsortedSegmentSum: .. image:: api_img/UnsortedSegmentSum.png Note: - If the segment_id i is absent in the segment_ids, then output[i] will be filled with 0. - On Ascend, if the value of segment_id is less than 0 or greater than the length of the input data shape, an execution error will occur. If the sum of the given segment_ids :math:`i` is empty, then :math:`\text{output}[i] = 0`. If the given segment_ids is negative, the value will be ignored. 'num_segments' must be equal to the number of different segment_ids. Inputs: - **input_x** (Tensor) - The shape is :math:`(x_1, x_2, ..., x_R)`. - **segment_ids** (Tensor) - Set the shape as :math:`(x_1, x_2, ..., x_N)`, where 0 < N <= R. - **num_segments** (int) - Set :math:`z` as num_segments. Outputs: Tensor, the shape is :math:`(z, x_{N+1}, ..., x_R)`. Raises: TypeError: If `num_segments` is not an int. ValueError: If length of shape of `segment_ids` is less than 1. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Tensor([1, 2, 3, 4], mindspore.float32) >>> segment_ids = Tensor([0, 0, 1, 2], mindspore.int32) >>> num_segments = 4 >>> output = ops.UnsortedSegmentSum()(input_x, segment_ids, num_segments) >>> print(output) [3. 3. 4. 0.] >>> input_x = Tensor([1, 2, 3, 4, 2, 5], mindspore.float32) >>> segment_ids = Tensor([0, 0, 1, 2, 3, 4], mindspore.int32) >>> num_segments = 6 >>> output = ops.UnsortedSegmentSum()(input_x, segment_ids, num_segments) >>> print(output) [3. 3. 4. 2. 5. 0.] """ @prim_attr_register def __init__(self): """Initialize UnsortedSegmentSum""" self.init_prim_io_names(inputs=['x', 'segment_ids', 'num_segments'], outputs=['y']) def __infer__(self, x, segment_ids, num_segments): x_type = x['dtype'] x_shp = x['shape'] validator.check_subclass("input_x", x_type, mstype.tensor, self.name) validator.check_value_type("x_shape", x_shp, [list], self.name) x_shp_len = len(x_shp) validator.check_positive_int(x_shp_len, "rank of input_x", self.name) segment_ids_shp = segment_ids['shape'] segment_ids_type = segment_ids['dtype'] validator.check_subclass("segment_ids", segment_ids_type, mstype.tensor, self.name) validator.check_value_type("segment_ids", segment_ids_shp, [list], self.name) segment_ids_shp_len = len(segment_ids_shp) validator.check_positive_int(segment_ids_shp_len, "rank of segment_ids", self.name) validator.check(f'rank of input_x', len(x_shp), 'rank of segments_id', len(segment_ids_shp), Rel.GE, self.name) if -1 not in x_shp and -1 not in segment_ids_shp: # only validate when both shapes fully known for i, value in enumerate(segment_ids_shp): validator.check("ids[%d]" % i, value, 'input[%d]' % i, x_shp[i], Rel.EQ, self.name) num_segments_v = num_segments['value'] num_segments_type = num_segments['dtype'] validator.check_subclass("num_segments", num_segments_type, [mstype.tensor, mstype.number], self.name) if isinstance(num_segments_type, type(mstype.tensor)): validator.check_tensor_dtype_valid("num_segments", num_segments_type, [mstype.int32, mstype.int64], self.name) shp = [-1] else: validator.check_value_type('num_segments', num_segments_v, [int], self.name) validator.check_positive_int(num_segments_v, "num_segments", self.name) shp = [num_segments_v] shp += x_shp[segment_ids_shp_len:] if "max_value" in num_segments and "min_value" in num_segments: output_max_shape = list(num_segments['max_value']) output_min_shape = list(num_segments['min_value']) else: if isinstance(num_segments_type, type(mstype.tensor)): raise ValueError(f"For '{self.name}', the dtype of 'num_segments' only support int type " f"when it is not a dynamic value, but got type of 'num_segments': " f"{num_segments_type}.") output_max_shape = [num_segments_v] output_min_shape = [num_segments_v] if 'max_shape' in x and 'min_shape' in x: max_output_incoming = x['max_shape'] min_output_incoming = x['min_shape'] else: max_output_incoming = x_shp min_output_incoming = x_shp output_max_shape += max_output_incoming[segment_ids_shp_len:] output_min_shape += min_output_incoming[segment_ids_shp_len:] return {'shape': shp, 'max_shape': output_max_shape, 'min_shape': output_min_shape, 'dtype': mstype.tensor_type(x_type.element_type()), 'value': None} class UnsortedSegmentMin(PrimitiveWithCheck): r""" Computes the minimum of a tensor along segments. The following figure shows the calculation process of UnsortedSegmentMin: .. image:: api_img/UnsortedSegmentMin.png .. math:: \text { output }_i=\text{min}_{j \ldots} \text { data }[j \ldots] where :math:`min` over tuples :math:`j...` such that :math:`segment_ids[j...] == i`. Note: If the segment_id i is absent in the segment_ids, then output[i] will be filled with the maximum value of the input_x's type. The `segment_ids` must be non-negative tensor. Inputs: - **input_x** (Tensor) - The shape is :math:`(x_1, x_2, ..., x_R)`. The data type must be float16, float32 or int32. - **segment_ids** (Tensor) - A `1-D` tensor whose shape is :math:`(x_1)`, the value must be non-negative tensor. The data type must be int32. - **num_segments** (int) - The value specifies the number of distinct `segment_ids`. Outputs: Tensor, set the number of `num_segments` as `N`, the shape is :math:`(N, x_2, ..., x_R)`. Raises: TypeError: If `num_segments` is not an int. ValueError: If length of shape of `segment_ids` is not equal to 1. Supported Platforms: ``Ascend`` ``GPU`` Examples: >>> input_x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [4, 2, 1]]).astype(np.float32)) >>> segment_ids = Tensor(np.array([0, 1, 1]).astype(np.int32)) >>> num_segments = 2 >>> unsorted_segment_min = ops.UnsortedSegmentMin() >>> output = unsorted_segment_min(input_x, segment_ids, num_segments) >>> print(output) [[1. 2. 3.] [4. 2. 1.]] """ @prim_attr_register def __init__(self): """Initialize UnsortedSegmentMin""" self.init_prim_io_names(inputs=['x', 'segment_ids', 'num_segments'], outputs=['y']) def __check__(self, x, segment_ids, num_segments): x_shape = x['shape'] segment_ids_shape = segment_ids['shape'] valid_type = [mstype.float16, mstype.float32, mstype.int32] validator.check_tensor_dtype_valid("x", x['dtype'], valid_type, self.name) validator.check_tensor_dtype_valid("segment_ids", segment_ids['dtype'], [mstype.int32], self.name) validator.check_equal_int(len(segment_ids_shape), 1, "rank of segment_ids_shape", self.name) num_segments_type = num_segments['dtype'] validator.check_subclass("num_segments", num_segments_type, [mstype.number], self.name) if -1 not in x_shape and -1 not in segment_ids_shape: # only validate when both shapes fully known validator.check(f'first shape of input_x', x_shape[0], 'length of segments_id', segment_ids_shape[0], Rel.EQ, self.name) num_segments_v = num_segments['value'] validator.check_value_type('num_segments', num_segments_v, [int], self.name) validator.check_positive_int(num_segments_v, "num_segments", self.name) class UnsortedSegmentMax(PrimitiveWithCheck): r""" Computes the maximum along segments of a tensor. The following figure shows the calculation process of UnsortedSegmentMax: .. image:: api_img/UnsortedSegmentMax.png .. math:: \text { output }_i=\text{max}_{j \ldots} \text { data }[j \ldots] where :math:`max` over tuples :math:`j...` such that :math:`segment\_ids[j...] == i`. Note: If the segment_id i is absent in the segment_ids, then output[i] will be filled with the minimum value of the input_x's type. Inputs: - **input_x** (Tensor) - The shape is :math:`(x_1, x_2, ..., x_R)`. The data type must be float16, float32 or int32. - **segment_ids** (Tensor) - A `1-D` tensor whose shape is :math:`(x_1)`, the value must be non-negative tensor. The data type must be int32. - **num_segments** (int) - The value specifies the number of distinct `segment_ids`. Outputs: Tensor, set the number of `num_segments` as `N`, the shape is :math:`(N, x_2, ..., x_R)`. Raises: TypeError: If `num_segments` is not an int. ValueError: If length of shape of `segment_ids` is not equal to 1. Supported Platforms: ``Ascend`` ``GPU`` Examples: >>> # case 1: Only have two num_segments, where is 0 and 1, and segment_ids=[0, 1, 1] >>> # num_segments = 2 indicates that there are two types of segment_id, >>> # the first number '0' in [0, 1, 1] indicates input_x[0], >>> # the second number '1' in [0, 1, 1] indicates input_x[1], >>> # the third number '1' in [0, 1, 1] indicates input_x[2], >>> # input_x[0], which is [1, 2, 3] will not be compared to other segment_id. >>> # Only the same segment_id will be compared. >>> from mindspore import Tensor >>> from mindspore import ops >>> import numpy as np >>> input_x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [4, 2, 1]]).astype(np.float32)) >>> segment_ids = Tensor(np.array([0, 1, 1]).astype(np.int32)) >>> num_segments = 2 >>> unsorted_segment_max = ops.UnsortedSegmentMax() >>> output = unsorted_segment_max(input_x, segment_ids, num_segments) >>> print(output) [[1. 2. 3.] [4. 5. 6.]] >>> >>> # case 2: The segment_ids=[0, 0, 1, 1]. >>> # [1, 2, 3] will compare with [4, 2, 0], >>> # and [4, 5, 6] will compare with [4, 2, 1]. >>> input_x = Tensor(np.array([[1, 2, 3], [4, 2, 0], [4, 5, 6], [4, 2, 1]]).astype(np.float32)) >>> segment_ids = Tensor(np.array([0, 0, 1, 1]).astype(np.int32)) >>> num_segments = 2 >>> unsorted_segment_max = ops.UnsortedSegmentMax() >>> output = unsorted_segment_max(input_x, segment_ids, num_segments) >>> print(input_x.shape) (4, 3) >>> print(output) [[4. 2. 3.] [4. 5. 6.]] >>> # case 3: If the input_x have three dimensions even more, what will happen? >>> # The shape of input_x is (2, 4, 3), >>> # and the length of segment_ids should be the same as the first dimension of input_x. >>> # Because the segment_ids are different, input_x[0] will not be compared to input_x[1]. >>> input_x = Tensor(np.array([[[1, 2, 3], [4, 2, 0], [4, 5, 6], [4, 2, 1]], ... [[1, 2, 3], [4, 2, 0], [4, 5, 6], [4, 2, 1]]]).astype(np.float32)) >>> segment_ids = Tensor(np.array([0, 1]).astype(np.int32)) >>> num_segments = 2 >>> unsorted_segment_max = ops.UnsortedSegmentMax() >>> output = unsorted_segment_max(input_x, segment_ids, num_segments) >>> print(input_x.shape) (2, 4, 3) >>> print(output) [[[1. 2. 3.] [4. 2. 0.] [4. 5. 6.] [4. 2. 1.]] [[1. 2. 3.] [4. 2. 0.] [4. 5. 6.] [4. 2. 1.]]] >>> # case 4: It has the same input with the 3rd case. >>> # Because num_segments is equal to 2, there are two segment_ids, but currently only one 0 is used. >>> # the segment_id i is absent in the segment_ids, then output[i] will be filled with >>> # the smallest possible value of the input_x's type. >>> segment_ids = Tensor(np.array([0, 0]).astype(np.int32)) >>> output = unsorted_segment_max(input_x, segment_ids, num_segments) >>> print(output) [[[ 1.0000000e+00 2.0000000e+00 3.0000000e+00] [ 4.0000000e+00 2.0000000e+00 0.0000000e+00] [ 4.0000000e+00 5.0000000e+00 6.0000000e+00] [ 4.0000000e+00 2.0000000e+00 1.0000000e+00]] [[-3.4028235e+38 -3.4028235e+38 -3.4028235e+38] [-3.4028235e+38 -3.4028235e+38 -3.4028235e+38] [-3.4028235e+38 -3.4028235e+38 -3.4028235e+38] [-3.4028235e+38 -3.4028235e+38 -3.4028235e+38]]] """ @prim_attr_register def __init__(self): """Initialize UnsortedSegmentMax""" self.init_prim_io_names(inputs=['x', 'segment_ids', 'num_segments'], outputs=['y']) def __check__(self, x, segment_ids, num_segments): x_shape = x['shape'] segment_ids_shape = segment_ids['shape'] valid_type = [mstype.float16, mstype.float32, mstype.int32] validator.check_tensor_dtype_valid("x", x['dtype'], valid_type, self.name) validator.check_tensors_dtypes_same_and_valid({"segment_ids": segment_ids['dtype']}, [mstype.int32, mstype.int64], self.name) validator.check_equal_int(len(segment_ids_shape), 1, "rank of segment_ids_shape", self.name) num_segments_type = num_segments['dtype'] validator.check_subclass("num_segments", num_segments_type, [mstype.number], self.name) if -1 not in x_shape and -1 not in segment_ids_shape: # only validate when both shapes fully known validator.check(f'first shape of input_x', x_shape[0], 'length of segments_id', segment_ids_shape[0], Rel.EQ, self.name) num_segments_v = num_segments['value'] validator.check_value_type('num_segments', num_segments_v, [int], self.name) validator.check_positive_int(num_segments_v, "num_segments", self.name) class UnsortedSegmentProd(PrimitiveWithInfer): """ Computes the product of a tensor along segments. The following figure shows the calculation process of UnsortedSegmentProd: .. image:: api_img/UnsortedSegmentProd.png Inputs: - **input_x** (Tensor) - The shape is :math:`(x_1, x_2, ..., x_R)`. With float16, float32 or int32 data type. - **segment_ids** (Tensor) - A `1-D` tensor whose shape is :math:`(x_1)`, the value must be non-negative tensor. Data type must be int32. - **num_segments** (int) - The value specifies the number of distinct `segment_ids`, must be greater than 0. Outputs: Tensor, set the number of `num_segments` as `N`, the shape is :math:`(N, x_2, ..., x_R)`. Raises: TypeError: If `num_segments` is not an int. ValueError: If length of shape of `segment_ids` is not equal to 1. Supported Platforms: ``Ascend`` Examples: >>> input_x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [4, 2, 1]]).astype(np.float32)) >>> segment_ids = Tensor(np.array([0, 1, 0]).astype(np.int32)) >>> num_segments = 2 >>> unsorted_segment_prod = ops.UnsortedSegmentProd() >>> output = unsorted_segment_prod(input_x, segment_ids, num_segments) >>> print(output) [[4. 4. 3.] [4. 5. 6.]] """ @prim_attr_register def __init__(self): """Initialize UnsortedSegmentProd""" self.init_prim_io_names(inputs=['x', 'segment_ids', 'num_segments'], outputs=['y']) def __infer__(self, x, segment_ids, num_segments): x_type = x['dtype'] x_shape = x['shape'] segment_ids_shape = segment_ids['shape'] validator.check_subclass("input_x", x_type, mstype.tensor, self.name) validator.check_value_type("x_shape", x_shape, [list], self.name) valid_type = [mstype.float16, mstype.float32, mstype.int32] validator.check_tensor_dtype_valid("x", x['dtype'], valid_type, self.name) validator.check_tensor_dtype_valid("segment_ids", segment_ids['dtype'], [mstype.int32], self.name) validator.check_equal_int(len(segment_ids_shape), 1, "rank of segment_ids_shape", self.name) validator.check(f'first shape of input_x', x_shape[0], 'length of segments_id', segment_ids_shape[0], Rel.EQ, self.name) num_segments_v = num_segments['value'] validator.check_value_type('num_segments', num_segments_v, [int], self.name) validator.check_positive_int(num_segments_v, "num_segments", self.name) segment_ids_shape_len = len(segment_ids_shape) out_shape = [num_segments_v] out_shape += x_shape[segment_ids_shape_len:] out = {'shape': out_shape, 'dtype': mstype.tensor_type(x_type.element_type()), 'value': None} return out class Concat(PrimitiveWithInfer): r""" Connect tensor in the specified axis. Connect input tensors along with the given axis. The input data is a tuple of tensors. These tensors have the same rank `R`. Set the given axis as `m`, and :math:`0 \le m < R`. Set the number of input tensors as `N`. For the :math:`i`-th tensor :math:`t_i`, it has the shape of :math:`(x_1, x_2, ..., x_{mi}, ..., x_R)`. :math:`x_{mi}` is the :math:`m`-th dimension of the :math:`i`-th tensor. Then, the shape of the output tensor is .. math:: (x_1, x_2, ..., \sum_{i=1}^Nx_{mi}, ..., x_R) .. warning:: The value range of "axis" is [-dims, dims - 1]. "dims" is the dimension length of "input_x". Args: axis (int): The specified axis. Default: 0. Inputs: - **input_x** (tuple, list) - A tuple or a list of input tensors. Suppose there are two tensors in this tuple or list, namely x1 and x2. To perform `Concat` in the axis 0 direction, except for the 0th axis, all other axes should be equal, that is, :math:`x1.shape[1] == x2.shape[1], x1.shape[2] == x2.shape[2], ..., x1.shape[R] == x2.shape[R]`, where the :math:`R` indicates the last axis. Outputs: - Tensor, the shape is :math:`(x_1, x_2, ..., \sum_{i=1}^Nx_{mi}, ..., x_R)`. The data type is the same with `input_x`. Raises: TypeError: If `axis` is not an int. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x1 = Tensor(np.array([[0, 1], [2, 1]]).astype(np.float32)) >>> input_x2 = Tensor(np.array([[0, 1], [2, 1]]).astype(np.float32)) >>> op = ops.Concat() >>> output = op((input_x1, input_x2)) >>> print(output) [[0. 1.] [2. 1.] [0. 1.] [2. 1.]] >>> op = ops.Concat(1) >>> output = op((input_x1, input_x2)) >>> print(output) [[0. 1. 0. 1.] [2. 1. 2. 1.]] """ @prim_attr_register def __init__(self, axis=0): """Initialize Concat""" validator.check_value_type("axis", axis, [int], self.name) def __infer__(self, input_x): axis = self.axis x_shp = input_x['shape'] x_type = input_x['dtype'] _, all_shp, _ = get_concat_offset(x_shp, x_type, axis, self.name) self.add_prim_attr('inputNums', len(x_shp)) ret_shp = x_shp[0].copy() value = None if input_x['value'] is not None: value = Tensor(np.concatenate([x.asnumpy() for x in input_x['value']], axis=axis)) ret_shp[axis] = all_shp out = {'shape': ret_shp, 'dtype': x_type[0], 'value': value} if -1 in x_shp[0]: x_min_shp = input_x['min_shape'] ret_min_shp = x_min_shp[0].copy() ret_min_shp[axis] = 0 for all_min_shp in x_min_shp: ret_min_shp[axis] += all_min_shp[axis] out['min_shape'] = ret_min_shp x_max_shp = input_x['max_shape'] ret_max_shp = x_max_shp[0].copy() ret_max_shp[axis] = 0 for all_max_shp in x_max_shp: ret_max_shp[axis] += all_max_shp[axis] out['max_shape'] = ret_max_shp return out class ParallelConcat(PrimitiveWithInfer): r""" Concats tensor in the first dimension. Concats input tensors along with the first dimension. The difference between Concat and ParallelConcat is that Concat requires all of the inputs be computed before the operation will begin but doesn't require that the input shapes be known during graph construction. Parallel concat will copy pieces of the input into the output as they become available, in some situations this can provide a performance benefit. Note: The input tensors are all required to have size 1 in the first dimension. Inputs: - **values** (tuple, list) - A tuple or a list of input tensors. The data type and shape of these tensors must be the same. The data type is Number except float64. Outputs: Tensor, data type is the same as `values`. Raises: ValueError: If length of shape of `values` is less than 1. ValueError: The data type and shape of these tensors are not the same. Supported Platforms: ``Ascend`` Examples: >>> data1 = Tensor(np.array([[0, 1]]).astype(np.int32)) >>> data2 = Tensor(np.array([[2, 1]]).astype(np.int32)) >>> op = ops.ParallelConcat() >>> output = op((data1, data2)) >>> print(output) [[0 1] [2 1]] """ @prim_attr_register def __init__(self): """Initialize ParallelConcat""" def __infer__(self, values): x_shp = values['shape'] x_type = values['dtype'] validator.check_int(len(x_shp), 1, Rel.GE, f'x_shp length', self.name) args = {f"x_type[{i}]": elem for i, elem in enumerate(x_type)} validator.check_tensors_dtypes_same_and_valid(args, mstype.number_type + (mstype.bool_,), self.name) first_elem = x_shp[0] for i, elem in enumerate(x_shp[1:]): j = i + 1 validator.check_equal_int(elem[0], 1, f'x_shp[{j}][0]', self.name) validator.check(f"x_shp[0] shape", first_elem, f"x_shp[{j}] shape", elem, Rel.EQ, self.name) ret_shp = x_shp[0].copy() ret_shp[0] = len(x_shp) self.add_prim_attr('shape', ret_shp) self.add_prim_attr('N', len(x_shp)) out = {'shape': ret_shp, 'dtype': x_type[0], 'value': None} return out def _get_stack_shape(x_shape, x_type, axis, prim_name): """for stack output shape""" validator.check_value_type("shape", x_shape, [tuple, list], prim_name) validator.check_int(len(x_shape), 1, Rel.GE, "len of input_x", prim_name) validator.check_subclass("input_x[0]", x_type[0], mstype.tensor, prim_name) rank_base = len(x_shape[0]) n = len(x_shape) out_shape = x_shape[0] validator.check_int_range(axis, -rank_base - 1, rank_base, Rel.INC_BOTH, 'axis', prim_name) if axis < 0: axis = axis + rank_base + 1 for i in range(1, n): validator.check('x_type[%d]' % i, x_type[i], 'base', x_type[0], Rel.EQ, prim_name, TypeError) if x_shape[i] != x_shape[0]: raise ValueError(f"For \'{prim_name}\' element {i} shape in input can not pack with first element") out_shape.insert(axis, n) return out_shape class Pack(PrimitiveWithInfer): """ Same as operator Stack. Pack will be deprecated in the future. Please use Stack instead. """ @deprecated("1.1", "Stack", True) @prim_attr_register def __init__(self, axis=0): """Initialize Pack""" validator.check_value_type("axis", axis, [int], self.name) self.axis = axis def __infer__(self, value): x_shape = value['shape'] x_type = value['dtype'] self.add_prim_attr('num', len(x_shape)) all_shape = _get_stack_shape(x_shape, x_type, self.axis, self.name) out = {'shape': all_shape, 'dtype': x_type[0], 'value': None} return out class Stack(PrimitiveWithInfer): r""" Stacks a list of tensors in specified axis. Stacks the list of input tensors with the same rank `R`, output is a tensor of rank `(R+1)`. Given input tensors of shape :math:`(x_1, x_2, ..., x_R)`. Set the number of input tensors as `N`. If :math:`0 \le axis`, the shape of the output tensor is :math:`(x_1, x_2, ..., x_{axis}, N, x_{axis+1}, ..., x_R)`. Args: axis (int): Dimension to stack. Default: 0. Negative values wrap around. The range is [-(R+1), R+1). Inputs: - **input_x** (Union[tuple, list]) - A Tuple or list of Tensor objects with the same shape and type. Outputs: Tensor. A stacked Tensor with the same type as `input_x`. Raises: TypeError: If the data types of elements in `input_x` are not the same. ValueError: If the length of `input_x` is not greater than 1; or if axis is out of the range [-(R+1), R+1); or if the shapes of elements in input_x are not the same. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> data1 = Tensor(np.array([0, 1]).astype(np.float32)) >>> data2 = Tensor(np.array([2, 3]).astype(np.float32)) >>> stack = ops.Stack() >>> output = stack([data1, data2]) >>> print(output) [[0. 1.] [2. 3.]] """ @prim_attr_register def __init__(self, axis=0): """Initialize Stack""" validator.check_value_type("axis", axis, [int], self.name) self.axis = axis def __infer__(self, value): x_shape = value['shape'] x_type = value['dtype'] self.add_prim_attr('num', len(x_shape)) all_shape = _get_stack_shape(x_shape, x_type, self.axis, self.name) tuple_value = value['value'] input_array = [] infered_value = None if tuple_value is not None: for item in tuple_value: npy_item = item.asnumpy() input_array.append(npy_item) infered_value = Tensor(np.stack(input_array, axis=self.axis)) out = {'shape': all_shape, 'dtype': x_type[0], 'value': infered_value} return out class Unpack(PrimitiveWithInfer): """ Same as operator Unstack. Unpack will be deprecated in the future. Please use Unstack instead. """ @deprecated("1.1", "Unstack", True) @prim_attr_register def __init__(self, axis=0): """Initialize Unpack""" validator.check_value_type("axis", axis, [int], self.name) self.axis = axis def __infer__(self, x): validator.check_subclass("x", x['dtype'], mstype.tensor, self.name) x_shape = list(x['shape']) dim = len(x_shape) validator.check_int_range(self.axis, -dim, dim, Rel.INC_LEFT, 'axis value', self.name) if self.axis < 0: self.axis = self.axis + dim output_num = x_shape[self.axis] validator.check_value_type("num", output_num, [int], self.name) validator.check_positive_int(output_num, "output_num", self.name) self.add_prim_attr('num', output_num) output_valid_check = x_shape[self.axis] - output_num validator.check_int(output_valid_check, 0, Rel.EQ, "The dimension which to unstack divides output_num", self.name) out_shapes = [] out_dtypes = [] out_shape = x_shape[:self.axis] + x_shape[self.axis + 1:] for _ in range(output_num): out_shapes.append(tuple(out_shape)) out_dtypes.append(x['dtype']) out_shapes = tuple(out_shapes) out_dtypes = tuple(out_dtypes) out = {'shape': out_shapes, 'dtype': out_dtypes, 'value': None} return out class Unstack(PrimitiveWithInfer): r""" Unstacks tensor in specified axis. Unstacks a tensor of rank `R` along axis dimension, output tensors will have rank `(R-1)`. Given a tensor of shape :math:`(x_1, x_2, ..., x_R)`. If :math:`0 \le axis`, the shape of tensor in output is :math:`(x_1, x_2, ..., x_{axis}, x_{axis+2}, ..., x_R)`. This is the opposite of pack. Args: axis (int): Dimension along which to pack. Default: 0. Negative values wrap around. The range is [-R, R). Inputs: - **input_x** (Tensor) - The shape is :math:`(x_1, x_2, ..., x_R)`. A tensor to be unstacked and the rank of the tensor must be greater than 0. Outputs: A tuple of tensors, the shape of each objects is the same. Raises: ValueError: If axis is out of the range [-len(input_x.shape), len(input_x.shape)). Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> unstack = ops.Unstack() >>> input_x = Tensor(np.array([[1, 1, 1, 1], [2, 2, 2, 2]])) >>> output = unstack(input_x) >>> print(output) (Tensor(shape=[4], dtype=Int64, value= [1, 1, 1, 1]), Tensor(shape=[4], dtype=Int64, value= [2, 2, 2, 2])) """ @prim_attr_register def __init__(self, axis=0): """Initialize Unstack""" validator.check_value_type("axis", axis, [int], self.name) self.axis = axis def __infer__(self, x): validator.check_subclass("x", x['dtype'], mstype.tensor, self.name) x_shape = list(x['shape']) dim = len(x_shape) validator.check_int_range(self.axis, -dim, dim, Rel.INC_LEFT, 'axis value', self.name) if self.axis < 0: self.axis = self.axis + dim output_num = x_shape[self.axis] validator.check_value_type("num", output_num, [int], self.name) validator.check_positive_int(output_num, "output_num", self.name) self.add_prim_attr('num', output_num) output_valid_check = x_shape[self.axis] - output_num validator.check_int(output_valid_check, 0, Rel.EQ, "The dimension which to unstack divides output_num", self.name) out_shapes = [] out_dtypes = [] out_shape = x_shape[:self.axis] + x_shape[self.axis + 1:] for _ in range(output_num): out_shapes.append(tuple(out_shape)) out_dtypes.append(x['dtype']) out_shapes = tuple(out_shapes) out_dtypes = tuple(out_dtypes) out = {'shape': out_shapes, 'dtype': out_dtypes, 'value': None} return out class Slice(PrimitiveWithInfer): """ Slices a tensor in the specified shape. Slice the tensor `input_x` in shape of `size` and starting at the location specified by `begin`, The slice `begin` represents the offset in each dimension of `input_x`, The slice `size` represents the size of the output tensor. Note that `begin` is zero-based and `size` is one-based. If `size[i]` is -1, all remaining elements in dimension i are included in the slice. This is equivalent to setting :math:`size[i] = input_x.shape(i) - begin[i]`. Inputs: - **input_x** (Tensor): The target tensor. The shape is :math:`(N,*)` where :math:`*` means, any number of additional dimensions. - **begin** (Union[tuple, list]): The beginning of the slice. Only constant value(>=0) is allowed. - **size** (Union[tuple, list]): The size of the slice. Only constant value is allowed. Outputs: Tensor, the shape is : input `size`, the data type is the same as `input_x`. Raises: TypeError: If `begin` or `size` is neither tuple nor list. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> data = Tensor(np.array([[[1, 1, 1], [2, 2, 2]], ... [[3, 3, 3], [4, 4, 4]], ... [[5, 5, 5], [6, 6, 6]]]).astype(np.int32)) >>> slice_op = ops.Slice() >>> output = slice_op(data, (1, 0, 0), (1, 1, 3)) >>> print(output) [[[3 3 3]]] >>> output = slice_op(data, (1, 0, 0), (1, 1, 2)) >>> print(output) [[[3 3]]] >>> output = slice_op(data, (1, 0, 0), (1, 1, 1)) >>> print(output) [[[3]]] >>> output = slice_op(data, (1, 1, 0), (1, 1, 3)) >>> print(output) [[[4 4 4]]] >>> output = slice_op(data, (1, 0, 1), (1, 1, 2)) >>> print(output) [[[3 3]]] """ @prim_attr_register def __init__(self): """Initialize slice""" self.init_prim_io_names(inputs=['x', 'begin', 'size'], outputs=['output']) def __infer__(self, x, begin, size): x_shape = x['shape'] x_shp_len = len(x_shape) begin_v, size_v = begin['value'], size['value'] if begin_v is None or size_v is None: # if size_v is not None and begin_v is None, it should be also a dynamic output shape. if size_v is None: if size['shape'][0] < 0: raise ValueError(f"For '{self.name}', the size shape haven't support dynamic yet.") out_shape = [-1] * size['shape'][0] else: out_shape = [-1] * len(size_v) if 'max_shape' in x: max_shape = x['max_shape'] min_shape = x['min_shape'] else: min_shape = x['shape'] max_shape = x['shape'] return {'shape': out_shape, 'dtype': x['dtype'], 'value': None, 'min_shape': min_shape, 'max_shape': max_shape} validator.check_valid_input('begin', begin['value'], self.name) validator.check_valid_input('size', size['value'], self.name) validator.check_value_type("input begin", begin_v, [tuple, list], self.name) validator.check_value_type("input size", size_v, [tuple, list], self.name) for key, value in zip(('begin', 'size'), (begin_v, size_v)): validator.check(f'len of {key}', len(value), 'len x\'s dim', x_shp_len) size_v = list(size_v) if -1 not in x_shape: for i in range(x_shp_len): if size_v[i] == -1: size_v[i] = x_shape[i] - begin_v[i] validator.check_positive_int(size_v[i], f'input size[{i}]') validator.check_non_negative_int(begin_v[i], f'input begin[{i}]') if x_shape[i] < begin_v[i] + size_v[i]: y = begin_v[i] + size_v[i] raise ValueError(f"For '{self.name}', the sliced shape can not be greater than origin shape, " f"but got sliced shape is {y}, and origin shape is {x_shape}.") return {'shape': size_v, 'dtype': x['dtype'], 'value': None} class ReverseV2(PrimitiveWithInfer): """ Reverses specific dimensions of a tensor. .. warning:: The value range of "axis" is [-dims, dims - 1]. "dims" is the dimension length of "input_x". Args: axis (Union[tuple(int), list(int)): The indices of the dimensions to reverse. Inputs: - **input_x** (Tensor) - The target tensor. The data type is Number except float64. The shape is :math:`(N,*)` where :math:`*` means, any number of additional dimensions. Outputs: Tensor, has the same shape and type as `input_x`. Raises: TypeError: If `axis` is neither list nor tuple. TypeError: If element of `axis` is not an int. Supported Platforms: ``Ascend`` ``GPU`` Examples: >>> input_x = Tensor(np.array([[1, 2, 3, 4], [5, 6, 7, 8]]), mindspore.int32) >>> op = ops.ReverseV2(axis=[1]) >>> output = op(input_x) >>> print(output) [[4 3 2 1] [8 7 6 5]] >>> op = ops.ReverseV2(axis=[1, 0]) >>> output = op(input_x) >>> print(output) [[8 7 6 5] [4 3 2 1]] """ @prim_attr_register def __init__(self, axis): """Initialize ReverseV2.""" validator.check_value_type('axis', axis, [list, tuple], self.name) for i, each in enumerate(axis): validator.check_value_type(f'axis[{i}]', each, [int], self.name) self.axis = axis self.init_prim_io_names(inputs=['x'], outputs=['output']) def infer_shape(self, x_shape): dim = len(x_shape) for i, each in enumerate(self.axis): validator.check_int_range(each, -dim, dim, Rel.INC_LEFT, f'axis[{i}]', self.name) normalized_axis = [] for i, v in enumerate(self.axis): if v < 0: normalized_axis.append(v + dim) else: normalized_axis.append(v) if len(normalized_axis) != len(set(normalized_axis)): duplicated = [item for item, count in Counter(normalized_axis).items() if count > 1] raise ValueError(f"For '{self.name}', the 'axis' cannot contain duplicate dimensions," f" but got duplicated elements {duplicated}.") return x_shape def infer_dtype(self, x_dtype): validator.check_tensor_dtype_valid('x', x_dtype, (mstype.bool_,) + mstype.number_type, self.name) return x_dtype class Rint(Primitive): """ Returns an integer that is closest to x element-wise. Inputs: - **input_x** (Tensor) - The target tensor, which must be one of the following types: float16, float32. The shape is :math:`(N,*)` where :math:`*` means, any number of additional dimensions. Outputs: Tensor, has the same shape and type as `input_x`. Raises: TypeError: If dtype of `input_x` is not in [float16, float32, float64]. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Tensor(np.array([-1.6, -0.1, 1.5, 2.0]), mindspore.float32) >>> op = ops.Rint() >>> output = op(input_x) >>> print(output) [-2. 0. 2. 2.] >>> input_x = Tensor(np.array([[-2.0, -1.9, -1.8, -1.7, -1.6], ... [-2.0, -1.9, -1.8, -1.7, -1.6]]), mindspore.float32) >>> output = op(input_x) >>> print(output) [[-2. -2. -2. -2. -2.] [-2. -2. -2. -2. -2.]] """ @prim_attr_register def __init__(self): """Initialize Rint.""" self.init_prim_io_names(inputs=['x'], outputs=['output']) class Select(Primitive): r""" Returns the selected elements, either from input :math:`x` or input :math:`y`, depending on the `condition`. Given a tensor as input, this operation inserts a dimension of 1 at the dimension, it was invalid when both math: 'x' and math: 'y' are none. Keep in mind that the shape of the output tensor can vary depending on how many true values are in the input. Indexes are output in row-first order. The conditional tensor acts as an optional compensation (mask), which determines whether the corresponding element / row in the output must be selected from :math:`x` (if true) or :math:`y` (if false) based on the value of each element. It can be defined as: .. math:: out_i = \begin{cases} x_i, & \text{if } condition_i \\ y_i, & \text{otherwise} \end{cases} If condition is a vector, then :math:`x` and :math:`y` are higher-dimensional matrices, then it chooses to copy that row (external dimensions) from :math:`x` and :math:`y`. If condition has the same shape as :math:`x` and :math:`y`, you can choose to copy these elements from :math:`x` and :math:`y`. Inputs: - **input_cond** (Tensor[bool]) - The shape is :math:`(x_1, x_2, ..., x_N, ..., x_R)`. The condition tensor, decides which element is chosen. - **input_x** (Tensor) - The shape is :math:`(x_1, x_2, ..., x_N, ..., x_R)`. The first input tensor. - **input_y** (Tensor) - The shape is :math:`(x_1, x_2, ..., x_N, ..., x_R)`. The second input tensor. Outputs: Tensor, has the same shape as `input_x`. The shape is :math:`(x_1, x_2, ..., x_N, ..., x_R)`. Raises: TypeError: If `input_x` or `input_y` is not a Tensor. ValueError: If shape of `input_x` is not equal to shape of `input_y` or shape of `input_cond`. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> select = ops.Select() >>> input_cond = Tensor([True, False]) >>> input_x = Tensor([2,3], mindspore.float32) >>> input_y = Tensor([1,2], mindspore.float32) >>> output = select(input_cond, input_x, input_y) >>> print(output) [2. 2.] """ @prim_attr_register def __init__(self): """Initialize Select.""" self.init_prim_io_names(inputs=['condition', 'x', 'y'], outputs=['output']) def _compute_slicing_length(begin, end, stride, x_shape, i): """Computes the length of the slicing.""" if i >= len(x_shape): raise ValueError(f"For 'StridedSlice', the index must be less than " f"the dimension of 'input_x', but got the dimension of 'input_x': {len(x_shape)} " f"and the index: {i}.") x_dim = x_shape[i] if stride > 0: # When slicing forward, convert begin and end to positive numbers. if begin >= x_dim or end < -x_dim: # When slicing forward, if begin >= x_dim or end < -x_dim, the length of the slicing is 0. slicing_length = 0 else: if -x_dim <= begin < 0: begin += x_dim if begin < -x_dim: # When slicing forward, if begin < -x_dim, set begin = 0, which means start from the 0th element. begin = 0 if -x_dim <= end < 0: end += x_dim if end > x_dim: # When slicing forward, if end > x_dim, set end = x_dims, which means slice to the last element. end = x_dim if begin >= end: # When slicing forward, if begin >= end, the length of the slicing is 0. slicing_length = 0 else: slicing_length = 1 + (end - 1 - begin) // stride else: # When slicing backward, convert begin and end to negative numbers. if begin < -x_dim or end >= x_dim: # When slicing backward, if begin < -x_dim or end >= x_dim, the length of the slicing is 0. slicing_length = 0 else: if 0 <= begin < x_dim: begin += -x_dim if begin >= x_dim: begin = -1 if 0 <= end < x_dim: end += -x_dim if end < -x_dim - 1: # Slicing to the 0th element. end = -x_dim - 1 if begin <= end: slicing_length = 0 else: slicing_length = 1 + (end + 1 - begin) // stride return slicing_length class StridedSlice(PrimitiveWithInfer): r""" Extracts a strided slice of a tensor. Given an input tensor, this operation inserts a dimension of length 1 at the dimension. This operation extracts a fragment of size (end-begin)/stride from the given 'input_tensor'. Starting from the beginning position, the fragment continues adding stride to the index until all dimensions are not less than the ending position. Given a `input_x[m1, m2, ..., mn]`, `begin`, `end` and `strides` will be vectors of length n. In each mask field (`begin_mask`, `end_mask`, `ellipsis_mask`, `new_axis_mask`, `shrink_axis_mask`) the ith bit will correspond to the ith m. If the ith bit of `begin_mask` is set, `begin[i]` is ignored and the fullest possible range in that dimension is used instead. `end_mask` is analogous, except with the end range. As for a 5*6*7 tensor, `x[2:,:3,:]` is equivalent to `x[2:5,0:3,0:7]`. If the ith bit of `ellipsis_mask` is set, as many unspecified dimensions as needed will be inserted between other dimensions. Only one non-zero bit is allowed in `ellipsis_mask`. As for a 5*6*7*8 tensor, `x[2:,...,:6]` is equivalent to `x[2:5,:,:,0:6]`. `x[2:,...]` is equivalent to `x[2:5,:,:,:]`. If the ith bit of `new_axis_mask` is set, `begin`, `end` and `strides` are ignored and a new length 1 dimension is added at the specified position in tthe output tensor. As for a 5*6*7 tensor, `x[:2, newaxis, :6]` will produce a tensor with shape (2, 1, 7). If the ith bit of `shrink_axis_mask` is set, ith size shrinks the dimension by 1, taking on the value at index `begin[i]`, `end[i]` and `strides[i]` are ignored. As for a 5*6*7 tensor, `x[:, 5, :]` will result in `shrink_axis_mask` equal to 4. Note: The stride may be negative value, which causes reverse slicing. The shape of `begin`, `end` and `strides` must be the same. `begin` and `end` are zero-indexed. The element of `strides` must be non-zero. Args: begin_mask (int): Starting index of the slice. Default: 0. end_mask (int): Ending index of the slice. Default: 0. ellipsis_mask (int): An int mask. Default: 0. new_axis_mask (int): An int mask. Default: 0. shrink_axis_mask (int): An int mask. Default: 0. Inputs: - **input_x** (Tensor) - The input Tensor. - **begin** (tuple[int]) - A tuple which represents the location where to start. Only constant value is allowed. - **end** (tuple[int]) - A tuple or which represents the maximum location where to end. Only constant value is allowed. - **strides** (tuple[int]) - A tuple which represents the stride is continuously added before reaching the maximum location. Only constant value is allowed. Outputs: Tensor, The output is explained by following example. In the 0th dimension, begin is 1, end is 2, and strides is 1, because :math:`1+1=2\geq2`, the interval is :math:`[1,2)`. Thus, return the element with :math:`index = 1` in 0th dimension, i.e., [[3, 3, 3], [4, 4, 4]]. In the 1st dimension, similarly, the interval is :math:`[0,1)`. Based on the return value of the 0th dimension, return the element with :math:`index = 0`, i.e., [3, 3, 3]. In the 2nd dimension, similarly, the interval is :math:`[0,3)`. Based on the return value of the 1st dimension, return the element with :math:`index = 0,1,2`, i.e., [3, 3, 3]. Finally, the output is [3, 3, 3]. Raises: TypeError: If `begin_mask`, `end_mask`, `ellipsis_mask`, `new_axis_mask` or `shrink_axis_mask` is not an int. TypeError: If `begin`, `end` or `strides` is not a tuple. ValueError: If `begin_mask`, `end_mask`, `ellipsis_mask`, `new_axis_mask` or `shrink_axis_mask` is less than 0. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Tensor([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]], ... [[5, 5, 5], [6, 6, 6]]], mindspore.float32) >>> # [[[1. 1. 1.] >>> # [2. 2. 2.]] >>> # >>> # [[3. 3. 3.] >>> # [4. 4. 4.]] >>> # >>> # [[5. 5. 5.] >>> # [6. 6. 6.]]] >>> # In order to visually view the multi-dimensional array, write the above as follows: >>> # [ >>> # [ >>> # [1,1,1] >>> # [2,2,2] >>> # ] >>> # [ >>> # [3,3,3] >>> # [4,4,4] >>> # ] >>> # [ >>> # [5,5,5] >>> # [6,6,6] >>> # ] >>> # ] >>> strided_slice = ops.StridedSlice() >>> output = strided_slice(input_x, (1, 0, 2), (3, 1, 3), (1, 1, 1)) >>> # Take this " output = strided_slice(input_x, (1, 0, 2), (3, 1, 3), (1, 1, 1)) " as an example, >>> # start = [1, 0, 2] , end = [3, 1, 3], stride = [1, 1, 1], Find a segment of (start, end), >>> # note that end is an open interval >>> # To facilitate understanding, this operator can be divided into three steps: >>> # Step 1: Calculation of the first dimension: >>> # start = 1, end = 3, stride = 1, So can take 1st, 2nd rows, and then gets the final output at this time. >>> # output_1th = >>> # [ >>> # [ >>> # [3,3,3] >>> # [4,4,4] >>> # ] >>> # [ >>> # [5,5,5] >>> # [6,6,6] >>> # ] >>> # ] >>> # Step 2: Calculation of the second dimension >>> # 2nd dimension, start = 0, end = 1, stride = 1. So only 0th rows can be taken, and the output at this time. >>> # output_2nd = >>> # [ >>> # [ >>> # [3,3,3] >>> # ] >>> # [ >>> # [5,5,5] >>> # ] >>> # ] >>> # Step 3: Calculation of the third dimension >>> # 3nd dimension,start = 2, end = 3, stride = 1, So can take 2th cols, >>> # and you get the final output at this time. >>> # output_3ed = >>> # [ >>> # [ >>> # [3] >>> # ] >>> # [ >>> # [5] >>> # ] >>> # ] >>> # The final output after finishing is: >>> print(output) [[[3.]] [[5.]]] >>> # another example like : >>> output = strided_slice(input_x, (1, 0, 0), (2, 1, 3), (1, 1, 1)) >>> print(output) [[[3. 3. 3.]]] """ @prim_attr_register def __init__(self, begin_mask=0, end_mask=0, ellipsis_mask=0, new_axis_mask=0, shrink_axis_mask=0): """Initialize StridedSlice""" self.init_prim_io_names(inputs=['x', 'begin', 'end', 'strides'], outputs=['output']) validator.check_non_negative_int(begin_mask, 'begin_mask', self.name) validator.check_non_negative_int(end_mask, 'end_mask', self.name) validator.check_non_negative_int(ellipsis_mask, 'ellipsis_mask', self.name) if len(tuple(filter(lambda x: x == '1', bin(ellipsis_mask)[-1:1:-1]))) > 1: raise ValueError(f"For '{self.name}', only support one ellipsis in the index, but got {end_mask}.") validator.check_non_negative_int(new_axis_mask, 'new_axis_mask', self.name) validator.check_non_negative_int(shrink_axis_mask, 'shrink_axis_mask', self.name) def _check_and_get_value(self, slice_input, name): """Check begin, end, strides. Get its length and value.""" slice_value = slice_input['value'] if slice_value is None: validator.check_tensor_dtype_valid(name, slice_input['dtype'], [mstype.int64], self.name) slice_shape = slice_input['shape'] if len(slice_shape) != 1: raise ValueError(f"For '{self.name}', both the 'begins', 'ends', and 'strides' must be 1-D, " f"but got '{name}' shape: {slice_shape}.") # not support scalar return slice_value, slice_shape[0] if isinstance(slice_value, Tensor_): validator.check_tensor_dtype_valid(name, slice_input['dtype'], [mstype.int64], self.name) slice_value = slice_value.asnumpy().tolist() elif not isinstance(slice_value, tuple): raise TypeError(f"For '{self.name}', both the 'begin', 'end', and 'strides' must be a tuple or Tensor, " f"but got '{name}': {slice_value}.") if tuple(filter(lambda x: not isinstance(x, int), slice_value)): raise TypeError(f"For '{self.name}', the elements of 'begin', 'end', and 'strides' must be int, " f"but got {name}: {slice_value}.") return slice_value, len(slice_value) def __infer__(self, x, begin, end, strides): x_shape = x['shape'] if -1 in x_shape: raise ValueError(f"For '{self.name}', input x is currently not support dynamic shape.") begin_v, begin_len = self._check_and_get_value(begin, 'begin') end_v, end_len = self._check_and_get_value(end, 'end') strides_v, strides_len = self._check_and_get_value(strides, 'strides') if strides_v is not None and tuple(filter(lambda x: x == 0, strides_v)): raise ValueError(f"For '{self.name}', the 'strides' cannot contain 0, but got 'strides': {strides_v}.") if begin_len != strides_len or end_len != strides_len: raise ValueError(f"For '{self.name}', 'begin', 'end' and 'strides' must be the same length, but got " f"'begin' length: {begin_len}, 'end' length: {end_len}, 'strides' length: {strides_len}.") if None in (strides_v, begin_v, end_v): ret_shape = self._compute_dynamic_slicing_shape(x_shape, begin_len) ret_min_shape = [1] * len(x_shape) ret_max_shape = x_shape for i, val in enumerate(ret_shape): if val > 0: ret_min_shape[i] = val ret_max_shape[i] = val return {'shape': ret_shape, 'dtype': x['dtype'], 'value': None, 'max_shape': ret_max_shape, 'min_shape': ret_min_shape} ret_shape = self._compute_slicing_shape(x_shape, begin_v, end_v, strides_v) if all(ret_shape): value = None else: init_func = Zero() init_func.__enable_zero_dim__ = True value = Tensor(dtype=x['dtype'].element_type(), shape=ret_shape, init=init_func) if "max_value" in x and "min_value" in x: validator.check_value_type("min_value", x["min_value"], [tuple, list], self.name) validator.check_value_type("max_value", x["max_value"], [tuple, list], self.name) max_value_np = np.array(x["max_value"]) min_value_np = np.array(x["min_value"]) slice_index = [] for begin_i, end_i, strides_i in zip(begin_v, end_v, strides_v): s = slice(begin_i, end_i, strides_i) slice_index.append(s) slice_index = tuple(slice_index) max_value_slice = max_value_np[slice_index] min_value_slice = min_value_np[slice_index] max_value_slice = tuple(max_value_slice.tolist()) min_value_slice = tuple(min_value_slice.tolist()) return {'shape': ret_shape, 'dtype': x['dtype'], 'value': value, 'max_value': max_value_slice, 'min_value': min_value_slice} return {'shape': ret_shape, 'dtype': x['dtype'], 'value': value} def _compute_slicing_shape(self, x_shape, begin_v, end_v, strides_v): """Computes the shape of the slicing.""" x_rank = len(x_shape) slice_len = len(begin_v) # After the integer is converted to binary, it is a str and the first two chars are the flag char '0b'. begin_pos = bin(self.begin_mask)[-1:1:-1] end_pos = bin(self.end_mask)[-1:1:-1] ellipsis_pos = bin(self.ellipsis_mask)[-1:1:-1] new_axis_pos = bin(self.new_axis_mask)[-1:1:-1] shrink_axis_pos = bin(self.shrink_axis_mask)[-1:1:-1] ret_shape = [] i, j = 0, 0 has_ellipsis = False while i < x_rank or j < slice_len: if j < slice_len: begin, end, stride = begin_v[j], end_v[j], strides_v[j] if j < len(ellipsis_pos) and ellipsis_pos[j] == '1': # When there is ellipsis, the latter part of the ellipsis will be processed separately. has_ellipsis = True break if j < len(begin_pos) and begin_pos[j] == '1': begin = -1 if strides_v[j] < 0 else 0 if j < len(end_pos) and end_pos[j] == '1': end = -(x_shape[i] + 1) if strides_v[j] < 0 else x_shape[i] if j < len(new_axis_pos) and new_axis_pos[j] == '1': ret_shape.append(1) j += 1 continue if j < len(shrink_axis_pos) and shrink_axis_pos[j] == '1': if (not -x_shape[i] <= begin < x_shape[i]) or stride < 0: raise IndexError(f"For '{self.name}', the 'strides[{i}]' cannot be negative number and " f"'begin[{i}]' should be in [-{x_shape[i]}, {x_shape[i]}) " f"when 'shrink_axis_mask' is greater than 0, " f"but got 'shrink_axis_mask': {self.shrink_axis_mask}, " f"'strides[{i}]': {stride}, 'begin[{i}]': {begin}.") j += 1 i += 1 continue else: begin, end, stride = 0, x_shape[i], 1 slicing_length = _compute_slicing_length(begin, end, stride, x_shape, i) ret_shape.append(slicing_length) i += 1 j += 1 if has_ellipsis: # When there is ellipsis, handle the second half of the ellipsis split. ellipsis_occupied_dims = x_rank - i - (slice_len - (j + 1)) + \ len(tuple(filter(lambda x: x == '1', new_axis_pos[j + 1:slice_len]))) ret_shape.extend(x_shape[i:i + ellipsis_occupied_dims]) j += 1 i += ellipsis_occupied_dims while i < x_rank or j < slice_len: begin, end, stride = begin_v[j], end_v[j], strides_v[j] if j < len(begin_pos) and begin_pos[j] == '1': begin = -1 if strides_v[j] < 0 else 0 if j < len(end_pos) and end_pos[j] == '1': end = -(x_shape[i] + 1) if strides_v[j] < 0 else x_shape[i] if j < len(new_axis_pos) and new_axis_pos[j] == '1': ret_shape.append(1) j += 1 continue if j < len(shrink_axis_pos) and shrink_axis_pos[j] == '1': if (not -x_shape[i] <= begin < x_shape[i]) or stride < 0: raise IndexError(f"For '{self.name}', the 'strides[{i}]' cannot be negative number and " f"'begin[{i}]' should be in [-{x_shape[i]}, {x_shape[i]}) " f"when 'shrink_axis_mask' is greater than 0, " f"but got 'shrink_axis_mask': {self.shrink_axis_mask}, " f"'strides[{i}]': {stride}, 'begin[{i}]': {begin}.") j += 1 i += 1 continue slicing_length = _compute_slicing_length(begin, end, stride, x_shape, i) ret_shape.append(slicing_length) i += 1 j += 1 return ret_shape def _compute_dynamic_slicing_shape(self, x_shape, slice_len): """Computes the shape of the slicing for dynamic shape, mask is currently not supported.""" x_rank = len(x_shape) if self.begin_mask != 0 or self.end_mask != 0 or self.ellipsis_mask or self.new_axis_mask != 0 \ or self.shrink_axis_mask != 0: raise ValueError("Mask is currently not supported if 'begin', 'end' or 'strides' is not a constant.") ret_shape = [] i, j = 0, 0 while i < x_rank or j < slice_len: slicing_length = -1 if j >= slice_len: if i >= len(x_shape): raise ValueError(f"For 'StridedSlice', the index must be less than or equal to " f"the dimension of 'input_x', but got the dimension of 'input_x': {len(x_shape)} " f"and the index: {i}.") begin, end, stride = 0, x_shape[i], 1 if end > 0: slicing_length = _compute_slicing_length(begin, end, stride, x_shape, i) ret_shape.append(slicing_length) i += 1 j += 1 return ret_shape class Diag(PrimitiveWithInfer): r""" Constructs a diagonal tensor with a given diagonal values. Assume `input_x` has dimensions :math:`[D_1,... D_k]`, the output is a tensor of rank 2k with dimensions :math:`[D_1,..., D_k, D_1,..., D_k]` where: :math:`output[i_1,..., i_k, i_1,..., i_k] = input_x[i_1,..., i_k]` and 0 everywhere else. Inputs: - **input_x** (Tensor) - The input tensor. The input shape must be less than 5d. Outputs: Tensor, has the same dtype as the `input_x`. Raises: TypeError: If `input_x` is not a Tensor. ValueError: If rank of `input_x` is less than 1. Supported Platforms: ``Ascend`` Examples: >>> input_x = Tensor([1, 2, 3, 4]) >>> diag = ops.Diag() >>> output = diag(input_x) >>> print(output) [[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]] """ @prim_attr_register def __init__(self): """Initialize Diag""" def infer_dtype(self, x_type): validator.check_subclass('input_x', x_type, mstype.tensor, self.name) return x_type def infer_shape(self, x_shape): validator.check("x rank", len(x_shape), "", 1, Rel.GE) ret_shape = copy.deepcopy(x_shape) ret_shape = ret_shape + ret_shape return ret_shape def infer_value(self, x): if x is None: return None # do constant-folding only when x rank is 1 if len(x.shape) != 1: return None ret = np.diag(x.asnumpy()) return Tensor(ret) class DiagPart(PrimitiveWithInfer): r""" Extracts the diagonal part from given tensor. Assume input has dimensions :math:`[D_1,..., D_k, D_1,..., D_k]`, the output is a tensor of rank k with dimensions :math:`[D_1,..., D_k]` where: :math:`output[i_1,..., i_k] = input[i_1,..., i_k, i_1,..., i_k]`. Inputs: - **input_x** (Tensor) - The input tensor of rank 2k, k is not zero. Outputs: Tensor, the extracted diagonal has the same dtype as the `input_x`. Raises: TypeError: If `input_x` is not a Tensor. ValueError: If rank of `input_x` is not even or zero. ValueError: If input_shape[i] is not equal to input_shape[i + len(input_shape)/2]. Supported Platforms: ``Ascend`` Examples >>> input_x = Tensor([[1, 0, 0, 0], ... [0, 2, 0, 0], ... [0, 0, 3, 0], ... [0, 0, 0, 4]]) >>> diag_part = ops.DiagPart() >>> output = diag_part(input_x) >>> print(output) [1 2 3 4] """ @prim_attr_register def __init__(self): """Initialize DiagPart""" def infer_dtype(self, x_type): validator.check_subclass('input_x', x_type, mstype.tensor, self.name) return x_type def infer_shape(self, x_shape): if len(x_shape) % 2 != 0 or \ not x_shape: raise ValueError(f"For \'{self.name}\', the dimension of 'input_x' must be non-zero and even, " f"but got dimension {len(x_shape)}, with shapes {x_shape}.") length = len(x_shape) // 2 for i in range(length): validator.check('input_shape[i + len(input_shape)/2]', x_shape[i + length], 'input_shape[i]', x_shape[i], Rel.EQ, self.name) ret_shape = x_shape[0:length] return ret_shape def infer_value(self, x): if x is None: return None # do constant-folding only when x rank is 2 if len(x.shape) != 2: return None ret = np.diag(x.asnumpy()) return Tensor(ret) class Eye(PrimitiveWithInfer): """ Creates a tensor with ones on the diagonal and zeros in the rest. Inputs: - **n** (int) - The number of rows of returned tensor. Constant value only. - **m** (int) - The number of columns of returned tensor. Constant value only. - **t** (mindspore.dtype) - MindSpore's dtype, The data type of the returned tensor. The data type can be Number. Outputs: Tensor, a tensor with ones on the diagonal and the rest of elements are zero. The shape of `output` depends on the user's Inputs `n` and `m`. And the data type depends on Inputs `t`. Raises: TypeError: If `m` or `n` is not an int. ValueError: If `m` or `n` is less than 1. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> eye = ops.Eye() >>> output = eye(2, 2, mindspore.int32) >>> print(output) [[1 0] [0 1]] >>> print(output.dtype) Int32 >>> output = eye(1, 2, mindspore.float64) >>> print(output) [[1. 0.]] >>> print(output.dtype) Float64 >>> # if wants a anti-diagonal >>> anti_diagonal_input = eye(2, 2, mindspore.int32) >>> # Note that ReverseV2 only supports "Ascend" and "GPU" at this time >>> reverse = ops.ReverseV2([1]) >>> anti_diagonal_output = reverse(anti_diagonal_input) >>> print(anti_diagonal_output) [[0 1] [1 0]] """ @prim_attr_register def __init__(self): """Initialize Eye""" def infer_value(self, n, m, t): validator.check_positive_int(n, "n", self.name) validator.check_positive_int(m, "m", self.name) args = {"dtype": t} validator.check_types_same_and_valid(args, mstype.number_type + (mstype.bool_,), self.name) np_type = mstype.dtype_to_nptype(t) ret = np.eye(n, m, dtype=np_type) return Tensor(ret) class ScatterNd(PrimitiveWithInfer): r""" Scatters a tensor into a new tensor depending on the specified indices. Creates an empty tensor with the given `shape`, and set values by scattering the update tensor depending on indices. The empty tensor has rank P and `indices` has rank Q where `Q >= 2`. `indices` has shape :math:`(i_0, i_1, ..., i_{Q-2}, N)` where `N <= P`. The last dimension of `indices` (with length `N` ) indicates slices along the `N` th dimension of the empty tensor. `updates` is a tensor of rank `Q-1+P-N`. Its shape is: :math:`(i_0, i_1, ..., i_{Q-2}, shape_N, ..., shape_{P-1})`. The following figure shows the calculation process of inserting two slices in the first dimension of a rank-3 with two matrices of new values: .. image:: api_img/ScatterNd.png Inputs: - **indices** (Tensor) - The index of scattering in the new tensor with int32 or int64 data type. The rank of indices must be at least 2 and `indices_shape[-1] <= len(shape)`. - **updates** (Tensor) - The source Tensor to be scattered. It has shape `indices_shape[:-1] + shape[indices_shape[-1]:]`. - **shape** (tuple[int]) - Define the shape of the output tensor, has the same data type as indices. The shape of `shape` is :math:`(x_1, x_2, ..., x_R)`, and length of 'shape' is greater than or equal 2. In other words, the shape of `shape` is at least :math:`(x_1, x_2)`. And the value of any element in `shape` must be greater than or equal 1. In other words, :math:`x_1` >= 1, :math:`x_2` >= 1. Outputs: Tensor, the new tensor, has the same type as `update` and the same shape as `shape`. Raises: TypeError: If `shape` is not a tuple. ValueError: If any element of `shape` is less than 1. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> op = ops.ScatterNd() >>> indices = Tensor(np.array([[0], [2]]), mindspore.int32) >>> updates = Tensor(np.array([[[1, 1, 1, 1], [2, 2, 2, 2], ... [3, 3, 3, 3], [4, 4, 4, 4]], ... [[1, 1, 1, 1], [2, 2, 2, 2], ... [3, 3, 3, 3], [4, 4, 4, 4]]]), mindspore.float32) >>> shape = (4, 4, 4) >>> output = op(indices, updates, shape) >>> print(output) [[[1. 1. 1. 1.] [2. 2. 2. 2.] [3. 3. 3. 3.] [4. 4. 4. 4.]] [[0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]] [[1. 1. 1. 1.] [2. 2. 2. 2.] [3. 3. 3. 3.] [4. 4. 4. 4.]] [[0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]]] >>> indices = Tensor(np.array([[0, 1], [1, 1]]), mindspore.int32) >>> updates = Tensor(np.array([3.2, 1.1]), mindspore.float32) >>> shape = (3, 3) >>> output = op(indices, updates, shape) >>> # In order to facilitate understanding, explain the operator pseudo-operation process step by step: >>> # Step 1: Generate an empty Tensor of the specified shape according to the shape >>> # [ >>> # [0. 0. 0.] >>> # [0. 0. 0.] >>> # [0. 0. 0.] >>> # ] >>> # Step 2: Modify the data at the specified location according to the indicators >>> # 0th row of indices is [0, 1], 0th row of updates is 3.2. >>> # means that the empty tensor in the 0th row and 1st col set to 3.2 >>> # [ >>> # [0. 3.2. 0.] >>> # [0. 0. 0.] >>> # [0. 0. 0.] >>> # ] >>> # 1th row of indices is [1, 1], 1th row of updates is 1.1. >>> # means that the empty tensor in the 1th row and 1st col set to 1.1 >>> # [ >>> # [0. 3.2. 0.] >>> # [0. 1.1 0.] >>> # [0. 0. 0.] >>> # ] >>> # The final result is as follows: >>> print(output) [[0. 3.2 0.] [0. 1.1 0.] [0. 0. 0.]] """ @prim_attr_register def __init__(self): """Initialize ScatterNd""" self.init_prim_io_names(inputs=['indices', 'update', 'shape'], outputs=['output']) def __infer__(self, indices, update, shape): shp = shape['value'] validator.check_subclass("update_dtype", update['dtype'], mstype.tensor, self.name) validator.check_tensor_dtype_valid("indices", indices['dtype'], [mstype.int32, mstype.int64], self.name) validator.check_value_type("shape", shp, [tuple], self.name) for i, x in enumerate(shp): validator.check_positive_int(x, f'shape[{i}]', self.name) indices_shape, update_shape = indices["shape"], update["shape"] if indices_shape[0] != update_shape[0]: raise ValueError(f"For '{self.name}', the first shape of 'indices' must be the same as the first shape of " f"'updates', but got the first shape of 'indices': {indices_shape[0]}, " f"the first shape of 'updates': {update_shape[0]}.") return {'shape': shp, 'dtype': update['dtype'], 'value': None} class ResizeNearestNeighbor(Primitive): r""" Resizes the input tensor by using the nearest neighbor algorithm. Resizes the input tensor to a given size by using the nearest neighbor algorithm. The nearest neighbor algorithm selects the value of the nearest point and does not consider the values of neighboring points at all, yielding a piecewise-constant interpolant. Args: size (Union[tuple, list]): The target size. The dimension of size must be 2. align_corners (bool): Whether the centers of the 4 corner pixels of the input and output tensors are aligned. Default: False. Inputs: - **input_x** (Tensor) - The input tensor. The shape of the tensor is :math:`(N, C, H, W)`. Outputs: Tensor, the shape of the output tensor is :math:`(N, C, NEW\_H, NEW\_W)`. The data type is the same as the `input_x`. Raises: TypeError: If `size` is neither tuple nor list. TypeError: If `align_corners` is not a bool. ValueError: If length of `size` is not equal to 2. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_tensor = Tensor(np.array([[[[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]]]), mindspore.float32) >>> resize = ops.ResizeNearestNeighbor((2, 2)) >>> output = resize(input_tensor) >>> print(output) [[[[-0.1 0.3] [ 0.4 0.5]]]] """ @prim_attr_register def __init__(self, size, align_corners=False): """Initialize ResizeNearestNeighbor""" validator.check_value_type("size", size, [tuple, list], self.name) validator.check_value_type("align_corners", align_corners, [bool], self.name) validator.check_equal_int(len(size), 2, "length of size", self.name) for i, value in enumerate(size): validator.check_non_negative_int(value, f'{i}th value of size', self.name) self.init_prim_io_names(inputs=['image_in'], outputs=['image_out']) class GatherNd(Primitive): r""" Gathers slices from a tensor by indices. Using given indices to gather slices from a tensor with a specified shape. `indices` is an K-dimensional integer tensor. Supposes it as a (K-1)-dimensional tensor and each element of it defines a slice of `input_x`: .. math:: output[(i_0, ..., i_{K-2})] = input\_x[indices[(i_0, ..., i_{K-2})]] The last dimension of `indices` can not more than the rank of `input_x`: :math:`indices.shape[-1] <= input\_x.rank`. Inputs: - **input_x** (Tensor) - The target tensor to gather values. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. - **indices** (Tensor) - The index tensor, with int32 or int64 data type. Outputs: Tensor, has the same type as `input_x` and the shape is indices_shape[:-1] + x_shape[indices_shape[-1]:]. Raises: ValueError: If length of shape of `input_x` is less than the last dimension of `indices`. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> op = ops.GatherNd() >>> input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32) >>> indices = Tensor(np.array([[0, 0], [1, 1]]), mindspore.int32) >>> output = op(input_x, indices) >>> print(output) [-0.1 0.5] """ @prim_attr_register def __init__(self): """Initialize GatherNd""" self.init_prim_io_names(inputs=['input_x', 'indices'], outputs=['y']) class TensorScatterUpdate(PrimitiveWithInfer): """ Creates a new tensor by updating the positions in `input_x` indicated by `indices`, with values from `update`. This operation is almost equivalent to using ScatterNd, except that the updates are applied on `input_x` instead of a zero tensor. `indices` must have rank at least 2, the last axis is the depth of each index vectors. For each index vector, there must be a corresponding value in `update`. If the depth of each index tensor matches the rank of `input_x`, then each index vector corresponds to a scalar in `input_x` and each `update` updates a scalar. If the depth of each index tensor is less than the rank of `input_x`, then each index vector corresponds to a slice in `input_x`, and each `update` updates a slice. The order in which updates are applied is nondeterministic, meaning that if there are multiple index vectors in `indices` that correspond to the same position, the value of that position in the output will be nondeterministic. Inputs: - **input_x** (Tensor) - The target tensor. The dimension of input_x must be no less than indices.shape[-1]. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. The data type is Number. - **indices** (Tensor) - The index of input tensor whose data type is int32 or int64. The rank must be at least 2. - **update** (Tensor) - The tensor to update the input tensor, has the same type as input, and :math:`update.shape = indices.shape[:-1]+input_x.shape[indices.shape[-1]:]` Outputs: Tensor, has the same shape and type as `input_x`. Raises: TypeError: If dtype of `indices` is neither int32 nor int64. ValueError: If length of shape of `input_x` is less than the last dimension of shape of `indices`. ValueError: If the value of `input_x` are not match with input `indices`. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32) >>> indices = Tensor(np.array([[0, 0], [1, 1]]), mindspore.int32) >>> update = Tensor(np.array([1.0, 2.2]), mindspore.float32) >>> op = ops.TensorScatterUpdate() >>> output = op(input_x, indices, update) >>> print(output) [[ 1. 0.3 3.6] [ 0.4 2.2 -3.2]] """ @prim_attr_register def __init__(self): self.init_prim_io_names(inputs=['input_x', 'indices', 'updates'], outputs=['y']) def infer_shape(self, input_x_shape, indices_shape, updates_shape): if len(indices_shape) < 2: raise ValueError(f"For '{self.name}', the dimension of 'indices' cannot be less than 2," f" but got {len(indices_shape)}.") if indices_shape[-1] > len(input_x_shape): raise ValueError(f"For '{self.name}', the last dimension of 'indices' must be less than or equal to " f"the dimension of 'input_x', but got the " f"last dimension of 'indices': {indices_shape[-1]} and the dimension of 'input_x': " f"{len(input_x_shape)}.") updates_shape_check = indices_shape[:-1] + input_x_shape[indices_shape[-1]:] if updates_shape_check != updates_shape: raise ValueError(f"For '{self.name}', the shape of 'update' must be equal to updates_shape_check, " f"where updates_shape_check = indices_shape[:-1] + input_x_shape[indices_shape[-1]:] " f"but got the shape of 'update': {updates_shape}, " f"updates_shape_check: {updates_shape_check}, indices_shape: {indices_shape} and " f"input_x_shape: {input_x_shape}. Please check input_x_shape and indices_shape.") return input_x_shape def infer_dtype(self, input_x_dtype, indices_dtype, updates_dtype): validator.check_tensor_dtype_valid('indices', indices_dtype, [mstype.int32, mstype.int64], self.name) args = {"input_x": input_x_dtype, "updates": updates_dtype} validator.check_tensors_dtypes_same_and_valid(args, (mstype.bool_,) + mstype.number_type, self.name) return input_x_dtype class TensorScatterAdd(PrimitiveWithInfer): """ Creates a new tensor by adding the values from the positions in `input_x` indicated by `indices`, with values from `updates`. When multiple values are given for the same index, the updated result will be the sum of all values. This operation is almost equivalent to using ScatterNdAdd, except that the updates are applied on `Tensor` instead of `Parameter`. The last axis of `indices` is the depth of each index vectors. For each index vector, there must be a corresponding value in `updates`. The shape of `updates` should be equal to the shape of `input_x[indices]`. For more details, see use cases. Note: If some values of the `indices` are out of bound, instead of raising an index error, the corresponding `updates` will not be updated to `input_x`. Inputs: - **input_x** (Tensor) - The target tensor. The dimension of input_x must be no less than indices.shape[-1]. - **indices** (Tensor) - The index of input tensor whose data type is int32 or int64. The rank must be at least 2. - **updates** (Tensor) - The tensor to update the input tensor, has the same type as input, and updates.shape should be equal to indices.shape[:-1] + input_x.shape[indices.shape[-1]:]. Outputs: Tensor, has the same shape and type as `input_x`. Raises: TypeError: If dtype of `indices` is neither int32 nor int64. ValueError: If length of shape of `input_x` is less than the last dimension of shape of `indices`. Supported Platforms: ``GPU`` Examples: >>> input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32) >>> indices = Tensor(np.array([[0, 0], [0, 0]]), mindspore.int32) >>> updates = Tensor(np.array([1.0, 2.2]), mindspore.float32) >>> # Next, demonstrate the approximate operation process of this operator: >>> # 1, indices[0] = [0, 0], indices[1] = [0, 0] >>> # 2, And input_x[0, 0] = -0.1 >>> # 3, So input_x[indices] = [-0.1, -0.1] >>> # 4, Satisfy the above formula: input_x[indices].shape=(2) == updates.shape=(2) >>> op = ops.TensorScatterAdd() >>> # 5, Perform the addition operation for the first time: >>> # first_input_x = input_x[0][0] + updates[0] = [[0.9, 0.3, 3.6], [0.4, 0.5, -3.2]] >>> # 6, Perform the addition operation for the second time: >>> # second_input_x = input_x[0][0] + updates[1] = [[3.1, 0.3, 3.6], [0.4, 0.5, -3.2]] >>> output = op(input_x, indices, updates) >>> print(output) [[ 3.1 0.3 3.6] [ 0.4 0.5 -3.2]] """ @prim_attr_register def __init__(self): self.init_prim_io_names(inputs=['input_x', 'indices', 'updates'], outputs=['y']) def infer_shape(self, input_x_shape, indices_shape, updates_shape): if len(indices_shape) < 2: raise ValueError(f"For '{self.name}', the dimension of 'indices' cannot be less than 2," f" but got {len(indices_shape)}.") if indices_shape[-1] > len(input_x_shape): raise ValueError(f"For '{self.name}', the last dimension of 'indices' must be less than or equal to " f"the dimension of 'input_x', but got the " f"last dimension of 'indices': {indices_shape[-1]} and the dimension of 'input_x': " f"{len(input_x_shape)}.") updates_shape_check = indices_shape[:-1] + input_x_shape[indices_shape[-1]:] if updates_shape_check != updates_shape: raise ValueError(f"For '{self.name}', the shape of 'update' must be equal to updates_shape_check, " f"where updates_shape_check = indices_shape[:-1] + input_x_shape[indices_shape[-1]:] " f"but got the shape of 'update': {updates_shape}, " f"updates_shape_check: {updates_shape_check}, indices_shape: {indices_shape} and " f"input_x_shape: {input_x_shape}. Please check input_x_shape and indices_shape.") return input_x_shape def infer_dtype(self, input_x_dtype, indices_dtype, updates_dtype): validator.check_tensor_dtype_valid('indices', indices_dtype, [mstype.int32, mstype.int64], self.name) args = {"input_x": input_x_dtype, "updates": updates_dtype} validator.check_tensors_dtypes_same_and_valid(args, (mstype.bool_,) + mstype.number_type, self.name) return input_x_dtype class ScatterUpdate(_ScatterOpDynamic): r""" Updates tensor values by using input indices and value. Using given values to update tensor value, along with the input indices. for each `i, ..., j` in `indices.shape`: .. math:: \text{input_x}[\text{indices}[i, ..., j], :] = \text{updates}[i, ..., j, :] Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent. If they have different data types, the lower priority data type will be converted to the relatively highest priority data type. Args: use_locking (bool): Whether protect the assignment by a lock. Default: True. Inputs: - **input_x** (Parameter) - The target tensor, with data type of Parameter. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. - **indices** (Tensor) - The index of input tensor. With int32 data type. If there are duplicates in indices, the order for updating is undefined. - **updates** (Tensor) - The tensor to update the input tensor, has the same type as input, and updates.shape = indices.shape + input_x.shape[1:]. Outputs: Tensor, has the same shape and type as `input_x`. Raises: TypeError: If `use_locking` is not a bool. TypeError: If `indices` is not an int32. RuntimeError: If the data type of `input_x` and `updates` conversion of Parameter is required when data type conversion of Parameter is not supported. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> np_x = np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]) >>> input_x = mindspore.Parameter(Tensor(np_x, mindspore.float32), name="x") >>> indices = Tensor(np.array([0, 1]), mindspore.int32) >>> np_updates = np.array([[2.0, 1.2, 1.0], [3.0, 1.2, 1.0]]) >>> updates = Tensor(np_updates, mindspore.float32) >>> op = ops.ScatterUpdate() >>> output = op(input_x, indices, updates) >>> print(output) [[2. 1.2 1.] [3. 1.2 1.]] """ @prim_attr_register def __init__(self, use_locking=True): """Initialize ScatterUpdate""" validator.check_value_type('use_locking', use_locking, [bool], self.name) self.init_prim_io_names(inputs=['x', 'indices', 'updates'], outputs=['y']) self.add_prim_attr('side_effect_mem', True) class ScatterNdUpdate(Primitive): r""" Updates tensor values by using input indices and value. Using given values to update tensor value, along with the input indices. `input_x` has rank P and `indices` has rank Q where `Q >= 2`. `indices` has shape :math:`(i_0, i_1, ..., i_{Q-2}, N)` where `N <= P`. The last dimension of `indices` (with length `N` ) indicates slices along the `N` th dimension of `input_x`. `updates` is a tensor of rank `Q-1+P-N`. Its shape is: :math:`(i_0, i_1, ..., i_{Q-2}, x\_shape_N, ..., x\_shape_{P-1})`. Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent. If they have different data types, the lower priority data type will be converted to the relatively highest priority data type. Args: use_locking (bool): Whether protect the assignment by a lock. Default: True. Inputs: - **input_x** (Parameter) - The target tensor, with data type of Parameter. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. - **indices** (Tensor) - The index of input tensor, with int32 data type. - **updates** (Tensor) - The tensor to be updated to the input tensor, has the same type as input. The shape is `indices_shape[:-1] + x_shape[indices_shape[-1]:]`. Outputs: Tensor, has the same shape and type as `input_x`. Raises: TypeError: If `use_locking` is not a bool. TypeError: If `indices` is not an int32. RuntimeError: If the data type of `input_x` and `updates` conversion of Parameter is required when data type conversion of Parameter is not supported. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> np_x = np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]) >>> input_x = mindspore.Parameter(Tensor(np_x, mindspore.float32), name="x") >>> indices = Tensor(np.array([[0, 0], [1, 1]]), mindspore.int32) >>> updates = Tensor(np.array([1.0, 2.2]), mindspore.float32) >>> op = ops.ScatterNdUpdate() >>> output = op(input_x, indices, updates) >>> print(output) [[1. 0.3 3.6] [0.4 2.2 -3.2]] """ __mindspore_signature__ = ( sig.make_sig('input_x', sig.sig_rw.RW_WRITE, dtype=sig.sig_dtype.T), sig.make_sig('indices', dtype=sig.sig_dtype.T1), sig.make_sig('updates', dtype=sig.sig_dtype.T) ) @prim_attr_register def __init__(self, use_locking=True): """Initialize ScatterNdUpdate""" validator.check_value_type('use_locking', use_locking, [bool], self.name) self.init_prim_io_names(inputs=['input_x', 'indices', 'value'], outputs=['y']) self.add_prim_attr('side_effect_mem', True) class ScatterMax(_ScatterOp): r""" Updates the value of the input tensor through the maximum operation. Using given values to update tensor value through the max operation, along with the input indices. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value. for each `i, ..., j` in `indices.shape`: .. math:: \text{input_x}[\text{indices}[i, ..., j], :] = max(\text{input_x}[\text{indices}[i, ..., j], :], \text{updates}[i, ..., j, :]) Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent. If they have different data types, the lower priority data type will be converted to the relatively highest priority data type. Args: use_locking (bool): Whether protect the assignment by a lock. Default: True. Inputs: - **input_x** (Parameter) - The target tensor, with data type of Parameter. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. - **indices** (Tensor) - The index to do max operation whose data type must be mindspore.int32. - **updates** (Tensor) - The tensor that performs the maximum operation with `input_x`, the data type is the same as `input_x`, the shape is `indices_shape + x_shape[1:]`. Outputs: Tensor, the updated `input_x`, has the same shape and type as `input_x`. Raises: TypeError: If `use_locking` is not a bool. TypeError: If `indices` is not an int32. ValueError: If the shape of `updates` is not equal to `indices_shape + x_shape[1:]`. RuntimeError: If the data type of `input_x` and `updates` conversion of Parameter is required when data type conversion of Parameter is not supported. Supported Platforms: ``Ascend`` ``CPU`` Examples: >>> input_x = Parameter(Tensor(np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]), mindspore.float32), ... name="input_x") >>> indices = Tensor(np.array([[0, 0], [1, 1]]), mindspore.int32) >>> updates = Tensor(np.ones([2, 2, 3]) * 88, mindspore.float32) >>> scatter_max = ops.ScatterMax() >>> output = scatter_max(input_x, indices, updates) >>> print(output) [[88. 88. 88.] [88. 88. 88.]] """ class ScatterMin(_ScatterOp): r""" Updates the value of the input tensor through the minimum operation. Using given values to update tensor value through the min operation, along with the input indices. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value. for each `i, ..., j` in `indices.shape`: .. math:: \text{input_x}[\text{indices}[i, ..., j], :] = min(\text{input_x}[\text{indices}[i, ..., j], :], \text{updates}[i, ..., j, :]) Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent. If they have different data types, the lower priority data type will be converted to the relatively highest priority data type. Args: use_locking (bool): Whether protect the assignment by a lock. Default: False. Inputs: - **input_x** (Parameter) - The target tensor, with data type of Parameter. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. - **indices** (Tensor) - The index to do min operation whose data type must be mindspore.int32. - **updates** (Tensor) - The tensor doing the min operation with `input_x`, the data type is same as `input_x`, the shape is `indices_shape + x_shape[1:]`. Outputs: Tensor, the updated `input_x`, has the same shape and type as `input_x`. Raises: TypeError: If `use_locking` is not a bool. TypeError: If `indices` is not an int32. ValueError: If the shape of `updates` is not equal to `indices_shape + x_shape[1:]`. RuntimeError: If the data type of `input_x` and `updates` conversion of Parameter is required when data type conversion of Parameter is not supported. Supported Platforms: ``Ascend`` ``CPU`` Examples: >>> input_x = Parameter(Tensor(np.array([[0.0, 1.0, 2.0], [0.0, 0.0, 0.0]]), mindspore.float32), ... name="input_x") >>> indices = Tensor(np.array([[0, 0], [1, 1]]), mindspore.int32) >>> update = Tensor(np.ones([2, 2, 3]), mindspore.float32) >>> scatter_min = ops.ScatterMin() >>> output = scatter_min(input_x, indices, update) >>> print(output) [[0. 1. 1.] [0. 0. 0.]] """ class ScatterAdd(_ScatterOpDynamic): r""" Updates the value of the input tensor through the addition operation. Using given values to update tensor value through the add operation, along with the input indices. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value. for each `i, ..., j` in `indices.shape`: .. math:: \text{input_x}[\text{indices}[i, ..., j], :] \mathrel{+}= \text{updates}[i, ..., j, :] Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent. If they have different data types, the lower priority data type will be converted to the relatively highest priority data type. Note: This is an in-place update operator. Therefore, the `input_x` will be updated after the operation is completed. Args: use_locking (bool): Whether protect the assignment by a lock. Default: False. Inputs: - **input_x** (Parameter) - The target tensor, with data type of Parameter. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. - **indices** (Tensor) - The index to do min operation whose data type must be mindspore.int32. - **updates** (Tensor) - The tensor doing the min operation with `input_x`, the data type is same as `input_x`, the shape is `indices_shape + x_shape[1:]`. Outputs: Tensor, the updated `input_x`, has the same shape and type as `input_x`. Raises: TypeError: If `use_locking` is not a bool. TypeError: If `indices` is not an int32. ValueError: If the shape of `updates` is not equal to `indices_shape + x_shape[1:]`. RuntimeError: If the data type of `input_x` and `updates` conversion of Parameter is required when data type conversion of Parameter is not supported. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> input_x = Parameter(Tensor(np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), mindspore.float32), name="x") >>> indices = Tensor(np.array([[0, 1], [1, 1]]), mindspore.int32) >>> updates = Tensor(np.ones([2, 2, 3]), mindspore.float32) >>> scatter_add = ops.ScatterAdd() >>> output = scatter_add(input_x, indices, updates) >>> print(output) [[1. 1. 1.] [3. 3. 3.]] >>> # for input_x will be updated after the operation is completed. input_x need to be re-initialized. >>> input_x = Parameter(Tensor(np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), mindspore.float32), name="x") >>> # for indices = [[0, 1], [1, 1]] >>> # step 1: [0, 1] >>> # input_x[0] = [0.0, 0.0, 0.0] + [1.0, 1.0, 1.0] = [1.0, 1.0, 1.0] >>> # input_x[1] = [0.0, 0.0, 0.0] + [3.0, 3.0, 3.0] = [3.0, 3.0, 3.0] >>> # step 2: [1, 1] >>> # input_x[1] = [3.0, 3.0, 3.0] + [7.0, 7.0, 7.0] = [10.0, 10.0, 10.0] >>> # input_x[1] = [10.0, 10.0, 10.0] + [9.0, 9.0, 9.0] = [19.0, 19.0, 19.0] >>> indices = Tensor(np.array([[0, 1], [1, 1]]), mindspore.int32) >>> updates = Tensor(np.array([[[1.0, 1.0, 1.0], [3.0, 3.0, 3.0]], ... [[7.0, 7.0, 7.0], [9.0, 9.0, 9.0]]]), mindspore.float32) >>> scatter_add = ops.ScatterAdd() >>> output = scatter_add(input_x, indices, updates) >>> print(output) [[ 1. 1. 1.] [19. 19. 19.]] >>> # for input_x will be updated after the operation is completed. input_x need to be re-initialized. >>> input_x = Parameter(Tensor(np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), mindspore.float32), name="x") >>> # for indices = [[1, 0], [1, 1]] >>> # step 1: [1, 0] >>> # input_x[0] = [0.0, 0.0, 0.0] + [3.0, 3.0, 3.0] = [3.0, 3.0, 3.0] >>> # input_x[1] = [0.0, 0.0, 0.0] + [1.0, 1.0, 1.0] = [1.0, 1.0, 1.0] >>> # step 2: [1, 1] >>> # input_x[1] = [1.0, 1.0, 1.0] + [7.0, 7.0, 7.0] = [8.0, 8.0, 8.0] >>> # input_x[1] = [8.0, 8.0, 8.0] + [9.0, 9.0, 9.0] = [17.0, 17.0, 17.0] >>> indices = Tensor(np.array([[1, 0], [1, 1]]), mindspore.int32) >>> updates = Tensor(np.array([[[1.0, 1.0, 1.0], [3.0, 3.0, 3.0]], ... [[7.0, 7.0, 7.0], [9.0, 9.0, 9.0]]]), mindspore.float32) >>> scatter_add = ops.ScatterAdd() >>> output = scatter_add(input_x, indices, updates) >>> print(output) [[ 3. 3. 3.] [17. 17. 17.]] >>> # for input_x will be updated after the operation is completed. input_x need to be re-initialized. >>> input_x = Parameter(Tensor(np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), mindspore.float32), name="x") >>> # for indices = [[0, 1], [0, 1]] >>> # step 1: [0, 1] >>> # input_x[0] = [0.0, 0.0, 0.0] + [1.0, 1.0, 1.0] = [1.0, 1.0, 1.0] >>> # input_x[1] = [0.0, 0.0, 0.0] + [3.0, 3.0, 3.0] = [3.0, 3.0, 3.0] >>> # step 2: [0, 1] >>> # input_x[0] = [1.0, 1.0, 1.0] + [7.0, 7.0, 7.0] = [8.0, 8.0, 8.0] >>> # input_x[1] = [3.0, 3.0, 3.0] + [9.0, 9.0, 9.0] = [12.0, 12.0, 12.0] >>> indices = Tensor(np.array([[0, 1], [0, 1]]), mindspore.int32) >>> updates = Tensor(np.array([[[1.0, 1.0, 1.0], [3.0, 3.0, 3.0]], ... [[7.0, 7.0, 7.0], [9.0, 9.0, 9.0]]]), mindspore.float32) >>> scatter_add = ops.ScatterAdd() >>> output = scatter_add(input_x, indices, updates) >>> print(output) [[ 8. 8. 8.] [12. 12. 12.]] """ @prim_attr_register def __init__(self, use_locking=False): """Initialize ScatterAdd""" validator.check_value_type('use_locking', use_locking, [bool], self.name) self.init_prim_io_names(inputs=['x', 'indices', 'updates'], outputs=['y']) self.add_prim_attr('side_effect_mem', True) class ScatterSub(_ScatterOpDynamic): r""" Updates the value of the input tensor through the subtraction operation. Using given values to update tensor value through the subtraction operation, along with the input indices. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value. for each `i, ..., j` in `indices.shape`: .. math:: \text{input_x}[\text{indices}[i, ..., j], :] \mathrel{-}= \text{updates}[i, ..., j, :] Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent. If they have different data types, the lower priority data type will be converted to the relatively highest priority data type. Args: use_locking (bool): Whether protect the assignment by a lock. Default: False. Inputs: - **input_x** (Parameter) - The target tensor, with data type of Parameter. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. - **indices** (Tensor) - The index to do min operation whose data type must be mindspore.int32. - **updates** (Tensor) - The tensor doing the min operation with `input_x`, the data type is same as `input_x`, the shape is `indices_shape + x_shape[1:]`. Outputs: Tensor, the updated `input_x`, has the same shape and type as `input_x`. Raises: TypeError: If `use_locking` is not a bool. TypeError: If `indices` is not an int32. ValueError: If the shape of `updates` is not equal to `indices_shape + x_shape[1:]`. RuntimeError: If the data type of `input_x` and `updates` conversion of Parameter is required when data type conversion of Parameter is not supported. Supported Platforms: ``Ascend`` ``CPU`` ``GPU`` Examples: >>> input_x = Parameter(Tensor(np.array([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]), mindspore.float32), name="x") >>> indices = Tensor(np.array([[0, 1]]), mindspore.int32) >>> updates = Tensor(np.array([[[1.0, 1.0, 1.0], [2.0, 2.0, 2.0]]]), mindspore.float32) >>> scatter_sub = ops.ScatterSub() >>> output = scatter_sub(input_x, indices, updates) >>> print(output) [[-1. -1. -1.] [-1. -1. -1.]] >>> # for input_x will be updated after the operation is completed. input_x need to be re-initialized. >>> input_x = Parameter(Tensor(np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), mindspore.float32), name="x") >>> # for indices = [[0, 1], [1, 1]] >>> # step 1: [0, 1] >>> # input_x[0] = [0.0, 0.0, 0.0] - [1.0, 1.0, 1.0] = [-1.0, -1.0, -1.0] >>> # input_x[1] = [0.0, 0.0, 0.0] - [3.0, 3.0, 3.0] = [-3.0, -3.0, -3.0] >>> # step 2: [1, 1] >>> # input_x[1] = [-3.0, -3.0, -3.0] - [7.0, 7.0, 7.0] = [-10.0, -10.0, -10.0] >>> # input_x[1] = [-10.0, -10.0, -10.0] - [9.0, 9.0, 9.0] = [-19.0, -19.0, -19.0] >>> indices = Tensor(np.array([[0, 1], [1, 1]]), mindspore.int32) >>> updates = Tensor(np.array([[[1.0, 1.0, 1.0], [3.0, 3.0, 3.0]], ... [[7.0, 7.0, 7.0], [9.0, 9.0, 9.0]]]), mindspore.float32) >>> scatter_sub = ops.ScatterSub() >>> output = scatter_sub(input_x, indices, updates) >>> print(output) [[ -1. -1. -1.] [-19. -19. -19.]] >>> # for input_x will be updated after the operation is completed. input_x need to be re-initialized. >>> input_x = Parameter(Tensor(np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), mindspore.float32), name="x") >>> # for indices = [[1, 0], [1, 1]] >>> # step 1: [1, 0] >>> # input_x[0] = [0.0, 0.0, 0.0] - [3.0, 3.0, 3.0] = [-3.0, -3.0, -3.0] >>> # input_x[1] = [0.0, 0.0, 0.0] - [1.0, 1.0, 1.0] = [-1.0, -1.0, -1.0] >>> # step 2: [1, 1] >>> # input_x[1] = [-1.0, -1.0, -1.0] - [7.0, 7.0, 7.0] = [-8.0, -8.0, -8.0] >>> # input_x[1] = [-8.0, -8.0, -8.0] - [9.0, 9.0, 9.0] = [-17.0, -17.0, -17.0] >>> indices = Tensor(np.array([[1, 0], [1, 1]]), mindspore.int32) >>> updates = Tensor(np.array([[[1.0, 1.0, 1.0], [3.0, 3.0, 3.0]], ... [[7.0, 7.0, 7.0], [9.0, 9.0, 9.0]]]), mindspore.float32) >>> scatter_sub = ops.ScatterSub() >>> output = scatter_sub(input_x, indices, updates) >>> print(output) [[ -3. -3. -3.] [-17. -17. -17.]] >>> # for input_x will be updated after the operation is completed. input_x need to be re-initialized. >>> input_x = Parameter(Tensor(np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), mindspore.float32), name="x") >>> # for indices = [[0, 1], [0, 1]] >>> # step 1: [0, 1] >>> # input_x[0] = [0.0, 0.0, 0.0] - [1.0, 1.0, 1.0] = [-1.0, -1.0, -1.0] >>> # input_x[1] = [0.0, 0.0, 0.0] - [3.0, 3.0, 3.0] = [-3.0, -3.0, -3.0] >>> # step 2: [0, 1] >>> # input_x[0] = [-1.0, -1.0, -1.0] - [7.0, 7.0, 7.0] = [-8.0, -8.0, -8.0] >>> # input_x[1] = [-3.0, -3.0, -3.0] - [9.0, 9.0, 9.0] = [-12.0, -12.0, -12.0] >>> indices = Tensor(np.array([[0, 1], [0, 1]]), mindspore.int32) >>> updates = Tensor(np.array([[[1.0, 1.0, 1.0], [3.0, 3.0, 3.0]], ... [[7.0, 7.0, 7.0], [9.0, 9.0, 9.0]]]), mindspore.float32) >>> scatter_sub = ops.ScatterSub() >>> output = scatter_sub(input_x, indices, updates) >>> print(output) [[ -8. -8. -8.] [-12. -12. -12.]] """ @prim_attr_register def __init__(self, use_locking=False): """Initialize ScatterSub""" validator.check_value_type('use_locking', use_locking, [bool], self.name) self.init_prim_io_names(inputs=['x', 'indices', 'updates'], outputs=['y']) self.add_prim_attr('side_effect_mem', True) class ScatterMul(_ScatterOp): r""" Updates the value of the input tensor through the multiply operation. Using given values to update tensor value through the mul operation, along with the input indices. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value. for each `i, ..., j` in `indices.shape`: .. math:: \text{input_x}[\text{indices}[i, ..., j], :] \mathrel{*}= \text{updates}[i, ..., j, :] Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent. If they have different data types, the lower priority data type will be converted to the relatively highest priority data type. Args: use_locking (bool): Whether protect the assignment by a lock. Default: False. Inputs: - **input_x** (Parameter) - The target tensor, with data type of Parameter. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. - **indices** (Tensor) - The index to do min operation whose data type must be mindspore.int32. - **updates** (Tensor) - The tensor doing the min operation with `input_x`, the data type is same as `input_x`, the shape is `indices_shape + x_shape[1:]`. Outputs: Tensor, the updated `input_x`, has the same shape and type as `input_x`. Raises: TypeError: If `use_locking` is not a bool. TypeError: If `indices` is not an int32. ValueError: If the shape of `updates` is not equal to `indices_shape + x_shape[1:]`. RuntimeError: If the data type of `input_x` and `updates` conversion of Parameter is required when data type conversion of Parameter is not supported. Supported Platforms: ``Ascend`` ``CPU`` Examples: >>> input_x = Parameter(Tensor(np.array([[1.0, 1.0, 1.0], [2.0, 2.0, 2.0]]), mindspore.float32), name="x") >>> indices = Tensor(np.array([0, 1]), mindspore.int32) >>> updates = Tensor(np.array([[2.0, 2.0, 2.0], [2.0, 2.0, 2.0]]), mindspore.float32) >>> scatter_mul = ops.ScatterMul() >>> output = scatter_mul(input_x, indices, updates) >>> print(output) [[2. 2. 2.] [4. 4. 4.]] >>> # for input_x will be updated after the operation is completed. input_x need to be re-initialized. >>> input_x = Parameter(Tensor(np.array([[1.0, 1.0, 1.0], [2.0, 2.0, 2.0]]), mindspore.float32), name="x") >>> # for indices = [[0, 1], [1, 1]] >>> # step 1: [0, 1] >>> # input_x[0] = [1.0, 1.0, 1.0] * [1.0, 1.0, 1.0] = [1.0, 1.0, 1.0] >>> # input_x[1] = [2.0, 2.0, 2.0] * [3.0, 3.0, 3.0] = [6.0, 6.0, 6.0] >>> # step 2: [1, 1] >>> # input_x[1] = [6.0, 6.0, 6.0] * [7.0, 7.0, 7.0] = [42.0, 42.0, 42.0] >>> # input_x[1] = [42.0, 42.0, 42.0] * [9.0, 9.0, 9.0] = [378.0, 378.0, 378.0] >>> indices = Tensor(np.array([[0, 1], [1, 1]]), mindspore.int32) >>> updates = Tensor(np.array([[[1.0, 1.0, 1.0], [3.0, 3.0, 3.0]], ... [[7.0, 7.0, 7.0], [9.0, 9.0, 9.0]]]), mindspore.float32) >>> scatter_mul = ops.ScatterMul() >>> output = scatter_mul(input_x, indices, updates) >>> print(output) [[ 1. 1. 1.] [378. 378. 378.]] >>> # for input_x will be updated after the operation is completed. input_x need to be re-initialized. >>> input_x = Parameter(Tensor(np.array([[1.0, 1.0, 1.0], [2.0, 2.0, 2.0]]), mindspore.float32), name="x") >>> # for indices = [[1, 0], [1, 1]] >>> # step 1: [1, 0] >>> # input_x[0] = [1.0, 1.0, 1.0] * [3.0, 3.0, 3.0] = [3.0, 3.0, 3.0] >>> # input_x[1] = [2.0, 2.0, 2.0] * [1.0, 1.0, 1.0] = [2.0, 2.0, 2.0] >>> # step 2: [1, 1] >>> # input_x[1] = [2.0, 2.0, 2.0] * [7.0, 7.0, 7.0] = [14.0, 14.0, 14.0] >>> # input_x[1] = [14.0, 14.0, 14.0] * [9.0, 9.0, 9.0] = [126.0, 126.0, 126.0] >>> indices = Tensor(np.array([[1, 0], [1, 1]]), mindspore.int32) >>> updates = Tensor(np.array([[[1.0, 1.0, 1.0], [3.0, 3.0, 3.0]], ... [[7.0, 7.0, 7.0], [9.0, 9.0, 9.0]]]), mindspore.float32) >>> scatter_mul = ops.ScatterMul() >>> output = scatter_mul(input_x, indices, updates) >>> print(output) [[ 3. 3. 3.] [126. 126. 126.]] >>> # for input_x will be updated after the operation is completed. input_x need to be re-initialized. >>> input_x = Parameter(Tensor(np.array([[1.0, 1.0, 1.0], [2.0, 2.0, 2.0]]), mindspore.float32), name="x") >>> # for indices = [[0, 1], [0, 1]] >>> # step 1: [0, 1] >>> # input_x[0] = [1.0, 1.0, 1.0] * [1.0, 1.0, 1.0] = [1.0, 1.0, 1.0] >>> # input_x[1] = [2.0, 2.0, 2.0] * [3.0, 3.0, 3.0] = [6.0, 6.0, 6.0] >>> # step 2: [0, 1] >>> # input_x[0] = [1.0, 1.0, 1.0] * [7.0, 7.0, 7.0] = [7.0, 7.0, 7.0] >>> # input_x[1] = [6.0, 6.0, 6.0] * [9.0, 9.0, 9.0] = [54.0, 54.0, 54.0] >>> indices = Tensor(np.array([[0, 1], [0, 1]]), mindspore.int32) >>> updates = Tensor(np.array([[[1.0, 1.0, 1.0], [3.0, 3.0, 3.0]], ... [[7.0, 7.0, 7.0], [9.0, 9.0, 9.0]]]), mindspore.float32) >>> scatter_mul = ops.ScatterMul() >>> output = scatter_mul(input_x, indices, updates) >>> print(output) [[ 7. 7. 7.] [54. 54. 54.]] """ class ScatterDiv(_ScatterOp): r""" Updates the value of the input tensor through the divide operation. Using given values to update tensor value through the div operation, along with the input indices. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value. for each `i, ..., j` in `indices.shape`: .. math:: \text{input_x}[\text{indices}[i, ..., j], :] \mathrel{/}= \text{updates}[i, ..., j, :] Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent. If they have different data types, the lower priority data type will be converted to the relatively highest priority data type. Args: use_locking (bool): Whether protect the assignment by a lock. Default: False. Inputs: - **input_x** (Parameter) - The target tensor, with data type of Parameter. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. - **indices** (Tensor) - The index to do min operation whose data type must be mindspore.int32. - **updates** (Tensor) - The tensor doing the min operation with `input_x`, the data type is same as `input_x`, the shape is `indices_shape + x_shape[1:]`. Outputs: Tensor, the updated `input_x`, has the same shape and type as `input_x`. Raises: TypeError: If `use_locking` is not a bool. TypeError: If `indices` is not an int32. ValueError: If the shape of `updates` is not equal to `indices_shape + x_shape[1:]`. RuntimeError: If the data type of `input_x` and `updates` conversion of Parameter is required when data type conversion of Parameter is not supported. Supported Platforms: ``Ascend`` ``CPU`` Examples: >>> input_x = Parameter(Tensor(np.array([[6.0, 6.0, 6.0], [2.0, 2.0, 2.0]]), mindspore.float32), name="x") >>> indices = Tensor(np.array([0, 1]), mindspore.int32) >>> updates = Tensor(np.array([[2.0, 2.0, 2.0], [2.0, 2.0, 2.0]]), mindspore.float32) >>> scatter_div = ops.ScatterDiv() >>> output = scatter_div(input_x, indices, updates) >>> print(output) [[3. 3. 3.] [1. 1. 1.]] >>> # for input_x will be updated after the operation is completed. input_x need to be re-initialized. >>> input_x = Parameter(Tensor(np.array([[105.0, 105.0, 105.0], ... [315.0, 315.0, 315.0]]), mindspore.float32), name="x") >>> # for indices = [[0, 1], [1, 1]] >>> # step 1: [0, 1] >>> # input_x[0] = [105.0, 105.0, 105.0] / [1.0, 1.0, 1.0] = [105.0, 105.0, 105.0] >>> # input_x[1] = [315.0, 315.0, 315.0] / [3.0, 3.0, 3.0] = [105.0, 105.0, 105.0] >>> # step 2: [1, 1] >>> # input_x[1] = [105.0, 105.0, 105.0] / [5.0, 5.0, 5.0] = [21.0, 21.0, 21.0] >>> # input_x[1] = [21.0, 21.0, 21.0] / [7.0, 7.0, 7.0] = [3.0, 3.0, 3.0] >>> indices = Tensor(np.array([[0, 1], [1, 1]]), mindspore.int32) >>> updates = Tensor(np.array([[[1.0, 1.0, 1.0], [3.0, 3.0, 3.0]], ... [[5.0, 5.0, 5.0], [7.0, 7.0, 7.0]]]), mindspore.float32) >>> scatter_div = ops.ScatterDiv() >>> output = scatter_div(input_x, indices, updates) >>> print(output) [[105. 105. 105.] [ 3. 3. 3.]] >>> # for input_x will be updated after the operation is completed. input_x need to be re-initialized. >>> input_x = Parameter(Tensor(np.array([[105.0, 105.0, 105.0], ... [315.0, 315.0, 315.0]]), mindspore.float32), name="x") >>> # for indices = [[1, 0], [1, 1]] >>> # step 1: [1, 0] >>> # input_x[0] = [105.0, 105.0, 105.0] / [3.0, 3.0, 3.0] = [35.0, 35.0, 35.0] >>> # input_x[1] = [315.0, 315.0, 315.0] / [1.0, 1.0, 1.0] = [315.0, 315.0, 315.0] >>> # step 2: [1, 1] >>> # input_x[1] = [315.0, 315.0, 315.0] / [5.0, 5.0, 5.0] = [63.0 63.0 63.0] >>> # input_x[1] = [63.0 63.0 63.0] / [7.0, 7.0, 7.0] = [9.0, 9.0, 9.0] >>> indices = Tensor(np.array([[1, 0], [1, 1]]), mindspore.int32) >>> updates = Tensor(np.array([[[1.0, 1.0, 1.0], [3.0, 3.0, 3.0]], ... [[5.0, 5.0, 5.0], [7.0, 7.0, 7.0]]]), mindspore.float32) >>> scatter_div = ops.ScatterDiv() >>> output = scatter_div(input_x, indices, updates) >>> print(output) [[35. 35. 35.] [ 9. 9. 9.]] >>> # for input_x will be updated after the operation is completed. input_x need to be re-initialized. >>> input_x = Parameter(Tensor(np.array([[105.0, 105.0, 105.0], ... [315.0, 315.0, 315.0]]), mindspore.float32), name="x") >>> # for indices = [[0, 1], [0, 1]] >>> # step 1: [0, 1] >>> # input_x[0] = [105.0, 105.0, 105.0] / [1.0, 1.0, 1.0] = [105.0, 105.0, 105.0] >>> # input_x[1] = [315.0, 315.0, 315.0] / [3.0, 3.0, 3.0] = [105.0, 105.0, 105.0] >>> # step 2: [0, 1] >>> # input_x[0] = [105.0, 105.0, 105.0] / [5.0, 5.0, 5.0] = [21.0, 21.0, 21.0] >>> # input_x[1] = [105.0, 105.0, 105.0] / [7.0, 7.0, 7.0] = [15.0, 15.0, 15.0] >>> indices = Tensor(np.array([[0, 1], [0, 1]]), mindspore.int32) >>> updates = Tensor(np.array([[[1.0, 1.0, 1.0], [3.0, 3.0, 3.0]], ... [[5.0, 5.0, 5.0], [7.0, 7.0, 7.0]]]), mindspore.float32) >>> scatter_div = ops.ScatterDiv() >>> output = scatter_div(input_x, indices, updates) >>> print(output) [[21. 21. 21.] [15. 15. 15.]] """ class ScatterNdAdd(Primitive): r""" Applies sparse addition to individual values or slices in a tensor. Using given values to update tensor value through the add operation, along with the input indices. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value. `input_x` has rank P and `indices` has rank Q where `Q >= 2`. `indices` has shape :math:`(i_0, i_1, ..., i_{Q-2}, N)` where `N <= P`. The last dimension of `indices` (with length `N` ) indicates slices along the `N` th dimension of `input_x`. `updates` is a tensor of rank `Q-1+P-N`. Its shape is: :math:`(i_0, i_1, ..., i_{Q-2}, x\_shape_N, ..., x\_shape_{P-1})`. Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent. If they have different data types, the lower priority data type will be converted to the relatively highest priority data type. Args: use_locking (bool): Whether protect the assignment by a lock. Default: False. Inputs: - **input_x** (Parameter) - The target tensor, with data type of Parameter. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. - **indices** (Tensor) - The index to do min operation whose data type must be mindspore.int32. The rank of indices must be at least 2 and `indices_shape[-1] <= len(shape)`. - **updates** (Tensor) - The tensor doing the min operation with `input_x`, the data type is same as `input_x`, the shape is `indices_shape[:-1] + x_shape[indices_shape[-1]:]`. Outputs: Tensor, the updated `input_x`, has the same shape and type as `input_x`. Raises: TypeError: If `use_locking` is not a bool. TypeError: If `indices` is not an int32. ValueError: If the shape of `updates` is not equal to `indices_shape[:-1] + x_shape[indices_shape[-1]:]`. RuntimeError: If the data type of `input_x` and `updates` conversion of Parameter is required when data type conversion of Parameter is not supported. Supported Platforms: ``Ascend`` ``GPU`` Examples: >>> input_x = Parameter(Tensor(np.array([1, 2, 3, 4, 5, 6, 7, 8]), mindspore.float32), name="x") >>> indices = Tensor(np.array([[2], [4], [1], [7]]), mindspore.int32) >>> updates = Tensor(np.array([6, 7, 8, 9]), mindspore.float32) >>> scatter_nd_add = ops.ScatterNdAdd() >>> output = scatter_nd_add(input_x, indices, updates) >>> print(output) [ 1. 10. 9. 4. 12. 6. 7. 17.] >>> input_x = Parameter(Tensor(np.zeros((4, 4, 4)), mindspore.int32)) >>> indices = Tensor(np.array([[0], [2]]), mindspore.int32) >>> updates = Tensor(np.array([[[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]], ... [[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]]]), mindspore.int32) >>> scatter_nd_add = ops.ScatterNdAdd() >>> output = scatter_nd_add(input_x, indices, updates) >>> print(output) [[[1 1 1 1] [2 2 2 2] [3 3 3 3] [4 4 4 4]] [[0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0]] [[5 5 5 5] [6 6 6 6] [7 7 7 7] [8 8 8 8]] [[0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0]]] """ __mindspore_signature__ = ( sig.make_sig('input_x', sig.sig_rw.RW_WRITE, dtype=sig.sig_dtype.T), sig.make_sig('indices', dtype=sig.sig_dtype.T1), sig.make_sig('updates', dtype=sig.sig_dtype.T) ) @prim_attr_register def __init__(self, use_locking=False): """Initialize ScatterNdAdd""" validator.check_value_type('use_locking', use_locking, [bool], self.name) self.init_prim_io_names(inputs=['input_x', 'indices', 'updates'], outputs=['y']) self.add_prim_attr('side_effect_mem', True) class ScatterNdSub(_ScatterNdOp): r""" Applies sparse subtraction to individual values or slices in a tensor. Using given values to update tensor value through the subtraction operation, along with the input indices. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value. `input_x` has rank P and `indices` has rank Q where `Q >= 2`. `indices` has shape :math:`(i_0, i_1, ..., i_{Q-2}, N)` where `N <= P`. The last dimension of `indices` (with length `N` ) indicates slices along the `N` th dimension of `input_x`. `updates` is a tensor of rank `Q-1+P-N`. Its shape is: :math:`(i_0, i_1, ..., i_{Q-2}, x\_shape_N, ..., x\_shape_{P-1})`. Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent. If they have different data types, the lower priority data type will be converted to relatively highest priority data type. Args: use_locking (bool): Whether protect the assignment by a lock. Default: False. Inputs: - **input_x** (Parameter) - The target tensor, with data type of Parameter. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. - **indices** (Tensor) - The index of input tensor, with int32 data type. The rank of indices must be at least 2 and `indices_shape[-1] <= len(shape)`. - **updates** (Tensor) - The tensor to be updated to the input tensor, has the same type as input. The shape is `indices_shape[:-1] + x_shape[indices_shape[-1]:]`. Outputs: Tensor, has the same shape and type as `input_x`. Raises: TypeError: If `use_locking` is not a bool. TypeError: If `indices` is not an int32. ValueError: If the shape of `updates` is not equal to `indices_shape[:-1] + x_shape[indices_shape[-1]:]`. RuntimeError: If the data type of `input_x` and `updates` conversion of Parameter is required when data type conversion of Parameter is not supported. Supported Platforms: ``Ascend`` ``GPU`` Examples: >>> input_x = Parameter(Tensor(np.array([1, 2, 3, 4, 5, 6, 7, 8]), mindspore.float32), name="x") >>> indices = Tensor(np.array([[2], [4], [1], [7]]), mindspore.int32) >>> updates = Tensor(np.array([6, 7, 8, 9]), mindspore.float32) >>> scatter_nd_sub = ops.ScatterNdSub() >>> output = scatter_nd_sub(input_x, indices, updates) >>> print(output) [ 1. -6. -3. 4. -2. 6. 7. -1.] >>> input_x = Parameter(Tensor(np.zeros((4, 4, 4)), mindspore.int32)) >>> indices = Tensor(np.array([[0], [2]]), mindspore.int32) >>> updates = Tensor(np.array([[[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]], ... [[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]]]), mindspore.int32) >>> scatter_nd_sub = ops.ScatterNdSub() >>> output = scatter_nd_sub(input_x, indices, updates) >>> print(output) [[[-1 -1 -1 -1] [-2 -2 -2 -2] [-3 -3 -3 -3] [-4 -4 -4 -4]] [[ 0 0 0 0] [ 0 0 0 0] [ 0 0 0 0] [ 0 0 0 0]] [[-5 -5 -5 -5] [-6 -6 -6 -6] [-7 -7 -7 -7] [-8 -8 -8 -8]] [[ 0 0 0 0] [ 0 0 0 0] [ 0 0 0 0] [ 0 0 0 0]]] """ class ScatterNonAliasingAdd(Primitive): """ Applies sparse addition to the input using individual values or slices. Using given values to update tensor value through the add operation, along with the input indices. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value. Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent. If they have different data types, the lower priority data type will be converted to the relatively highest priority data type. Inputs: - **input_x** (Parameter) - The target parameter. The data type must be float16, float32 or int32. - **indices** (Tensor) - The index to perform the addition operation whose data type must be mindspore.int32. - **updates** (Tensor) - The tensor that performs the addition operation with `input_x`, the data type is the same as `input_x`, the shape is `indices_shape[:-1] + x_shape[indices_shape[-1]:]`. Outputs: Parameter, the updated `input_x`. Raises: TypeError: If dtype of `indices` is not int32. TypeError: If dtype of `input_x` is not one of float16, float32, int32. ValueError: If the shape of `updates` is not equal to `indices_shape[:-1] + x_shape[indices_shape[-1]:]`. RuntimeError: If the data type of `input_x` and `updates` conversion of Parameter is required when data type conversion of Parameter is not supported. Supported Platforms: ``Ascend`` Examples: >>> input_x = Parameter(Tensor(np.array([1, 2, 3, 4, 5, 6, 7, 8]), mindspore.float32), name="x") >>> indices = Tensor(np.array([[2], [4], [1], [7]]), mindspore.int32) >>> updates = Tensor(np.array([6, 7, 8, 9]), mindspore.float32) >>> scatter_non_aliasing_add = ops.ScatterNonAliasingAdd() >>> output = scatter_non_aliasing_add(input_x, indices, updates) >>> print(output) [ 1. 10. 9. 4. 12. 6. 7. 17.] """ __mindspore_signature__ = ( sig.make_sig('input_x', sig.sig_rw.RW_WRITE, dtype=sig.sig_dtype.T), sig.make_sig('indices', dtype=sig.sig_dtype.T1), sig.make_sig('updates', dtype=sig.sig_dtype.T) ) @prim_attr_register def __init__(self): """Initialize ScatterNonAliasingAdd""" self.init_prim_io_names(inputs=['input_x', 'indices', 'updates'], outputs=['y']) self.add_prim_attr('side_effect_mem', True) class SpaceToDepth(PrimitiveWithInfer): r""" Rearrange blocks of spatial data into depth. The output tensor's `height` dimension is :math:`height / block\_size`. The output tensor's `weight` dimension is :math:`weight / block\_size`. The depth of output tensor is :math:`block\_size * block\_size * input\_depth`. The input tensor's height and width must be divisible by `block_size`. The data format is "NCHW". Args: block_size (int): The block size used to divide spatial data. It must be >= 2. Inputs: - **x** (Tensor) - The target tensor. The data type is Number. It must be a 4-D tensor. Outputs: Tensor, the same data type as `x`. It must be a 4-D tensor. Tensor of shape :math:`(N, ( C_{in} * \text{block_size} * 2), H_{in} / \text{block_size}, W_{in} / \text{block_size})`. Raises: TypeError: If `block_size` is not an int. ValueError: If `block_size` is less than 2. ValueError: If length of shape of `x` is not equal to 4. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> x = Tensor(np.random.rand(1,3,2,2), mindspore.float32) >>> block_size = 2 >>> space_to_depth = ops.SpaceToDepth(block_size) >>> output = space_to_depth(x) >>> print(output.shape) (1, 12, 1, 1) """ @prim_attr_register def __init__(self, block_size): """Initialize SpaceToDepth""" self.init_prim_io_names(inputs=['x'], outputs=['y']) validator.check_value_type('block_size', block_size, [int], self.name) validator.check('block_size', block_size, '', 2, Rel.GE) self.block_size = block_size self.add_prim_attr("data_format", "NCHW") def infer_shape(self, x_shape): validator.check('x dimension', len(x_shape), '', 4, Rel.EQ) out_shape = copy.deepcopy(x_shape) for i in range(2): if out_shape[i + 2] % self.block_size != 0: msg_prefix = "2nd" if i + 2 == 2 else "3rd" raise ValueError(f"For '{self.name}', the shape of output with index {i + 2} must be divided " f"exactly by 'block_size', but got the {msg_prefix} dimension " f"of output: {out_shape[i + 2]} and " f"'block_size': {self.block_size}.") out_shape[i + 2] //= self.block_size out_shape[1] *= self.block_size * self.block_size return out_shape def infer_dtype(self, x_dtype): validator.check_subclass("x_dtype", x_dtype, mstype.tensor, self.name) return x_dtype class DepthToSpace(PrimitiveWithInfer): r""" Rearrange blocks of depth data into spatial dimensions. This is the reverse operation of SpaceToDepth. The depth of output tensor is :math:`input\_depth / (block\_size * block\_size)`. The output tensor's `height` dimension is :math:`height * block\_size`. The output tensor's `weight` dimension is :math:`weight * block\_size`. The input tensor's depth must be divisible by `block_size * block_size`. The data format is "NCHW". Args: block_size (int): The block size used to divide depth data. It must be >= 2. Inputs: - **x** (Tensor) - The target tensor. It must be a 4-D tensor with shape :math:`(N, C_{in}, H_{in}, W_{in})`. The data type is Number. Outputs: Tensor of shape :math:`(N, C_{in} / \text{block_size} ^ 2, H_{in} * \text{block_size}, W_{in} * \text{block_size})`. Raises: TypeError: If `block_size` is not an int. ValueError: If `block_size` is less than 2. ValueError: If length of shape of `x` is not equal to 4. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> x = Tensor(np.random.rand(1, 12, 1, 1), mindspore.float32) >>> block_size = 2 >>> depth_to_space = ops.DepthToSpace(block_size) >>> output = depth_to_space(x) >>> print(output.shape) (1, 3, 2, 2) """ @prim_attr_register def __init__(self, block_size): """Initialize DepthToSpace""" self.init_prim_io_names(inputs=['x'], outputs=['y']) validator.check_value_type('block_size', block_size, [int], self.name) validator.check('block_size', block_size, '', 2, Rel.GE, self.name) self.block_size = block_size self.add_prim_attr("data_format", "NCHW") def infer_shape(self, x_shape): validator.check('x dimension', len(x_shape), '', 4, Rel.EQ) out_shape = copy.deepcopy(x_shape) for i in range(2): out_shape[i + 2] *= self.block_size validator.check_int(x_shape[1] % (self.block_size * self.block_size), 0, Rel.EQ, 'x_shape[1] % (block_size*block_size)', self.name) out_shape[1] //= self.block_size * self.block_size return out_shape def infer_dtype(self, x_dtype): validator.check_subclass("x_dtype", x_dtype, mstype.tensor, self.name) return x_dtype class SpaceToBatch(PrimitiveWithInfer): r""" SpaceToBatch is deprecated. Please use :class:`mindspore.ops.SpaceToBatchND` instead. Divides spatial dimensions into blocks and combines the block size with the original batch. This operation will divide spatial dimensions (H, W) into blocks with `block_size`, the output tensor's H and W dimension is the corresponding number of blocks after division. The output tensor's batch dimension is the product of the original batch and the square of block_size. Before division, the spatial dimensions of the input are zero padded according to paddings if necessary. Args: block_size (int): The block size of dividing blocks with value greater than or equal to 2. paddings (Union[tuple, list]): The padding values for H and W dimension, containing 2 subtraction lists. Each subtraction list contains 2 integer value. All values must be greater than 0. paddings[i] specifies the paddings for the spatial dimension i, which corresponds to the input dimension i+2. It is required that input_shape[i+2]+paddings[i][0]+paddings[i][1] is divisible by block_size. Inputs: - **input_x** (Tensor) - The input tensor. It must be a 4-D tensor. The data type is Number. Outputs: Tensor, the output tensor with the same data type as input. Assume input shape is :math:`(n, c, h, w)` with :math:`block\_size` and :math:`paddings`. The shape of the output tensor will be :math:`(n', c', h', w')`, where :math:`n' = n*(block\_size*block\_size)` :math:`c' = c` :math:`h' = (h+paddings[0][0]+paddings[0][1])//block\_size` :math:`w' = (w+paddings[1][0]+paddings[1][1])//block\_size` Raises: TypeError: If `block_size` is not an int. ValueError: If `block_size` is less than 2. Supported Platforms: Deprecated Examples: >>> block_size = 2 >>> paddings = [[0, 0], [0, 0]] >>> space_to_batch = ops.SpaceToBatch(block_size, paddings) >>> input_x = Tensor(np.array([[[[1, 2], [3, 4]]]]), mindspore.float32) >>> output = space_to_batch(input_x) >>> print(output) [[[[1.]]] [[[2.]]] [[[3.]]] [[[4.]]]] """ @prim_attr_register def __init__(self, block_size, paddings): """Initialize SpaceToBatch""" logger.warning("WARN_DEPRECATED: The usage of SpaceToBatch is deprecated." " Please use SpaceToBatchND.") validator.check_value_type('block_size', block_size, [int], self.name) validator.check('block_size', block_size, '', 2, Rel.GE, self.name) self.block_size = block_size validator.check('paddings shape', np.array(paddings).shape, '', (2, 2), Rel.EQ, self.name) for elem in itertools.chain(*paddings): validator.check_non_negative_int(elem, 'paddings element', self.name) validator.check_value_type('paddings element', elem, [int], self.name) self.paddings = paddings def infer_dtype(self, x_dtype): validator.check_tensor_dtype_valid('input_x', x_dtype, mstype.number_type, self.name) return x_dtype def infer_shape(self, x_shape): validator.check_equal_int(len(x_shape), 4, 'rank of input_x', self.name) out_shape = copy.deepcopy(x_shape) for i in range(2): padded = out_shape[i + 2] + self.paddings[i][0] + self.paddings[i][1] if padded % self.block_size != 0: msg_ndim = "2nd" if i + 2 == 2 else "3rd" raise ValueError(f"For '{self.name}', the shape of the output tensor should be " f"divisible by 'block_size', but got the {msg_ndim} dimension of output: {padded} and " f"'block_size': {self.block_size}. Please check the official homepage " f"for more information about the output tensor.") out_shape[i + 2] = padded // self.block_size out_shape[0] *= self.block_size * self.block_size return out_shape class BatchToSpace(PrimitiveWithInfer): r""" Divides batch dimension with blocks and interleaves these blocks back into spatial dimensions. This operation will divide batch dimension N into blocks with block_size, the output tensor's N dimension is the corresponding number of blocks after division. The output tensor's H, W dimension is product of original H, W dimension and block_size with given amount to crop from dimension, respectively. Args: block_size (int): The block size of division, has the value not less than 2. crops (Union[list(int), tuple(int)]): The crop value for H and W dimension, containing 2 subtraction lists. Each list contains 2 integers. All values must be not less than 0. crops[i] specifies the crop values for the spatial dimension i, which corresponds to the input dimension i+2. It is required that :math:`input\_shape[i+2]*block\_size >= crops[i][0]+crops[i][1]` Inputs: - **input_x** (Tensor) - The input tensor. It must be a 4-D tensor, dimension 0 must be divisible by product of `block_shape`. The data type is float16 or float32. Outputs: Tensor, the output tensor with the same type as input. Assume input shape is (n, c, h, w) with block_size and crops. The output shape will be (n', c', h', w'), where :math:`n' = n//(block\_size*block\_size)` :math:`c' = c` :math:`h' = h*block\_size-crops[0][0]-crops[0][1]` :math:`w' = w*block\_size-crops[1][0]-crops[1][1]` Raises: TypeError: If `block_size` or element of `crops` is not an int. TypeError: If `crops` is neither list nor tuple. ValueError: If `block_size` is less than 2. Supported Platforms: ``Ascend`` ``GPU`` Examples: >>> block_size = 2 >>> crops = [[0, 0], [0, 0]] >>> batch_to_space = ops.BatchToSpace(block_size, crops) >>> input_x = Tensor(np.array([[[[1]]], [[[2]]], [[[3]]], [[[4]]]]), mindspore.float32) >>> output = batch_to_space(input_x) >>> print(output) [[[[1. 2.] [3. 4.]]]] """ @prim_attr_register def __init__(self, block_size, crops): """Initialize BatchToSpace""" logger.warning("WARN_DEPRECATED: The usage of BatchToSpace is deprecated." " Please use BatchToSpaceND.") validator.check_value_type('block_size', block_size, [int], self.name) validator.check('block_size', block_size, '', 2, Rel.GE, self.name) self.block_size = block_size validator.check_value_type('crops type', crops, [list, tuple], self.name) validator.check('crops shape', np.array(crops).shape, '', (2, 2)) for elem in itertools.chain(*crops): validator.check_non_negative_int(elem, 'crops element', self.name) validator.check_value_type('crops element', elem, [int], self.name) self.crops = crops def infer_dtype(self, x_dtype): validator.check_tensor_dtype_valid('input_x', x_dtype, mstype.number_type, self.name) return x_dtype def infer_shape(self, x_shape): validator.check('rank of input_x', len(x_shape), '', 4) out_shape = copy.deepcopy(x_shape) for i in range(2): x_block_prod = out_shape[i + 2] * self.block_size crops_sum = self.crops[i][0] + self.crops[i][1] validator.check("x block shape prod", x_block_prod, 'crops sum', crops_sum, Rel.GT, self.name) out_shape[i + 2] = x_block_prod - crops_sum block_size_prod = self.block_size * self.block_size if out_shape[0] % block_size_prod != 0: raise ValueError(f"For '{self.name}', the shape of output with index 0 must be divided exactly " f"by block_size_prod, but got the shape of output: {out_shape} and " f"block_size_prod: {block_size_prod}.") out_shape[0] = out_shape[0] // block_size_prod return out_shape class SpaceToBatchND(PrimitiveWithInfer): r""" Divides spatial dimensions into blocks and combines the block size with the original batch. This operation will divide spatial dimensions (H, W) into blocks with block_shape, the output tensor's H and W dimension is the corresponding number of blocks after division. The output tensor's batch dimension is the product of the original batch and the product of `block_shape`. Before division, the spatial dimensions of the input are zero padded according to paddings if necessary. Args: block_shape (Union[list(int), tuple(int), int]): The block shape of dividing block with all value greater than 1. If `block_shape` is a tuple or list, the length of `block_shape` is M corresponding to the number of spatial dimensions. If `block_shape` is an int, the block size of M dimensions are the same, equal to `block_shape`. M must be 2. paddings (Union[tuple, list]): The padding values for H and W dimension, containing 2 subtraction list. Each contains 2 integer value. All values must be greater than 0. `paddings[i]` specifies the paddings for the spatial dimension i, which corresponds to the input dimension i+2. It is required that input_shape[i+2]+paddings[i][0]+paddings[i][1] is divisible by block_shape[i]. Inputs: - **input_x** (Tensor) - The input tensor. It must be a 4-D tensor. Outputs: Tensor, the output tensor with the same data type as input. Assume input shape is :math:`(n, c, h, w)` with :math:`block\_shape` and :math:`paddings`. The shape of the output tensor will be :math:`(n', c', h', w')`, where :math:`n' = n*(block\_shape[0]*block\_shape[1])` :math:`c' = c` :math:`h' = (h+paddings[0][0]+paddings[0][1])//block\_shape[0]` :math:`w' = (w+paddings[1][0]+paddings[1][1])//block\_shape[1]` Raises: TypeError: If `block_shape` is not one of list, tuple, int. TypeError: If `paddings` is neither list nor tuple. ValueError: If length of shape of `block_shape` is not equal to 1. ValueError: If length of `block_shape` or `paddings` is not equal to 2. Supported Platforms: ``Ascend`` Examples: >>> block_shape = [2, 2] >>> paddings = [[0, 0], [0, 0]] >>> space_to_batch_nd = ops.SpaceToBatchND(block_shape, paddings) >>> input_x = Tensor(np.array([[[[1, 2], [3, 4]]]]), mindspore.float32) >>> output = space_to_batch_nd(input_x) >>> print(output) [[[[1.]]] [[[2.]]] [[[3.]]] [[[4.]]]] """ @prim_attr_register def __init__(self, block_shape, paddings): """Initialize SpaceToBatchND""" if isinstance(block_shape, int): block_shape = (block_shape,) * 2 self.add_prim_attr("block_shape", block_shape) validator.check_value_type('block_shape type', block_shape, [list, tuple], self.name) validator.check('block_shape shape', len(np.array(block_shape).shape), '', 1, Rel.EQ, self.name) block_rank = len(block_shape) validator.check('block_shape length', block_rank, '', 2, Rel.EQ, self.name) for elem in block_shape: validator.check('block_shape element', elem, '', 1, Rel.GE, self.name) validator.check_value_type('block_shape element', elem, [int], self.name) self.block_shape = block_shape validator.check_value_type('paddings type', paddings, [list, tuple], self.name) validator.check('paddings length', len(paddings), '', 2, Rel.EQ, self.name) validator.check('paddings shape', np.array(paddings).shape, '', (block_rank, 2), Rel.EQ, self.name) for elem in itertools.chain(*paddings): validator.check_non_negative_int(elem, 'paddings element', self.name) validator.check_value_type('paddings element', elem, [int], self.name) self.paddings = paddings def infer_dtype(self, x_dtype): validator.check_tensor_dtype_valid('input_x', x_dtype, mstype.number_type, self.name) return x_dtype def infer_shape(self, x_shape): x_rank = len(x_shape) validator.check_equal_int(x_rank, 4, 'x_shape rank', self.name) out_shape = copy.deepcopy(x_shape) block_shape_prod = 1 offset = 2 for i in range(len(self.block_shape)): padded = out_shape[i + offset] + self.paddings[i][0] + \ self.paddings[i][1] if padded % self.block_shape[i] != 0: raise ValueError(f"For '{self.name}', the padded should be divisible by 'block_shape', " f"where padded = input_x_shape[i + 2] + paddings[i][0] + paddings[i][1], " f"but got input_x_shape[{i + 2}]: {out_shape[i + offset]}, " f"paddings[{i}][0]: {self.paddings[i][0]} and paddings[{i}][1]: {self.paddings[i][1]}." f" Please check the official api documents for " f"more information about the output tensor.") out_shape[i + offset] = padded // self.block_shape[i] block_shape_prod = block_shape_prod * self.block_shape[i] out_shape[0] *= block_shape_prod return out_shape class BatchToSpaceND(Primitive): r""" Divides batch dimension with blocks and interleaves these blocks back into spatial dimensions. This operation will divide batch dimension N into blocks with block_shape, the output tensor's N dimension is the corresponding number of blocks after division. The output tensor's H, W dimension is the product of original H, W dimension and block_shape with given amount to crop from dimension, respectively. Args: block_shape (Union[list(int), tuple(int), int]): The block shape of dividing block with all value greater than 1. If `block_shape` is a tuple or list, the length of `block_shape` is M corresponding to the number of spatial dimensions. If `block_shape` is an int, the block size of M dimensions are the same, equal to `block_shape`. M must be 2. crops (Union[list(int), tuple(int)]): The crop value for H and W dimension, containing 2 subtraction list, each containing 2 int value. All values must be >= 0. crops[i] specifies the crop values for spatial dimension i, which corresponds to input dimension i+2. It is required that :math:`input\_shape[i+2]*block\_shape[i] > crops[i][0]+crops[i][1]` Inputs: - **input_x** (Tensor) - The input tensor. It must be a 4-D tensor, dimension 0 must be divisible by product of `block_shape`. The data type is float16 or float32. Outputs: Tensor, the output tensor with the same type as input. Assume input shape is (n, c, h, w) with block_shape and crops. The output shape will be (n', c', h', w'), where :math:`n' = n//(block\_shape[0]*block\_shape[1])` :math:`c' = c` :math:`h' = h*block\_shape[0]-crops[0][0]-crops[0][1]` :math:`w' = w*block\_shape[1]-crops[1][0]-crops[1][1]` Raises: TypeError: If `block_shape` is not one of list, tuple, int. TypeError: If `crops` is neither list nor tuple. ValueError: If length of `block_shape` or `crops` is not equal to 2. Supported Platforms: ``Ascend`` Examples: >>> block_shape = [2, 2] >>> crops = [[0, 0], [0, 0]] >>> batch_to_space_nd = ops.BatchToSpaceND(block_shape, crops) >>> input_x = Tensor(np.array([[[[1]]], [[[2]]], [[[3]]], [[[4]]]]), mindspore.float32) >>> output = batch_to_space_nd(input_x) >>> print(output) [[[[1. 2.] [3. 4.]]]] """ @prim_attr_register def __init__(self, block_shape, crops): """Initialize BatchToSpaceND""" if isinstance(block_shape, int): block_shape = (block_shape,) * 2 self.add_prim_attr("block_shape", block_shape) validator.check_value_type('block_shape type', block_shape, [list, tuple], self.name) validator.check('block_shape shape', len(np.array(block_shape).shape), '', 1, Rel.EQ, self.name) block_rank = len(block_shape) validator.check('block_shape length', block_rank, '', 2, Rel.EQ, self.name) for elem in block_shape: validator.check('block_shape element', elem, '', 1, Rel.GE, self.name) validator.check_value_type('block_shape element', elem, [int], self.name) self.block_shape = block_shape validator.check_value_type('crops type', crops, [list, tuple], self.name) validator.check('crops length', len(crops), '', 2, Rel.EQ, self.name) validator.check('crops shape', np.array(crops).shape, '', (block_rank, 2), Rel.EQ, self.name) for elem in itertools.chain(*crops): validator.check_non_negative_int(elem, 'crops element', self.name) validator.check_value_type('crops element', elem, [int], self.name) self.crops = crops class BroadcastTo(Primitive): """ Broadcasts input tensor to a given shape. Input shape can be broadcast to target shape if for each dimension pair they are either equal or input is one or the target dimension is -1. In case of -1 in target shape, it will be replaced by the input shape's value in that dimension. When input shape is broadcast to target shape, it starts with the trailing dimensions. If there is a -1 in the target shape, the -1 cannot be in a leading, non-existing dimension. Args: shape (tuple): The target shape to broadcast. Can be fully specified, or have -1 in one position where it will be substituted by the input tensor's shape in that position, see example. Inputs: - **input_x** (Tensor) - The input tensor. The data type should be one of the following types: float16, float32, int32, int8, uint8. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. Outputs: Tensor, with the given `shape` and the same data type as `input_x`. Raises: TypeError: If `shape` is not a tuple. ValueError: if the target and input shapes are incompatible, or if a - 1 in the target shape is in an invalid location. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> shape = (2, 3) >>> input_x = Tensor(np.array([1, 2, 3]).astype(np.float32)) >>> broadcast_to = ops.BroadcastTo(shape) >>> output = broadcast_to(input_x) >>> print(output) [[1. 2. 3.] [1. 2. 3.]] >>> shape = (-1, 2) >>> input_x = Tensor(np.array([[1], [2]]).astype(np.float32)) >>> broadcast_to = ops.BroadcastTo(shape) >>> output = broadcast_to(input_x) >>> print(output) [[1. 1.] [2. 2.]] """ @prim_attr_register def __init__(self, shape): """Initialize BroadcastTo""" validator.check_value_type("shape", shape, (tuple), self.name) validator.check("shape length", len(shape), "", 0, Rel.GT, self.name) for ix, i in enumerate(shape): validator.check_value_type('target shape index -> ' + str(ix), i, [int], self.name) validator.check("shape element", i, "shape element min limit", -1, Rel.GE, self.name) self.shape = shape class Meshgrid(PrimitiveWithInfer): """ Generates coordinate matrices from given coordinate tensors. Given N one-dimensional coordinate tensors, returns a tuple outputs of N N-D coordinate tensors for evaluating expressions on an N-D grid. Args: indexing ('xy', 'ij', optional): Cartesian ('xy', default) or matrix ('ij') indexing of output. In the 2-D case with inputs of length `M` and `N`, the outputs are of shape `(N, M)` for 'xy' indexing and `(M, N)` for 'ij' indexing. In the 3-D case with inputs of length `M`, `N` and `P`, outputs are of shape `(N, M, P)` for 'xy' indexing and `(M, N, P)` for 'ij' indexing. Inputs: - **input** (Union[tuple]) - A Tuple of N 1-D Tensor objects. The length of input should be greater than 1. The data type is Number. Outputs: Tensors, A Tuple of N N-D Tensor objects. The data type is the same with the Inputs. Raises: TypeError: If `indexing` is not a str or `input` is not a tuple. ValueError: If `indexing` is neither 'xy' nor 'ij'. Supported Platforms: ``Ascend`` ``GPU`` Examples: >>> x = Tensor(np.array([1, 2, 3, 4]).astype(np.int32)) >>> y = Tensor(np.array([5, 6, 7]).astype(np.int32)) >>> z = Tensor(np.array([8, 9, 0, 1, 2]).astype(np.int32)) >>> inputs = (x, y, z) >>> meshgrid = ops.Meshgrid(indexing="xy") >>> output = meshgrid(inputs) >>> print(output) (Tensor(shape=[3, 4, 5], dtype=Int32, value= [[[1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [4, 4, 4, 4, 4]], [[1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [4, 4, 4, 4, 4]], [[1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [4, 4, 4, 4, 4]]]), Tensor(shape=[3, 4, 5], dtype=Int32, value= [[[5, 5, 5, 5, 5], [5, 5, 5, 5, 5], [5, 5, 5, 5, 5], [5, 5, 5, 5, 5]], [[6, 6, 6, 6, 6], [6, 6, 6, 6, 6], [6, 6, 6, 6, 6], [6, 6, 6, 6, 6]], [[7, 7, 7, 7, 7], [7, 7, 7, 7, 7], [7, 7, 7, 7, 7], [7, 7, 7, 7, 7]]]), Tensor(shape=[3, 4, 5], dtype=Int32, value= [[[8, 9, 0, 1, 2], [8, 9, 0, 1, 2], [8, 9, 0, 1, 2], [8, 9, 0, 1, 2]], [[8, 9, 0, 1, 2], [8, 9, 0, 1, 2], [8, 9, 0, 1, 2], [8, 9, 0, 1, 2]], [[8, 9, 0, 1, 2], [8, 9, 0, 1, 2], [8, 9, 0, 1, 2], [8, 9, 0, 1, 2]]])) """ @prim_attr_register def __init__(self, indexing="xy"): """Initialize Meshgrid.""" validator.check_value_type("indexing", indexing, (str), self.name) validator.check_string(indexing.lower(), ["xy", "ij"], "indexing", self.name) self.indexing = indexing def infer_shape(self, x_shape): validator.check_value_type("shape", x_shape, [tuple], self.name) validator.check_int(len(x_shape), 2, Rel.GE, "len of input", self.name) n = len(x_shape) shape_0 = [] for s in x_shape: validator.check_int(len(s), 1, Rel.EQ, 'each input rank', self.name) shape_0.append(s[0]) if self.indexing == "xy": shape_0[0], shape_0[1] = shape_0[1], shape_0[0] out_shape = tuple(tuple(shape_0) for _ in range(n)) return out_shape def infer_dtype(self, x_type): validator.check_subclass("input[0]", x_type[0], mstype.tensor, self.name) n = len(x_type) for i in range(1, n): validator.check('x_type[%d]' % i, x_type[i], 'base', x_type[0], Rel.EQ, self.name, TypeError) return x_type class InplaceUpdate(PrimitiveWithInfer): r""" Updates specified rows with values in `v`. Args: indices (Union[int, tuple]): Indices into the left-most dimension of `x`, and determines which rows of x to update with v. It is an int or tuple, whose value is in [0, the first dimension size of x). Inputs: - **x** (Tensor) - A tensor which to be inplace updated. It can be one of the following data types: float32, float16 and int32. - **v** (Tensor) - A tensor with the same type as `x` and the same dimension size as `x` except the first dimension, which must be the same as the size of `indices`. Outputs: Tensor, with the same type and shape as the input `x`. Raises: TypeError: If `indices` is neither int nor tuple. TypeError: If `indices` is a tuple and its element is not an int. Supported Platforms: ``Ascend`` Examples: >>> indices = (0, 1) >>> x = Tensor(np.array([[1, 2], [3, 4], [5, 6]]), mindspore.float32) >>> v = Tensor(np.array([[0.5, 1.0], [1.0, 1.5]]), mindspore.float32) >>> inplace_update = ops.InplaceUpdate(indices) >>> output = inplace_update(x, v) >>> print(output) [[0.5 1. ] [1. 1.5] [5. 6. ]] """ @prim_attr_register def __init__(self, indices): """Initialize InplaceUpdate""" self.init_prim_io_names(inputs=['x', 'v'], outputs=['y']) self.indices = indices validator.check_value_type("indices", indices, [int, tuple], self.name) if isinstance(indices, int): self.indices = (indices,) for item in self.indices: validator.check_value_type("item of indices", item, [int], self.name) def infer_dtype(self, x_dtype, v_dtype): args = {'x': x_dtype, 'v': v_dtype} valid_type = [mstype.int32, mstype.float16, mstype.float32] validator.check_tensors_dtypes_same_and_valid(args, valid_type, self.name) return x_dtype def infer_shape(self, x_shape, v_shape): validator.check("x", len(x_shape), "v", len(v_shape), Rel.EQ, self.name) validator.check("size of indices", len(self.indices), "v's first dimension", v_shape[0], Rel.EQ, self.name) for i in self.indices: if i < 0 or i >= x_shape[0]: raise ValueError(f"For '{self.name}', the value of indices must be in [0, {x_shape[0]}), " f"but got {i}.") x_rank = len(x_shape) for idx in range(x_rank)[1:]: validator.check('v dim %d' % idx, v_shape[idx], "x dim %d" % idx, x_shape[idx], Rel.EQ, self.name) return x_shape class ReverseSequence(PrimitiveWithInfer): """ Reverses variable length slices. Args: seq_dim (int): The dimension where reversal is performed. Required. batch_dim (int): The input is sliced in this dimension. Default: 0. Inputs: - **x** (Tensor) - The input to reverse, supporting all number types including bool. - **seq_lengths** (Tensor) - Must be a 1-D vector with int32 or int64 types. Outputs: Reversed tensor with the same shape and data type as input. Raises: TypeError: If `seq_dim` or `batch_dim` is not an int. Supported Platforms: ``Ascend`` ``GPU`` Examples: >>> x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), mindspore.float32) >>> seq_lengths = Tensor(np.array([1, 2, 3])) >>> reverse_sequence = ops.ReverseSequence(seq_dim=1) >>> output = reverse_sequence(x, seq_lengths) >>> print(output) [[1. 2. 3.] [5. 4. 6.] [9. 8. 7.]] >>> x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), mindspore.float32) >>> seq_lengths = Tensor(np.array([1, 2, 3])) >>> reverse_sequence = ops.ReverseSequence(seq_dim=0, batch_dim=1) >>> output = reverse_sequence(x, seq_lengths) >>> print(output) [[1. 5. 9.] [4. 2. 6.] [7. 8. 3.]] >>> x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), mindspore.float32) >>> seq_lengths = Tensor(np.array([2, 2, 3])) >>> reverse_sequence = ops.ReverseSequence(seq_dim=1) >>> output = reverse_sequence(x, seq_lengths) >>> print(output) [[2. 1. 3.] [5. 4. 6.] [9. 8. 7.]] >>> x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), mindspore.float32) >>> seq_lengths = Tensor(np.array([3, 2, 3])) >>> reverse_sequence = ops.ReverseSequence(seq_dim=1) >>> output = reverse_sequence(x, seq_lengths) >>> print(output) [[3. 2. 1.] [5. 4. 6.] [9. 8. 7.]] >>> x = Tensor(np.array([[1, 2, 3, 4], [5, 6, 7, 8]]), mindspore.float32) >>> seq_lengths = Tensor(np.array([4, 4])) >>> reverse_sequence = ops.ReverseSequence(seq_dim=1) >>> output = reverse_sequence(x, seq_lengths) >>> print(output) [[4. 3. 2. 1.] [8. 7. 6. 5.]] """ @prim_attr_register def __init__(self, seq_dim, batch_dim=0): """Initialize ReverseSequence""" self.init_prim_io_names(inputs=['x', 'seq_lengths'], outputs=['y']) validator.check_value_type("seq_dim", seq_dim, [int], self.name) self.seq_dim_ = seq_dim validator.check_value_type("batch_dim", batch_dim, [int], self.name) self.batch_dim_ = batch_dim def infer_shape(self, x, seq_lengths): validator.check("seq_dim", self.seq_dim_, "x rank", len(x), Rel.LE, self.name) validator.check("batch_dim", self.batch_dim_, "x rank", len(x), Rel.LE, self.name) validator.check("batch_dim", self.batch_dim_, "seq_dim", self.seq_dim_, Rel.NE, self.name) validator.check("seq_lengths rank", len(seq_lengths), "expected", 1, Rel.EQ, self.name) validator.check("seq_lengths vector size", seq_lengths[0], "input size along batch_dim", x[self.batch_dim_], Rel.EQ, self.name) return x def infer_dtype(self, x, seq_lengths): validator.check_tensor_dtype_valid("x_dtype", x, mstype.number_type + (mstype.bool_,), self.name) validator.check_tensor_dtype_valid("seq_lengths_dtype", seq_lengths, [mstype.int32, mstype.int64], self.name) return x class EditDistance(PrimitiveWithInfer): r""" Computes the Levenshtein Edit Distance. It is used to measure the similarity of two sequences. The inputs are variable-length sequences provided by SparseTensors (hypothesis_indices, hypothesis_values, hypothesis_shape) and (truth_indices, truth_values, truth_shape). .. math:: \operatorname{lev}_{a, b}(i, j)=\left\{\begin{array}{ll} \max (i, j) \qquad \qquad \qquad \qquad \qquad \quad \ \text { if } \min (i, j)=0 \\ \min \left\{\begin{array}{ll} \operatorname{lev}_{a, b}(i-1, j)+1 & \\ \operatorname{lev}_{a, b}(i, j-1)+1 & \text { otherwise. } \\ \operatorname{lev}_{a, b}(i-1, j-1)+1_{\left(a_{i} \neq b_{j}\right)} \end{array}\right. & \end{array}\right. Where the :math:`a` indicates the hypothesis and the :math:`a` indicates the truth. For ease of understanding, i and j here in may be considered as lengths of a and b. Args: normalize (bool): If true, edit distances are normalized by length of truth. Default: True. Inputs: - **hypothesis_indices** (Tensor) - The indices of the hypothesis list SparseTensor. With int64 data type. The shape of tensor is :math:`(N, R)`. - **hypothesis_values** (Tensor) - The values of the hypothesis list SparseTensor. With float32 data type. Must be 1-D vector with length of N. - **hypothesis_shape** (Tensor) - The shape of the hypothesis list SparseTensor. Must be R-length vector with int64 data type. Only constant value is allowed. - **truth_indices** (Tensor) - The indices of the truth list SparseTensor. With int64 data type. The shape of tensor is :math:`(M, R)`. - **truth_values** (Tensor) - The values of the truth list SparseTensor. Must be 1-D vector with length of M. With float32 data type. - **truth_shape** (Tensor) - The shape of the truth list SparseTensor. Must be R-length vector with int64 data type. Only constant value is allowed. Outputs: Tensor, a dense tensor with rank `R-1` and float32 data type. Raises: TypeError: If `normalize` is not a bool. Supported Platforms: ``Ascend`` Examples: >>> import numpy as np >>> from mindspore import context >>> from mindspore import Tensor >>> import mindspore.nn as nn >>> import mindspore.ops as ops >>> class EditDistance(nn.Cell): ... def __init__(self, hypothesis_shape, truth_shape, normalize=True): ... super(EditDistance, self).__init__() ... self.edit_distance = ops.EditDistance(normalize) ... self.hypothesis_shape = hypothesis_shape ... self.truth_shape = truth_shape ... ... def construct(self, hypothesis_indices, hypothesis_values, truth_indices, truth_values): ... return self.edit_distance(hypothesis_indices, hypothesis_values, self.hypothesis_shape, ... truth_indices, truth_values, self.truth_shape) ... >>> hypothesis_indices = Tensor(np.array([[0, 0, 0], [1, 0, 1], [1, 1, 1]]).astype(np.int64)) >>> hypothesis_values = Tensor(np.array([1, 2, 3]).astype(np.float32)) >>> hypothesis_shape = Tensor(np.array([1, 1, 2]).astype(np.int64)) >>> truth_indices = Tensor(np.array([[0, 1, 0], [0, 0, 1], [1, 1, 0], [1, 0, 1]]).astype(np.int64)) >>> truth_values = Tensor(np.array([1, 3, 2, 1]).astype(np.float32)) >>> truth_shape = Tensor(np.array([2, 2, 2]).astype(np.int64)) >>> edit_distance = EditDistance(hypothesis_shape, truth_shape) >>> output = edit_distance(hypothesis_indices, hypothesis_values, truth_indices, truth_values) >>> print(output) [[1. 1.] [1. 1.]] """ @prim_attr_register def __init__(self, normalize=True): """Initialize EditDistance""" self.normalize = validator.check_value_type("normalize", normalize, [bool], self.name) self.set_const_input_indexes([2, 5]) def __infer__(self, h_indices, h_values, h_shape, truth_indices, truth_values, truth_shape): validator.check_valid_input('hypothesis_shape', h_shape['value'], self.name) validator.check_valid_input('truth_shape', truth_shape['value'], self.name) args_int = {"hypothesis_indices": h_indices['dtype'], "hypothesis_shape": h_shape['dtype'], "truth_indices": truth_indices['dtype'], "truth_shape": truth_shape['dtype']} validator.check_tensors_dtypes_same_and_valid(args_int, [mstype.int64], self.name) args = {"hypothesis_values": h_values['dtype'], "truth_values": truth_values['dtype']} validator.check_tensors_dtypes_same_and_valid(args, mstype.number_type, self.name) hypothesis_indices_shp, truth_indices_shp = h_indices['shape'], truth_indices['shape'] validator.check("hypothesis_indices rank", len(hypothesis_indices_shp), "expected", 2, Rel.EQ, self.name) validator.check("truth_indices rank", len(truth_indices_shp), "expected", 2, Rel.EQ, self.name) validator.check("hypothesis_values rank", len(h_values['shape']), "expected", 1, Rel.EQ, self.name) validator.check("hypothesis_shape rank", len(h_shape['shape']), "expected", 1, Rel.EQ, self.name) validator.check("truth_values rank", len(truth_values['shape']), "expected", 1, Rel.EQ, self.name) validator.check("truth_shape rank", len(truth_shape['shape']), "expected", 1, Rel.EQ, self.name) validator.check("hypothesis_values shape", h_values['shape'][0], "hypothesis_indices shape[0]", hypothesis_indices_shp[0], Rel.EQ, self.name) validator.check("hypothesis_shape", h_shape['shape'][0], "hypothesis_indices shape[1]", hypothesis_indices_shp[1], Rel.EQ, self.name) validator.check("truth_values shape", truth_values['shape'][0], "truth_indices shape[0]", truth_indices_shp[0], Rel.EQ, self.name) validator.check("hypothesis_shape", h_shape['shape'][0], "truth_shape", truth_shape['shape'][0], Rel.EQ, self.name) hypothesis_shape_v = h_shape['value'].asnumpy() truth_shape_v = truth_shape['value'].asnumpy() out_shape_rank = len(hypothesis_shape_v) - 1 out_shape = [] for i in range(out_shape_rank): out_shape.append(max(hypothesis_shape_v[i], truth_shape_v[i])) return {'shape': tuple(out_shape), 'dtype': mstype.tensor_type(mstype.float32), 'value': None} class TransShape(PrimitiveWithInfer): """ Transforms the shape of input tensor to target shape. Inputs: - **input_x** (Tensor) - A input tensor. - **out_shape** (tuple[int]) - The shape of output data. Outputs: Tensor, a tensor whose data type is same as 'input_x', and the shape is the same as the `out_shape`. """ @prim_attr_register def __init__(self): """Initialize TransShape.""" self.__setattr_flag__ = True def __infer__(self, x, shape): shp = shape['value'] dtype = x['dtype'] validator.check_tensor_dtype_valid('x', dtype, mstype.number_type + (mstype.bool_,), self.name) self.add_prim_attr('out_shape', tuple(shp)) return {'shape': shp, 'dtype': dtype, 'value': None} class Sort(Primitive): """ Sorts the elements of the input tensor along a given dimension in ascending order by value. Args: axis (int): The dimension to sort along. Default: -1. descending (bool): Controls the sorting order. If descending is True then the elements are sorted in descending order by value. Default: False. .. warning:: Currently, only the data type of Float16 is supported. If use Float32, it may cause loss of accuracy. Inputs: - **x** (Tensor) - The input to sort, with float16 or float32 data type. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. Outputs: - **y1** (Tensor) - A tensor whose values are the sorted values, with the same shape and data type as input. - **y2** (Tensor) - The indices of the elements in the original input tensor. Data type is int32. Raises: TypeError: If `axis` is not an int. TypeError: If `descending` is not a bool. TypeError: If dtype of `x` is neither float16 nor float32. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> x = Tensor(np.array([[8, 2, 1], [5, 9, 3], [4, 6, 7]]), mindspore.float16) >>> sort = ops.Sort() >>> output = sort(x) >>> print(output) (Tensor(shape=[3, 3], dtype=Float16, value= [[ 1.0000e+00, 2.0000e+00, 8.0000e+00], [ 3.0000e+00, 5.0000e+00, 9.0000e+00], [ 4.0000e+00, 6.0000e+00, 7.0000e+00]]), Tensor(shape=[3, 3], dtype=Int32, value= [[2, 1, 0], [2, 0, 1], [0, 1, 2]])) """ @prim_attr_register def __init__(self, axis=-1, descending=False): """Initialize Sort""" self.axis = validator.check_value_type("axis", axis, [int], self.name) self.descending = validator.check_value_type("descending", descending, [bool], self.name) self.init_prim_io_names(inputs=['x'], outputs=['y1', 'y2']) class EmbeddingLookup(PrimitiveWithCheck): """ Returns a slice of input tensor based on the specified indices. This Primitive has the similar functionality as GatherV2 operating on `axis = 0`, but has one more inputs: `offset`. Inputs: - **input_params** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. This represents a Tensor slice, instead of the entire Tensor. Currently, the dimension is restricted to be 2. - **input_indices** (Tensor) - The shape of tensor is :math:`(y_1, y_2, ..., y_S)`. Specifies the indices of elements of the original Tensor. Values can be out of range of `input_params`, and the exceeding part will be filled with 0 in the output. Values do not support negative and the result is undefined if values are negative. The data type should be int32 or int64. - **offset** (int) - Specifies the offset value of this `input_params` slice. Thus the real indices are equal to `input_indices` minus `offset`. Outputs: Tensor, the shape of tensor is :math:`(z_1, z_2, ..., z_N)`. The data type is the same with `input_params`. Raises: TypeError: If dtype of `input_indices` is not int. ValueError: If length of shape of `input_params` is greater than 2. Supported Platforms: ``Ascend`` ``CPU`` ``GPU`` Examples: >>> input_params = Tensor(np.array([[8, 9], [10, 11], [12, 13], [14, 15]]), mindspore.float32) >>> input_indices = Tensor(np.array([[5, 2], [8, 5]]), mindspore.int32) >>> offset = 4 >>> output = ops.EmbeddingLookup()(input_params, input_indices, offset) >>> print(output) [[[10. 11.] [ 0. 0.]] [[ 0. 0.] [10. 11.]]] """ @prim_attr_register def __init__(self): """Initialize EmbeddingLookup.""" self.__setattr_flag__ = True self.init_prim_io_names(inputs=['params', 'indices', 'offset'], outputs=['output']) def __check__(self, params, indices, offset): validator.check_subclass("params", params['dtype'], mstype.tensor, self.name) validator.check_tensor_dtype_valid("indices", indices['dtype'], mstype.int_type, self.name) validator.check_subclass("offset", offset['dtype'], mstype.int_, self.name) indices_shp = indices['shape'] if not indices_shp: raise ValueError(f"For '{self.name}', the dimension of 'input_indices' should not " f"be zero, but got {len(indices_shp)}.") params_shp = params['shape'] if len(params_shp) > 2: raise ValueError(f"For '{self.name}', the dimension of 'input_params' must <= 2, " f"but got {len(params_shp)}.") class GatherD(Primitive): """ Gathers values along an axis specified by dim. For a 3-D tensor, the output is: .. code-block:: output[i][j][k] = x[index[i][j][k]][j][k] # if dim == 0 output[i][j][k] = x[i][index[i][j][k]][k] # if dim == 1 output[i][j][k] = x[i][j][index[i][j][k]] # if dim == 2 If `x` is an n-D tensor with shape :math:`(z_0, z_1, ..., z_i, ..., z_{n-1})` and `dim` = i, the `index` must be an n-D tensor with shape :math:`(z_0, z_1, ..., y, ..., z_{n-1})` where `y`>=1 and the output will have the same shape as `index`. Inputs: - **x** (Tensor) - The source tensor. The shape is :math:`(N,*)` where :math:`*` means,any number of additional dimensions. - **dim** (int) - The axis along which to index. It must be int32 or int64. Only constant value is allowed. - **index** (Tensor) - The indices of elements to gather. It can be one of the following data types: int32, int64. The value range of each index element is [-x_rank[dim], x_rank[dim]). Outputs: Tensor, the shape of tensor is :math:`(z_1, z_2, ..., z_N)`, has the same data type with `x`. Raises: TypeError: If dtype of `dim` or `index` is neither int32 nor int64. ValueError: If length of shape of `x` is not equal to length of shape of `index`. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> x = Tensor(np.array([[1, 2], [3, 4]]), mindspore.int32) >>> index = Tensor(np.array([[0, 0], [1, 0]]), mindspore.int32) >>> dim = 1 >>> output = ops.GatherD()(x, dim, index) >>> print(output) [[1 1] [4 3]] """ @prim_attr_register def __init__(self): """Initialize GatherD""" self.init_prim_io_names(inputs=['x', 'dim', 'index'], outputs=['output']) class Identity(PrimitiveWithInfer): """ Returns a Tensor with the same shape and contents as input. Inputs: - **x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. The data type is Number. Outputs: Tensor, the shape of tensor and the data type are the same as `input_x`, :math:`(x_1, x_2, ..., x_R)`. Raises: TypeError: If `x` is not a Tensor. Supported Platforms: ``Ascend`` ``CPU`` ``GPU`` Examples: >>> x = Tensor(np.array([1, 2, 3, 4]), mindspore.int64) >>> output = ops.Identity()(x) >>> print(output) [1 2 3 4] """ # Side effect is identity with input. side_effect_propagate = 1 @prim_attr_register def __init__(self): """Initialize identity""" self.add_prim_attr('side_effect_propagate', 1) def __infer__(self, x): validator.check_subclass("x", x['dtype'], mstype.tensor, self.name) validator.check_tensor_dtype_valid('x', x['dtype'], mstype.number_type + (mstype.bool_,), self.name) out = {'shape': x['shape'], 'dtype': x['dtype'], 'value': None} return out class Range(PrimitiveWithCheck): r""" Creates a sequence of numbers that begins at `start` and extends by increments of `delta` up to but not including `limit`. The types of all 3 inputs must be the same. The type of the resulting tensor is the same as the type of the inputs. Args: maxlen (int): Memory that can fit `maxlen` many elements will be allocated for the output. Optional, must be positive, defaults to 1000000. If the output has more than `maxlen` elements, a runtime error will occur. Inputs: - **start** (Tensor) - A scalar Tensor. The first number in the sequence. Must have type: int32 or float32 - **limit** (Tensor) - A scalar Tensor. Upper limit of the sequence, exclusive. Must have type: int32 or float32 - **delta** (Tensor) - A scalar Tensor. Number that increments `start`. Must have type: int32 or float32 Outputs: A 1-D Tensor, with the same type as the inputs. Supported Platforms: ``GPU`` Examples: >>> start = Tensor(0, mstype.int32) >>> limit = Tensor(10, mstype.int32) >>> delta = Tensor(4, mstype.int32) >>> output = ops.Range()(start, limit, delta) >>> print(output) [0, 4, 8] """ @prim_attr_register def __init__(self, maxlen=1000000): self.init_prim_io_names(inputs=['start', 'limit', 'delta'], outputs=['output']) validator.check_value_type("maxlen", maxlen, [int], self.name) validator.check_positive_int(maxlen, "maxlen", self.name) self.maxlen = maxlen self.add_prim_attr('maxlen', maxlen) def check_shape(self, start_shape, limit_shape, delta_shape): validator.check("start_shape", len(start_shape), "", 0, Rel.EQ, self.name) validator.check("limit_shape", len(limit_shape), "", 0, Rel.EQ, self.name) validator.check("delta_shape", len(delta_shape), "", 0, Rel.EQ, self.name) def check_dtype(self, start_dtype, limit_dtype, delta_dtype): valid_dtypes = [mstype.int32, mstype.float32] inputs = {"start": start_dtype, "limit": limit_dtype, "delta": delta_dtype} validator.check_tensors_dtypes_same_and_valid(inputs, valid_dtypes, self.name) def infer_value(self, start_value, limit_value, delat_value): """Infer the value of input for Range.""" if start_value is not None and limit_value is not None and delat_value is not None: start = np.asscalar(start_value.asnumpy()) limit = np.asscalar(limit_value.asnumpy()) delat = np.asscalar(delat_value.asnumpy()) return Tensor(np.arange(start, limit, delat), dtype=start_value.dtype) return None class MaskedFill(Primitive): """ Fills elements of self tensor with value where mask is True. The shapes of `input` and `mask` need to be the same or broadcast. Inputs: - **input** (Tensor) - The source tensor whose data type is one of float16, float32, int8, int32. - **mask** (Tensor[bool]) - The boolean mask. - **value** (Union[float, Tensor]) – The value to fill in with, which only supports a 0-dimensional tensor or a float number. Outputs: Tensor, has the same type and shape as `input`. Raises: TypeError: If `input` or `mask` is not a tensor. TypeError: If `value` is neither float number nor tensor. TypeError: If dtype of `input` or `value` is not one of float16, float32, int8, int32. TypeError: If dtype of `value` is different from that of `input`. TypeError: If dtype of `mask` is not bool. ValueError: If the shapes of `input` and `mask` could not be broadcast. Supported Platforms: ``Ascend`` Examples: >>> input = Tensor(np.array([1., 2., 3., 4.]), mindspore.float32) >>> mask = Tensor(np.array([True, True, False, True]), mindspore.bool_) >>> output = ops.MaskedFill()(input, mask, 0.5) >>> print(output) [0.5 0.5 3. 0.5] """ @prim_attr_register def __init__(self): self.init_prim_io_names(inputs=['input', 'mask', 'value'], outputs=['output']) class MaskedSelect(PrimitiveWithCheck): """ Returns a new 1-D Tensor which indexes the input tensor according to the boolean mask. The shapes of the mask tensor and the input tensor don't need to match, but they must be broadcastable. Inputs: - **x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. - **mask** (Tensor[bool]) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. Outputs: A 1-D Tensor, with the same type as x. Raises: TypeError: If `x` is not a Tensor. Supported Platforms: ``Ascend`` ``CPU`` Examples: >>> x = Tensor(np.array([1, 2, 3, 4]), mindspore.int64) >>> mask = Tensor(np.array([1, 0, 1, 0]), mindspore.bool_) >>> output = ops.MaskedSelect()(x, mask) >>> print(output) [1 3] """ @prim_attr_register def __init__(self): self.init_prim_io_names(inputs=['x', 'mask'], outputs=['output']) def check_shape(self, x_shape, mask_shape): get_broadcast_shape(x_shape, mask_shape, self.name, arg_name1="x", arg_name2="mask") def check_dtype(self, x_dtype, mask_dtype): validator.check_tensor_dtype_valid('mask', mask_dtype, [mstype.bool_], self.name) validator.check_tensor_dtype_valid('x', x_dtype, mstype.number_type, self.name) class SearchSorted(PrimitiveWithInfer): """ Find the indices from the innermost dimension of `sequence` such that the order of the innermost dimension within `sequence` would be preserved when the corresponding values in `values` were inserted before the indices. Args: out_int32 (bool): Output datatype. Optional. If True, the output datatype will be int32; if False, the output datatype will be int64. Default is False. right (bool): Search Strategy. Optional. If True, return the last suitable index found. If False, return the first such index. Default is False. Inputs: - **sequence** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R-1, x_R)` or `(x_1)`. It must contain monitonically increasing sequence on the innermost dimension. - **values** (Tensor) - The shape of tensor is : math:`(x_1, x_2, ..., x_R-1, x_S)`. Outputs: Tensor containing the indices from the innermost dimension of the input sequence such that, if insert the corresponding value in the values tensor, the order of the tensor sequence would be preserved. The shape of tensor is :math:`(x_1, x_2, ..., x_R-1, x_S)`, whose datatype is int32 if out_int32 is True, otherwise int64, and shape is the same as the shape of values. Raises: ValueError: If `sequence` and `values` do not have proper shapes. Supported Platforms: ``CPU`` Examples: >>> sequence = Tensor(np.array([[0, 1, 3, 5, 7], [2, 4, 6, 8, 10]]), mindspore.float32) >>> values = Tensor(np.array([[3, 6, 9], [3, 6, 9]]), mindspore.float32) >>> output = ops.SearchSorted()(sequence, values) >>> print(output) [[2 4 5] [1 2 4]] """ @prim_attr_register def __init__(self, out_int32=False, right=False): """Initialize SearchSorted""" self.out_int32 = validator.check_value_type("out_int32", out_int32, [bool], self.name) self.right = validator.check_value_type("right", right, [bool], self.name) self.init_prim_io_names(inputs=['sequence', 'values'], outputs=['positions']) def infer_shape(self, sequence_shape, values_shape): if len(sequence_shape) != 1 and sequence_shape[:-1] != values_shape[:-1]: raise ValueError(f"For '{self.name}', the 'sequence' should be 1 dimensional or " f"all dimensions except the last dimension of 'sequence' " f"must be the same as all dimensions except the last dimension of 'values'. " f"but got shape of 'sequence': {sequence_shape} " f"and shape of 'values': {values_shape}.") return values_shape def infer_dtype(self, sequence_dtype, values_dtype): args = {"sequence_dtype": sequence_dtype, "values_dtype": values_dtype} validator.check_tensors_dtypes_same_and_valid(args, mstype.number_type, self.name) return mstype.tensor_type(mstype.int32) if self.out_int32 else mstype.tensor_type(mstype.int64) class TensorScatterMax(PrimitiveWithInfer): """ By comparing the value at the position indicated by the index in input_x with the value in the update, the value at the index will eventually be equal to the largest one to create a new tensor. The last axis of the index is the depth of each index vector. For each index vector, there must be a corresponding value in `updates`. The shape of `updates` should be equal to the shape of input_x[indices]. For more details, see use cases. Note: If some values of the `indices` are out of bound, instead of raising an index error, the corresponding `updates` will not be updated to `input_x`. Inputs: - **input_x** (Tensor) - The target tensor. The dimension of input_x must be no less than indices.shape[-1]. - **indices** (Tensor) - The index of input tensor whose data type is int32 or int64. The rank must be at least 2. - **updates** (Tensor) - The tensor to update the input tensor, has the same type as input, and updates.shape should be equal to indices.shape[:-1] + input_x.shape[indices.shape[-1]:]. Outputs: Tensor, has the same shape and type as `input_x`. Raises: TypeError: If dtype of `indices` is neither int32 nor int64. ValueError: If length of shape of `input_x` is less than the last dimension of shape of `indices`. Supported Platforms: ``GPU`` Examples: >>> input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32) >>> indices = Tensor(np.array([[0, 0], [0, 0]]), mindspore.int32) >>> updates = Tensor(np.array([1.0, 2.2]), mindspore.float32) >>> # Next, demonstrate the approximate operation process of this operator: >>> # 1, indices[0] = [0, 0], indices[1] = [0, 0] >>> # 2, And input_x[0, 0] = -0.1 >>> # 3, So input_x[indices] = [-0.1, -0.1] >>> # 4, Satisfy the above formula: input_x[indices].shape=(2) == updates.shape=(2) >>> op = ops.TensorScatterMax() >>> # 5, Perform the max operation for the first time: >>> # first_input_x = Max(input_x[0][0], updates[0]) = [[2.2, 0.3, 3.6], [0.4, 0.5, -3.2]] >>> # 6, Perform the max operation for the second time: >>> # second_input_x = Max(input_x[0][0], updates[0]) = [[2.2, 0.3, 3.6], [0.4, 0.5, -3.2]] >>> output = op(input_x, indices, updates) >>> print(output) [[ 2.2 0.3 3.6] [ 0.4 0.5 -3.2]] """ @prim_attr_register def __init__(self): self.init_prim_io_names(inputs=['input_x', 'indices', 'updates'], outputs=['y']) def infer_shape(self, input_x_shape, indices_shape, updates_shape): if len(indices_shape) < 2: raise ValueError(f"For '{self.name}', the dimension of 'indices' cannot be less than 2," f" but got {len(indices_shape)}.") if indices_shape[-1] > len(input_x_shape): raise ValueError(f"For '{self.name}', the last dimension of 'indices' must be less than or equal to " f"the dimension of 'input_x', but got the " f"last dimension of 'indices': {indices_shape[-1]} and the dimension of 'input_x': " f"{len(input_x_shape)}.") updates_shape_check = indices_shape[:-1] + input_x_shape[indices_shape[-1]:] if updates_shape_check != updates_shape: raise ValueError(f"For '{self.name}', the shape of 'update' must be equal to updates_shape_check, " f"where updates_shape_check = indices_shape[:-1] + input_x_shape[indices_shape[-1]:] " f"but got the shape of 'update': {updates_shape}, " f"updates_shape_check: {updates_shape_check}, indices_shape: {indices_shape} and " f"input_x_shape: {input_x_shape}. Please check input_x_shape and indices_shape.") return input_x_shape def infer_dtype(self, input_x_dtype, indices_dtype, updates_dtype): validator.check_tensor_dtype_valid('indices', indices_dtype, [mstype.int32, mstype.int64], self.name) args = {"input_x": input_x_dtype, "updates": updates_dtype} valid_input_types = (mstype.float16, mstype.float32, mstype.int8, mstype.uint8, mstype.int32) validator.check_tensors_dtypes_same_and_valid(args, valid_input_types, self.name) return input_x_dtype class TensorScatterMin(PrimitiveWithInfer): """ By comparing the value at the position indicated by the index in input_x with the value in the `updates`, the value at the index will eventually be equal to the smallest one to create a new tensor. The last axis of the index is the depth of each index vector. For each index vector, there must be a corresponding value in `updates`. The shape of `updates` should be equal to the shape of input_x[indices]. For more details, see use cases. Note: If some values of the `indices` are out of bound, instead of raising an index error, the corresponding `updates` will not be updated to `input_x`. Inputs: - **input_x** (Tensor) - The target tensor. The dimension of input_x must be no less than indices.shape[-1]. - **indices** (Tensor) - The index of input tensor whose data type is int32 or int64. The rank must be at least 2. - **updates** (Tensor) - The tensor to update the input tensor, has the same type as input, and updates.shape should be equal to indices.shape[:-1] + input_x.shape[indices.shape[-1]:]. Outputs: Tensor, has the same shape and type as `input_x`. Raises: TypeError: If dtype of `indices` is neither int32 nor int64. ValueError: If length of shape of `input_x` is less than the last dimension of shape of `indices`. Supported Platforms: ``GPU`` Examples: >>> input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32) >>> indices = Tensor(np.array([[0, 0], [0, 0]]), mindspore.int32) >>> updates = Tensor(np.array([1.0, 2.2]), mindspore.float32) >>> # Next, demonstrate the approximate operation process of this operator: >>> # 1, indices[0] = [0, 0], indices[1] = [0, 0] >>> # 2, And input_x[0, 0] = -0.1 >>> # 3, So input_x[indices] = [-0.1, -0.1] >>> # 4, Satisfy the above formula: input_x[indices].shape=(2) == updates.shape=(2) >>> op = ops.TensorScatterMin() >>> # 5, Perform the min operation for the first time: >>> # first_input_x = Min(input_x[0][0], updates[0]) = [[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]] >>> # 6, Perform the min operation for the second time: >>> # second_input_x = Min(input_x[0][0], updates[1]) = [[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]] >>> output = op(input_x, indices, updates) >>> print(output) [[ -0.1 0.3 3.6] [ 0.4 0.5 -3.2]] """ @prim_attr_register def __init__(self): self.init_prim_io_names(inputs=['input_x', 'indices', 'updates'], outputs=['y']) def infer_shape(self, input_x_shape, indices_shape, updates_shape): if len(indices_shape) < 2: raise ValueError(f"For '{self.name}', the dimension of 'indices' cannot be less than 2," f" but got {len(indices_shape)}.") if indices_shape[-1] > len(input_x_shape): raise ValueError(f"For '{self.name}', the last dimension of 'indices' must be less than or equal to " f"the dimension of 'input_x', but got the " f"last dimension of 'indices': {indices_shape[-1]} and the dimension of 'input_x': " f"{len(input_x_shape)}.") updates_shape_check = indices_shape[:-1] + input_x_shape[indices_shape[-1]:] if updates_shape_check != updates_shape: raise ValueError(f"For '{self.name}', the shape of 'update' must be equal to updates_shape_check, " f"where updates_shape_check = indices_shape[:-1] + input_x_shape[indices_shape[-1]:] " f"but got the shape of 'update': {updates_shape}, " f"updates_shape_check: {updates_shape_check}, indices_shape: {indices_shape} and " f"input_x_shape: {input_x_shape}. Please check input_x_shape and indices_shape.") return input_x_shape def infer_dtype(self, input_x_dtype, indices_dtype, updates_dtype): validator.check_tensor_dtype_valid('indices', indices_dtype, [mstype.int32, mstype.int64], self.name) args = {"input_x": input_x_dtype, "updates": updates_dtype} valid_input_types = (mstype.float16, mstype.float32, mstype.int8, mstype.uint8, mstype.int32) validator.check_tensors_dtypes_same_and_valid(args, valid_input_types, self.name) return input_x_dtype class TensorScatterSub(PrimitiveWithInfer): """ Creates a new tensor by subtracting the values from the positions in `input_x` indicated by `indices`, with values from `updates`. When multiple values are provided for the same index, the result of the update will be to subtract these values respectively. This operation is almost equivalent to using ScatterNdSub, except that the updates are applied on `Tensor` instead of `Parameter`. The last axis of `indices` is the depth of each index vectors. For each index vector, there must be a corresponding value in `updates`. The shape of `updates` should be equal to the shape of `input_x[indices]`. For more details, see use cases. Note: If some values of the `indices` are out of bound, instead of raising an index error, the corresponding `updates` will not be updated to `input_x`. Inputs: - **input_x** (Tensor) - The target tensor. The dimension of input_x must be no less than indices.shape[-1]. - **indices** (Tensor) - The index of input tensor whose data type is int32 or int64. The rank must be at least 2. - **updates** (Tensor) - The tensor to update the input tensor, has the same type as input, and updates.shape should be equal to indices.shape[:-1] + input_x.shape[indices.shape[-1]:]. Outputs: Tensor, has the same shape and type as `input_x`. Raises: TypeError: If dtype of `indices` is neither int32 nor int64. ValueError: If length of shape of `input_x` is less than the last dimension of shape of `indices`. Supported Platforms: ``GPU`` Examples: >>> input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32) >>> indices = Tensor(np.array([[0, 0], [0, 0]]), mindspore.int32) >>> updates = Tensor(np.array([1.0, 2.2]), mindspore.float32) >>> # Next, demonstrate the approximate operation process of this operator: >>> # 1, indices[0] = [0, 0], indices[1] = [0, 0] >>> # 2, And input_x[0, 0] = -0.1 >>> # 3, So input_x[indices] = [-0.1, -0.1] >>> # 4, Satisfy the above formula: input_x[indices].shape=(2) == updates.shape=(2) >>> op = ops.TensorScatterSub() >>> # 5, Perform the subtract operation for the first time: >>> # first_input_x = input_x[0][0] - updates[0] = [[-1.1, 0.3, 3.6], [0.4, 0.5, -3.2]] >>> # 6, Perform the subtract operation for the second time: >>> # second_input_x = input_x[0][0] - updates[1] = [[-3.3, 0.3, 3.6], [0.4, 0.5, -3.2]] >>> output = op(input_x, indices, updates) >>> print(output) [[-3.3000002 0.3 3.6 ] [ 0.4 0.5 -3.2 ]] """ @prim_attr_register def __init__(self): self.init_prim_io_names(inputs=['input_x', 'indices', 'updates'], outputs=['y']) def infer_shape(self, input_x_shape, indices_shape, updates_shape): if len(indices_shape) < 2: raise ValueError(f"For '{self.name}', the dimension of 'indices' cannot be less than 2," f" but got {len(indices_shape)}.") if indices_shape[-1] > len(input_x_shape): raise ValueError(f"For '{self.name}', the last dimension of 'indices' must be less than or equal to " f"the dimension of 'input_x', but got the " f"last dimension of 'indices': {indices_shape[-1]} and the dimension of 'input_x': " f"{len(input_x_shape)}.") updates_shape_check = indices_shape[:-1] + input_x_shape[indices_shape[-1]:] if updates_shape_check != updates_shape: raise ValueError(f"For '{self.name}', the shape of 'update' must be equal to updates_shape_check, " f"where updates_shape_check = indices_shape[:-1] + input_x_shape[indices_shape[-1]:] " f"but got the shape of 'update': {updates_shape}, " f"updates_shape_check: {updates_shape_check}, indices_shape: {indices_shape} and " f"input_x_shape: {input_x_shape}. Please check input_x_shape and indices_shape.") return input_x_shape def infer_dtype(self, input_x_dtype, indices_dtype, updates_dtype): validator.check_tensor_dtype_valid('indices', indices_dtype, [mstype.int32, mstype.int64], self.name) args = {"input_x": input_x_dtype, "updates": updates_dtype} valid_input_types = (mstype.float16, mstype.float32, mstype.int8, mstype.uint8, mstype.int32) validator.check_tensors_dtypes_same_and_valid(args, valid_input_types, self.name) return input_x_dtype class SplitV(Primitive): r""" Splits the input tensor into num_split tensors along the given dimension. The `input_x` tensor will be split into sub-tensors with individual shapes given by `size_splits` along the split dimension. This requires that `input_x.shape(split_dim)` is equal to the sum of `size_splits`. The shape of `input_x` is :math:`(x_1, x_2, ..., x_M, ..., x_R)`. The rank of `input_x` is `R`. Set the given `split_dim` as M, and :math:`-R \le M < R`. Set the given `num_split` as `N`, the given `size_splits` as :math:`(x_{m_1}, x_{m_2}, ..., x_{m_N})`, :math:`x_M=\sum_{i=1}^Nx_{m_i}`. The output is a list of tensor objects, for the :math:`i`-th tensor, it has the shape of :math:`(x_1, x_2, ..., x_{m_i}, ..., x_R)`. :math:`x_{m_i}` is the :math:`M`-th dimension of the :math:`i`-th tensor. Then, the shape of the output tensor is .. math:: ((x_1, x_2, ..., x_{m_1}, ..., x_R), (x_1, x_2, ..., x_{m_2}, ..., x_R), ..., (x_1, x_2, ..., x_{m_N}, ..., x_R)) Args: size_splits (Union[tuple, list]): The list containing the sizes of each output tensor along the split dimension. Must sum to the dimension of value along `split_dim`. Can contain one -1 indicating that dimension is to be inferred. split_dim (int): The dimension along which to split. Must be in the range [-len(input_x.shape), len(input_x.shape)). num_split (int): The number of output tensors. Must be positive int. Inputs: - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ...,x_M ..., x_R)`. Outputs: Tensor, a list of `num_split` Tensor objects with the shape :math:`((x_1, x_2, ..., x_{m_1}, ..., x_R), (x_1, x_2, ..., x_{m_2}, ..., x_R), ..., (x_1, x_2, ..., x_{m_N}, ..., x_R))`, :math:`x_M=\sum_{i=1}^Nx_{m_i}`. The data type is the same with `input_x`. Raises: TypeError: If `input_x` is not a Tensor. TypeError: If `size_splits` is not a tuple or a list. TypeError: If element of `size_splits` is not an int. TypeError: If `split_dim` or `num_split` is not an int. ValueError: If rank of the `size_splits` is not equal to `num_split`. ValueError: If sum of the `size_splits` is not equal to the dimension of value along `split_dim`. ValueError: If `split_dim` is out of the range [-len(input_x.shape), len(input_x.shape)). ValueError: If the `num_split` is less than or equal to 0. Supported Platforms: ``Ascend`` Examples: >>> input_x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), mindspore.int32) >>> op = ops.SplitV(size_splits=[1, -1], split_dim=1, num_split=2) >>> output = op(input_x) >>> print(output) (Tensor(shape=[3, 1], dtype=Int32, value= [[1], [4], [7]]), Tensor(shape=[3, 2], dtype=Int32, value= [[2, 3], [5, 6], [8, 9]])) >>> input_x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), mindspore.int32) >>> op = ops.SplitV(size_splits=[2, 1], split_dim=0, num_split=2) >>> output = op(input_x) >>> print(output) (Tensor(shape=[2, 3], dtype=Int32, value= [[1, 2, 3], [4, 5, 6]]), Tensor(shape=[1, 3], dtype=Int32, value= [[7, 8, 9]])) """ @prim_attr_register def __init__(self, size_splits, split_dim, num_split): """Initialize SplitV""" validator.check_value_type("size_splits", size_splits, [tuple, list], self.name) for elements_of_size_splits in size_splits: validator.check_value_type("elements of size_splits", elements_of_size_splits, [int], self.name) if elements_of_size_splits != -1 and elements_of_size_splits < 1: raise ValueError(f"For \'{self.name}\', all elements of size_splits must be positive (except at most " f"one default value -1), but got: {elements_of_size_splits}.") validator.check_value_type("split_dim", split_dim, [int], self.name) validator.check_value_type("num_split", num_split, [int], self.name) validator.check_positive_int(num_split, "num_split", self.name) self.init_prim_io_names(inputs=['input_x'], outputs=['output']) class ScatterElements(Primitive): """ ScatterElements takes three inputs data, updates, and indices of the same rank r >= 1 and an optional attribute axis that identifies an axis of data (default is 0). The output of the operation is produced by creating a copy of the input data, and then updating its value to values specified by updates at specific index positions specified by indices. Args: axis (int): which axis to scatter, default is 0. Inputs: - **data** (Tensor) - The target tensor. c - **indices** (Tensor) - The index of input tensor whose data type is int32 or int64. - **update** (Tensor) - The tensor to update the input tensor, has the same type as input, and update.shape should be equal to indices.shape. Outputs: Tensor, has the same shape and type as `data`. Raises: TypeError: If dtype of `indices` is neither int32 nor int64. Supported Platforms: ``Ascend`` Examples: >>> op = ops.ScatterElements(0) >>> data = Tensor(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), mindspore.float32) >>> indices = Tensor(np.array([[1, 0, 2], [0, 2, 1]]), mindspore.int32) >>> updates = Tensor(np.array([[0, 0, 0], [0, 0, 0]]), mindspore.float32) >>> output = op(data, indices, updates) >>> print(output) [[ 0.0 0.0 3.0] [ 0.0 5.0 0.0] [ 7.0 0.0 0.0]] >>> op = ops.ScatterElements(1) >>> data = Tensor(np.array([[1, 2, 3, 4, 5]), mindspore.int32) >>> indices = Tensor(np.array([[2, 4]), mindspore.int32) >>> updates = Tensor(np.array([[8, 8]]), mindspore.int32) >>> output = op(data, indices, updates) >>> print(output) [[ 1 2 8 4 8]] """ @prim_attr_register def __init__(self, axis=0): """Initialize ScatterElements""" validator.check_value_type("axis", axis, [int], self.name) self.init_prim_io_names(inputs=['data', 'indices', 'updates'], outputs=['y']) class ExtractVolumePatches(Primitive): """ Extract patches from input and put them in the "depth" output dimension. 3D extension of extract_image_patches. Args: kernel_size (Union[int, tuple[int], list[int]]): A list of ints which's length is 3 or 5. The size of the sliding window for each dimension of input. Must be: [1, 1, k_d, k_h, k_w] or [k_d, k_h, k_w]. If k_d = k_h = k_w, you can enter an integer. strides (Union[int, tuple[int], list[int]]): A list of ints which's length is 3 or 5. How far the centers of two consecutive patches are in input. Must be: [1, 1, s_d, s_h, s_w] or [s_d, s_h, s_w]. If s_d = s_h = s_w, you can enter an integer. padding (str): A string from: "SAME", "VALID". The type of padding algorithm to use. Inputs: - **input_x** (Tensor) - A Tensor. Must be one of the following types: float16, float32. 5-D Tensor with shape :math:`(x_n, x_c, x_d, x_h, x_w)`. Outputs: Tensor, has the same type as input. If padding is VALID, the shape is :math:`(x_n, k_d * k_h * k_w * x_c, 1 + (x_d - k_d) / s_d, 1 + (x_h - k_h) / s_h, 1 + (x_w - k_w) / s_w)`; if padding is SAME, the shape is :math:`( x_n, k_d * k_h * k_w * x_c, (x_d + s_d - 1) / s_d, (x_h + s_h - 1) / s_h, (x_w + s_w - 1) / s_w)`. Raises: TypeError: If dtype of input_x is neither float16 nor float32. TypeError: If kernel_size or strides is not a list, a tuple or an int. TypeError: If input_x is not a tensor. TypeError: If padding is not str. ValueError: If the length of kernel_size is neither 3 nor 5 and kernel_size is not an integer. ValueError: If the length of strides is neither 3 nor 5 and strides is not an integer. ValueError: If padding is neither "VALID" nor "SAME". ValueError: If elements of kernel_size or strides are not positive integer. ValueError: If input_x is not a tensor in dimension 5. ValueError: If input_x's shape has zero. ValueError: If one of kernel_size or strides' first two numbers is not 1. ValueError: If padding = "VALID" and input - kernel_size is less than 0 in d, h or w dimension. ValueError: If padding = "SAME" and :math:`padding_needed = ((input_x + strides - 1) / strides - 1) * strides + kernel_size - input` is less than 0 in d, h or w dimension. ValueError: If x_h is not 1 or x_w is not 1 and x_w + padding_needed - k_w - s_w is less than 0. ValueError: If x_d * x_h * x_w is greater than 2048. Supported Platforms: ``Ascend`` Example: >>> kernel_size = (1, 1, 2, 2, 2) >>> strides = (1, 1, 1, 1, 1) >>> padding = "VALID" >>> input_x = P.Reshape()(Tensor(np.arange(1, 28), mstype.float16), (1, 1, 3, 3, 3)) >>> output_y = P.ExtractVolumePatches(kernel_size, strides, padding)(input_x) >>> print(output_y.shape) (1, 8, 2, 2, 2) """ @prim_attr_register def __init__(self, kernel_size, strides, padding): validator.check_value_type("kernel_size", kernel_size, (int, list, tuple), self.name) validator.check_value_type("strides", strides, (int, list, tuple), self.name) if isinstance(kernel_size, (list, tuple)): kernel_size = tuple(kernel_size) if len(kernel_size) == 5: validator.check_int(kernel_size[0], 1, Rel.EQ, "kernel_size[0]", self.name) validator.check_int(kernel_size[1], 1, Rel.EQ, "kernel_size[1]", self.name) if isinstance(strides, (list, tuple)): strides = tuple(strides) if len(strides) == 5: validator.check_int(strides[0], 1, Rel.EQ, "strides[0]", self.name) validator.check_int(strides[1], 1, Rel.EQ, "strides[1]", self.name) self.kernel_size = _check_3d_int_or_tuple("kernel_size", kernel_size, self.name, allow_five=True, ret_five=True, greater_zero=True) self.strides = _check_3d_int_or_tuple("strides", strides, self.name, allow_five=True, ret_five=True, greater_zero=True) self.add_prim_attr("kernel_size", self.kernel_size) self.add_prim_attr("strides", self.strides) validator.check_value_type("padding_dtype", padding, (str), self.name) self.padding = validator.check_string(padding.upper(), ['VALID', 'SAME'], 'padding', self.name) self.add_prim_attr("padding", self.padding)
def dobro(n, formatar=False): num = n * 2 return num if not formatar else moeda(num) def metade(n, formatar=False): num = n / 2 return num if not formatar else moeda(num) def aumentar(n, aumenta, formatar=False): num = (n * aumenta) / 100 num += n return num if formatar is False else moeda(num) def diminuir(n, diminui, formatar=False): nu = n nume = (nu * diminui) / 100 num = n - nume return num if formatar is False else moeda(num) def moeda(n, cifrao='R$'): return f'{cifrao}{n:.2f}'.replace('.', ',') def resumo(n=0, aumenta=0, diminui=0): print('-='*20) print(f'{'RESUMO DO VALOR':^40}') print('-='*20) print(f'\033[1;30mPreço analisado: \t\t{moeda(n)}' f'\nDobro do preço: \t\t{dobro(n, True)}' f'\nMetade do preço: \t\t{metade(n, True)}' f'\n{aumenta:.0f}% de aumento: \t\t{aumentar(n, aumenta, True)}' f'\n{diminui:.0f}% de redução: \t\t{diminuir(n, diminui, True)}\033[m') print('-='*20)
def dobro(n, formatar=False): num = n * 2 return num if not formatar else moeda(num) def metade(n, formatar=False): num = n / 2 return num if not formatar else moeda(num) def aumentar(n, aumenta, formatar=False): num = (n * aumenta) / 100 num += n return num if formatar is False else moeda(num) def diminuir(n, diminui, formatar=False): nu = n nume = (nu * diminui) / 100 num = n - nume return num if formatar is False else moeda(num) def moeda(n, cifrao='R$'): return f'{cifrao}{n:.2f}'.replace('.', ',') def resumo(n=0, aumenta=0, diminui=0): print('-='*20) print(f'{"RESUMO DO VALOR":^40}') print('-='*20) print(f'\033[1;30mPreço analisado: \t\t{moeda(n)}' f'\nDobro do preço: \t\t{dobro(n, True)}' f'\nMetade do preço: \t\t{metade(n, True)}' f'\n{aumenta:.0f}% de aumento: \t\t{aumentar(n, aumenta, True)}' f'\n{diminui:.0f}% de redução: \t\t{diminuir(n, diminui, True)}\033[m') print('-='*20)
# decorator function def mymypy(types): def wrap(func): def inner(*args): for t, a in zip(types, args): if not isinstance(a, t): raise TypeError(f'Argument: {a} is not type {t}') return func(*args) return inner return wrap # --- testing --- @mymypy([float, int]) def mul(a, b): return a * b try: print(f'mul result: {mul(2.5, 3)}') print(f'mul result: {mul(4, 2)}') except TypeError as e: print(e) class MyClass: def __init__(self, x): self.x = x @mymypy([int, MyClass, int]) def objtest(a, b, c): return a * b.x - c mc = MyClass(5) try: print(f'objtest result: {objtest(2, mc, 1)}') print(f'objtest result: {objtest(2, 'k', 1)}') except TypeError as e: print(e)
# decorator function def mymypy(types): def wrap(func): def inner(*args): for t, a in zip(types, args): if not isinstance(a, t): raise TypeError(f'Argument: {a} is not type {t}') return func(*args) return inner return wrap # --- testing --- @mymypy([float, int]) def mul(a, b): return a * b try: print(f'mul result: {mul(2.5, 3)}') print(f'mul result: {mul(4, 2)}') except TypeError as e: print(e) class MyClass: def __init__(self, x): self.x = x @mymypy([int, MyClass, int]) def objtest(a, b, c): return a * b.x - c mc = MyClass(5) try: print(f'objtest result: {objtest(2, mc, 1)}') print(f'objtest result: {objtest(2, "k", 1)}') except TypeError as e: print(e)
import config import facebook graph = facebook.GraphAPI(access_token=config.fb_access_token, version="2.12") # graph.put_object(parent_object='me', connection_name='feed', message='Hello, world from rihanna') def fb(message): try: if {"facebook", "posts"} - set(message.split()) == set(): return fb_feed() elif {"facebook", "pages", "like"} - set(message.split()) == set(): return fb_likes() elif message == "how many facebook friends do i have": return f"You have {friends_num()} friends" else: return "Please ask me another question" except Exception as e: reply = f"Error in facebook: {e}" return {'display': reply, 'say': reply} def fb_likes(): data = graph.get_object('me', fields=['likes']) reply = 'Top 5 facebook pages you like' for i in data['likes']['data'][:5]: reply += f"\n{i["name"]}" return {'display': reply, 'say': reply} def fb_feed(): data = graph.get_object('me', fields=['feed']) reply = '5 Recent Facebook Posts' n = 0 for i in data['feed']['data']: if "message" in i: reply += f"\nPosted '{i["message"]}' on {i["created_time"].split("T")[0]}" n += 1 if n == 5: break return {'display': reply, 'say': reply} def friends_num(): fr = graph.get_object('me', fields=['friends']) reply = fr['friends']['summary']['total_count'] return {'display': reply, 'say': reply} # https://facebook-sdk.readthedocs.io/en/latest/api.html # https://developers.facebook.com/tools/explorer/ # print(friends_num()) #print(fb("show my facebook posts"))
import config import facebook graph = facebook.GraphAPI(access_token=config.fb_access_token, version="2.12") # graph.put_object(parent_object='me', connection_name='feed', message='Hello, world from rihanna') def fb(message): try: if {"facebook", "posts"} - set(message.split()) == set(): return fb_feed() elif {"facebook", "pages", "like"} - set(message.split()) == set(): return fb_likes() elif message == "how many facebook friends do i have": return f"You have {friends_num()} friends" else: return "Please ask me another question" except Exception as e: reply = f"Error in facebook: {e}" return {'display': reply, 'say': reply} def fb_likes(): data = graph.get_object('me', fields=['likes']) reply = 'Top 5 facebook pages you like' for i in data['likes']['data'][:5]: reply += f"\n{i['name']}" return {'display': reply, 'say': reply} def fb_feed(): data = graph.get_object('me', fields=['feed']) reply = '5 Recent Facebook Posts' n = 0 for i in data['feed']['data']: if "message" in i: reply += f"\nPosted '{i['message']}' on {i['created_time'].split('T')[0]}" n += 1 if n == 5: break return {'display': reply, 'say': reply} def friends_num(): fr = graph.get_object('me', fields=['friends']) reply = fr['friends']['summary']['total_count'] return {'display': reply, 'say': reply} # https://facebook-sdk.readthedocs.io/en/latest/api.html # https://developers.facebook.com/tools/explorer/ # print(friends_num()) #print(fb("show my facebook posts"))
import math import os import xml.dom.minidom from collections import defaultdict from datetime import datetime as dt from struct import unpack import fsspec import numpy as np from .parse_base import ParseBase FILENAME_DATETIME_AZFP = "\\w+.01A" class ParseAZFP(ParseBase): """Class for converting data from ASL Environmental Sciences AZFP echosounder.""" def __init__(self, file, params, storage_options={}): super().__init__(file, storage_options) # Parent class attributes # regex pattern used to grab datetime embedded in filename self.timestamp_pattern = FILENAME_DATETIME_AZFP self.xml_path = params # Class attributes self.parameters = dict() self.unpacked_data = defaultdict(list) self.sonar_type = "AZFP" def load_AZFP_xml(self): """Parse XML file to get params for reading AZFP data.""" """Parses the AZFP XML file. """ def get_value_by_tag_name(tag_name, element=0): """Returns the value in an XML tag given the tag name and the number of occurrences.""" return px.getElementsByTagName(tag_name)[element].childNodes[0].data # TODO: consider writing a ParamAZFPxml class for storing parameters xmlmap = fsspec.get_mapper(self.xml_path, **self.storage_options) px = xml.dom.minidom.parse(xmlmap.fs.open(xmlmap.root)) int_params = { "NumFreq": "num_freq", "SerialNumber": "serial_number", "BurstInterval": "burst_interval", "PingsPerBurst": "pings_per_burst", "AverageBurstPings": "average_burst_pings", "SensorsFlag": "sensors_flag", } float_params = [ "ka", "kb", "kc", "A", "B", "C", # Temperature coeffs "X_a", "X_b", "X_c", "X_d", "Y_a", "Y_b", "Y_c", "Y_d", ] # Tilt coeffs] freq_params = { "RangeSamples": "range_samples", "RangeAveragingSamples": "range_averaging_samples", "DigRate": "dig_rate", "LockOutIndex": "lockout_index", "Gain": "gain", "PulseLen": "pulse_length", "DS": "DS", "EL": "EL", "TVR": "TVR", "VTX0": "VTX", "BP": "BP", } # Retreive integer parameters from the xml file for old_name, new_name in int_params.items(): self.parameters[new_name] = int(get_value_by_tag_name(old_name)) # Retreive floating point parameters from the xml file for param in float_params: self.parameters[param] = float(get_value_by_tag_name(param)) # Retrieve frequency dependent parameters from the xml file for old_name, new_name in freq_params.items(): self.parameters[new_name] = [ float(get_value_by_tag_name(old_name, ch)) for ch in range(self.parameters["num_freq"]) ] def parse_raw(self): """Parse raw data file from AZFP echosounder. Parameters ---------- raw : list raw filename """ # Start of computation subfunctions def compute_temp(counts): """ Returns the temperature in celsius given from xml data and the counts from ancillary """ v_in = 2.5 * (counts / 65535) R = (self.parameters["ka"] + self.parameters["kb"] * v_in) / ( self.parameters["kc"] - v_in ) # fmt: off T = 1 / ( self.parameters["A"] + self.parameters["B"] * (math.log(R)) + self.parameters["C"] * (math.log(R) ** 3) ) - 273 # fmt: on return T def compute_tilt(N, a, b, c, d): return a + b * N + c * N ** 2 + d * N ** 3 def compute_battery(N): USL5_BAT_CONSTANT = (2.5 / 65536.0) * (86.6 + 475.0) / 86.6 return N * USL5_BAT_CONSTANT # Instrument specific constants HEADER_SIZE = 124 HEADER_FORMAT = ( ">HHHHIHHHHHHHHHHHHHHHHHHHHHHHHHHHHHBBBBHBBBBBBBBHHHHHHHHHHHHHHHHHHHH" ) # Read xml file into dict self.load_AZFP_xml() fmap = fsspec.get_mapper(self.source_file, **self.storage_options) with fmap.fs.open(fmap.root, "rb") as file: ping_num = 0 eof = False while not eof: header_chunk = file.read(HEADER_SIZE) if header_chunk: header_unpacked = unpack(HEADER_FORMAT, header_chunk) # Reading will stop if the file contains an unexpected flag if self._split_header(file, header_unpacked): # Appends the actual 'data values' to unpacked_data self._add_counts(file, ping_num) if ping_num == 0: # Display information about the file that was loaded in self._print_status() # Compute temperature from unpacked_data[ii]['ancillary][4] self.unpacked_data["temperature"].append( compute_temp(self.unpacked_data["ancillary"][ping_num][4]) ) # compute x tilt from unpacked_data[ii]['ancillary][0] self.unpacked_data["tilt_x"].append( compute_tilt( self.unpacked_data["ancillary"][ping_num][0], self.parameters["X_a"], self.parameters["X_b"], self.parameters["X_c"], self.parameters["X_d"], ) ) # Compute y tilt from unpacked_data[ii]['ancillary][1] self.unpacked_data["tilt_y"].append( compute_tilt( self.unpacked_data["ancillary"][ping_num][1], self.parameters["Y_a"], self.parameters["Y_b"], self.parameters["Y_c"], self.parameters["Y_d"], ) ) # Compute cos tilt magnitude from tilt x and y values self.unpacked_data["cos_tilt_mag"].append( math.cos( ( math.sqrt( self.unpacked_data["tilt_x"][ping_num] ** 2 + self.unpacked_data["tilt_y"][ping_num] ** 2 ) ) * math.pi / 180 ) ) # Calculate voltage of main battery pack self.unpacked_data["battery_main"].append( compute_battery( self.unpacked_data["ancillary"][ping_num][2] ) ) # If there is a Tx battery pack self.unpacked_data["battery_tx"].append( compute_battery(self.unpacked_data["ad"][ping_num][0]) ) else: break else: # End of file eof = True ping_num += 1 self._check_uniqueness() self._get_ping_time() # Explicitly cast frequency to a float in accordance with the SONAR-netCDF4 convention self.unpacked_data["frequency"] = self.unpacked_data["frequency"].astype( np.float64 ) @staticmethod def _get_fields(): """Returns the fields contained in each header of the raw file.""" _fields = ( ("profile_flag", "u2"), ("profile_number", "u2"), ("serial_number", "u2"), ("ping_status", "u2"), ("burst_int", "u4"), ("year", "u2"), # Year ("month", "u2"), # Month ("day", "u2"), # Day ("hour", "u2"), # Hour ("minute", "u2"), # Minute ("second", "u2"), # Second ("hundredths", "u2"), # Hundredths of a second ("dig_rate", "u2", 4), # Digitalization rate for each channel ("lockout_index", "u2", 4), # Lockout index for each channel ("num_bins", "u2", 4), # Number of bins for each channel ( "range_samples_per_bin", "u2", 4, ), # Range samples per bin for each channel ("ping_per_profile", "u2"), # Number of pings per profile ("avg_pings", "u2"), # Flag indicating whether the pings average in time ("num_acq_pings", "u2"), # Pings acquired in the burst ("ping_period", "u2"), # Ping period in seconds ("first_ping", "u2"), ("last_ping", "u2"), ( "data_type", "u1", 4, ), # Datatype for each channel 1=Avg unpacked_data (5bytes), 0=raw (2bytes) ("data_error", "u2"), # Error number is an error occurred ("phase", "u1"), # Phase number used to acquire this profile ("overrun", "u1"), # 1 if an overrun occurred ("num_chan", "u1"), # 1, 2, 3, or 4 ("gain", "u1", 4), # gain channel 1-4 ("spare_chan", "u1"), # spare channel ("pulse_length", "u2", 4), # Pulse length chan 1-4 uS ("board_num", "u2", 4), # The board the data came from channel 1-4 ("frequency", "u2", 4), # frequency for channel 1-4 in kHz ( "sensor_flag", "u2", ), # Flag indicating if pressure sensor or temperature sensor is available ("ancillary", "u2", 5), # Tilt-X, Y, Battery, Pressure, Temperature ("ad", "u2", 2), # AD channel 6 and 7 ) return _fields def _print_status(self): """Prints message to console giving information about the raw file being parsed.""" filename = os.path.basename(self.source_file) timestamp = dt( self.unpacked_data["year"][0], self.unpacked_data["month"][0], self.unpacked_data["day"][0], self.unpacked_data["hour"][0], self.unpacked_data["minute"][0], int( self.unpacked_data["second"][0] + self.unpacked_data["hundredths"][0] / 100 ), ) timestr = timestamp.strftime("%Y-%b-%d %H:%M:%S") pathstr, xml_name = os.path.split(self.xml_path) print( f"{dt.now().strftime("%H:%M:%S")} parsing file {filename} with {xml_name}, " f"time of first ping: {timestr}" ) def _split_header(self, raw, header_unpacked): """Splits the header information into a dictionary. Modifies self.unpacked_data Parameters ---------- raw open binary file header_unpacked output of struct unpack of raw file Returns ------- True or False depending on whether the unpacking was successful """ FILE_TYPE = 64770 # Instrument specific constant fields = self._get_fields() if ( header_unpacked[0] != FILE_TYPE ): # first field should match hard-coded FILE_TYPE from manufacturer check_eof = raw.read(1) if check_eof: print("Error: Unknown file type") return False header_byte_cnt = 0 # fields with num_freq data still takes 4 bytes, # the extra bytes contain random numbers firmware_freq_len = 4 field_w_freq = ( "dig_rate", "lockout_index", "num_bins", "range_samples_per_bin", # fields with num_freq data "data_type", "gain", "pulse_length", "board_num", "frequency", ) for field in fields: if field[0] in field_w_freq: # fields with num_freq data self.unpacked_data[field[0]].append( header_unpacked[ header_byte_cnt : header_byte_cnt + self.parameters["num_freq"] ] ) header_byte_cnt += firmware_freq_len elif len(field) == 3: # other longer fields ('ancillary' and 'ad') self.unpacked_data[field[0]].append( header_unpacked[header_byte_cnt : header_byte_cnt + field[2]] ) header_byte_cnt += field[2] else: self.unpacked_data[field[0]].append(header_unpacked[header_byte_cnt]) header_byte_cnt += 1 return True def _add_counts(self, raw, ping_num): """Unpacks the echosounder raw data. Modifies self.unpacked_data.""" vv_tmp = [[]] * self.unpacked_data["num_chan"][ping_num] for freq_ch in range(self.unpacked_data["num_chan"][ping_num]): counts_byte_size = self.unpacked_data["num_bins"][ping_num][freq_ch] if self.unpacked_data["data_type"][ping_num][freq_ch]: if self.unpacked_data["avg_pings"][ ping_num ]: # if pings are averaged over time divisor = ( self.unpacked_data["ping_per_profile"][ping_num] * self.unpacked_data["range_samples_per_bin"][ping_num][freq_ch] ) else: divisor = self.unpacked_data["range_samples_per_bin"][ping_num][ freq_ch ] ls = unpack( ">" + "I" * counts_byte_size, raw.read(counts_byte_size * 4) ) # Linear sum lso = unpack( ">" + "B" * counts_byte_size, raw.read(counts_byte_size * 1) ) # linear sum overflow v = (np.array(ls) + np.array(lso) * 4294967295) / divisor v = (np.log10(v) - 2.5) * (8 * 65535) * self.parameters["DS"][freq_ch] v[np.isinf(v)] = 0 vv_tmp[freq_ch] = v else: counts_chunk = raw.read(counts_byte_size * 2) counts_unpacked = unpack(">" + "H" * counts_byte_size, counts_chunk) vv_tmp[freq_ch] = counts_unpacked self.unpacked_data["counts"].append(vv_tmp) def _check_uniqueness(self): """Check for ping-by-ping consistency of sampling parameters and reduce if identical.""" if not self.unpacked_data: self.parse_raw() if ( np.array(self.unpacked_data["profile_flag"]).size != 1 ): # Only check uniqueness once. # fields with num_freq data field_w_freq = ( "dig_rate", "lockout_index", "num_bins", "range_samples_per_bin", "data_type", "gain", "pulse_length", "board_num", "frequency", ) # fields to reduce size if the same for all pings field_include = ( "profile_flag", "serial_number", "burst_int", "ping_per_profile", "avg_pings", "ping_period", "phase", "num_chan", "spare_chan", ) for field in field_w_freq: uniq = np.unique(self.unpacked_data[field], axis=0) if uniq.shape[0] == 1: self.unpacked_data[field] = uniq.squeeze() else: raise ValueError( f"Header value {field} is not constant for each ping" ) for field in field_include: uniq = np.unique(self.unpacked_data[field]) if uniq.shape[0] == 1: self.unpacked_data[field] = uniq.squeeze() else: raise ValueError( f"Header value {field} is not constant for each ping" ) def _get_ping_time(self): """Assemble ping time from parsed values.""" if not self.unpacked_data: self.parse_raw() ping_time = [] for ping_num, year in enumerate(self.unpacked_data["year"]): ping_time.append( np.datetime64( dt( year, self.unpacked_data["month"][ping_num], self.unpacked_data["day"][ping_num], self.unpacked_data["hour"][ping_num], self.unpacked_data["minute"][ping_num], int( self.unpacked_data["second"][ping_num] + self.unpacked_data["hundredths"][ping_num] / 100 ), ).replace(tzinfo=None), "[ms]", ) ) self.ping_time = ping_time @staticmethod def _calc_Sv_offset(f, pulse_length): """Calculate the compensation factor for Sv calculation.""" # TODO: this method seems should be in echopype.process if f > 38000: if pulse_length == 300: return 1.1 elif pulse_length == 500: return 0.8 elif pulse_length == 700: return 0.5 elif pulse_length == 900: return 0.3 elif pulse_length == 1000: return 0.3 else: if pulse_length == 500: return 1.1 elif pulse_length == 1000: return 0.7
import math import os import xml.dom.minidom from collections import defaultdict from datetime import datetime as dt from struct import unpack import fsspec import numpy as np from .parse_base import ParseBase FILENAME_DATETIME_AZFP = "\\w+.01A" class ParseAZFP(ParseBase): """Class for converting data from ASL Environmental Sciences AZFP echosounder.""" def __init__(self, file, params, storage_options={}): super().__init__(file, storage_options) # Parent class attributes # regex pattern used to grab datetime embedded in filename self.timestamp_pattern = FILENAME_DATETIME_AZFP self.xml_path = params # Class attributes self.parameters = dict() self.unpacked_data = defaultdict(list) self.sonar_type = "AZFP" def load_AZFP_xml(self): """Parse XML file to get params for reading AZFP data.""" """Parses the AZFP XML file. """ def get_value_by_tag_name(tag_name, element=0): """Returns the value in an XML tag given the tag name and the number of occurrences.""" return px.getElementsByTagName(tag_name)[element].childNodes[0].data # TODO: consider writing a ParamAZFPxml class for storing parameters xmlmap = fsspec.get_mapper(self.xml_path, **self.storage_options) px = xml.dom.minidom.parse(xmlmap.fs.open(xmlmap.root)) int_params = { "NumFreq": "num_freq", "SerialNumber": "serial_number", "BurstInterval": "burst_interval", "PingsPerBurst": "pings_per_burst", "AverageBurstPings": "average_burst_pings", "SensorsFlag": "sensors_flag", } float_params = [ "ka", "kb", "kc", "A", "B", "C", # Temperature coeffs "X_a", "X_b", "X_c", "X_d", "Y_a", "Y_b", "Y_c", "Y_d", ] # Tilt coeffs] freq_params = { "RangeSamples": "range_samples", "RangeAveragingSamples": "range_averaging_samples", "DigRate": "dig_rate", "LockOutIndex": "lockout_index", "Gain": "gain", "PulseLen": "pulse_length", "DS": "DS", "EL": "EL", "TVR": "TVR", "VTX0": "VTX", "BP": "BP", } # Retreive integer parameters from the xml file for old_name, new_name in int_params.items(): self.parameters[new_name] = int(get_value_by_tag_name(old_name)) # Retreive floating point parameters from the xml file for param in float_params: self.parameters[param] = float(get_value_by_tag_name(param)) # Retrieve frequency dependent parameters from the xml file for old_name, new_name in freq_params.items(): self.parameters[new_name] = [ float(get_value_by_tag_name(old_name, ch)) for ch in range(self.parameters["num_freq"]) ] def parse_raw(self): """Parse raw data file from AZFP echosounder. Parameters ---------- raw : list raw filename """ # Start of computation subfunctions def compute_temp(counts): """ Returns the temperature in celsius given from xml data and the counts from ancillary """ v_in = 2.5 * (counts / 65535) R = (self.parameters["ka"] + self.parameters["kb"] * v_in) / ( self.parameters["kc"] - v_in ) # fmt: off T = 1 / ( self.parameters["A"] + self.parameters["B"] * (math.log(R)) + self.parameters["C"] * (math.log(R) ** 3) ) - 273 # fmt: on return T def compute_tilt(N, a, b, c, d): return a + b * N + c * N ** 2 + d * N ** 3 def compute_battery(N): USL5_BAT_CONSTANT = (2.5 / 65536.0) * (86.6 + 475.0) / 86.6 return N * USL5_BAT_CONSTANT # Instrument specific constants HEADER_SIZE = 124 HEADER_FORMAT = ( ">HHHHIHHHHHHHHHHHHHHHHHHHHHHHHHHHHHBBBBHBBBBBBBBHHHHHHHHHHHHHHHHHHHH" ) # Read xml file into dict self.load_AZFP_xml() fmap = fsspec.get_mapper(self.source_file, **self.storage_options) with fmap.fs.open(fmap.root, "rb") as file: ping_num = 0 eof = False while not eof: header_chunk = file.read(HEADER_SIZE) if header_chunk: header_unpacked = unpack(HEADER_FORMAT, header_chunk) # Reading will stop if the file contains an unexpected flag if self._split_header(file, header_unpacked): # Appends the actual 'data values' to unpacked_data self._add_counts(file, ping_num) if ping_num == 0: # Display information about the file that was loaded in self._print_status() # Compute temperature from unpacked_data[ii]['ancillary][4] self.unpacked_data["temperature"].append( compute_temp(self.unpacked_data["ancillary"][ping_num][4]) ) # compute x tilt from unpacked_data[ii]['ancillary][0] self.unpacked_data["tilt_x"].append( compute_tilt( self.unpacked_data["ancillary"][ping_num][0], self.parameters["X_a"], self.parameters["X_b"], self.parameters["X_c"], self.parameters["X_d"], ) ) # Compute y tilt from unpacked_data[ii]['ancillary][1] self.unpacked_data["tilt_y"].append( compute_tilt( self.unpacked_data["ancillary"][ping_num][1], self.parameters["Y_a"], self.parameters["Y_b"], self.parameters["Y_c"], self.parameters["Y_d"], ) ) # Compute cos tilt magnitude from tilt x and y values self.unpacked_data["cos_tilt_mag"].append( math.cos( ( math.sqrt( self.unpacked_data["tilt_x"][ping_num] ** 2 + self.unpacked_data["tilt_y"][ping_num] ** 2 ) ) * math.pi / 180 ) ) # Calculate voltage of main battery pack self.unpacked_data["battery_main"].append( compute_battery( self.unpacked_data["ancillary"][ping_num][2] ) ) # If there is a Tx battery pack self.unpacked_data["battery_tx"].append( compute_battery(self.unpacked_data["ad"][ping_num][0]) ) else: break else: # End of file eof = True ping_num += 1 self._check_uniqueness() self._get_ping_time() # Explicitly cast frequency to a float in accordance with the SONAR-netCDF4 convention self.unpacked_data["frequency"] = self.unpacked_data["frequency"].astype( np.float64 ) @staticmethod def _get_fields(): """Returns the fields contained in each header of the raw file.""" _fields = ( ("profile_flag", "u2"), ("profile_number", "u2"), ("serial_number", "u2"), ("ping_status", "u2"), ("burst_int", "u4"), ("year", "u2"), # Year ("month", "u2"), # Month ("day", "u2"), # Day ("hour", "u2"), # Hour ("minute", "u2"), # Minute ("second", "u2"), # Second ("hundredths", "u2"), # Hundredths of a second ("dig_rate", "u2", 4), # Digitalization rate for each channel ("lockout_index", "u2", 4), # Lockout index for each channel ("num_bins", "u2", 4), # Number of bins for each channel ( "range_samples_per_bin", "u2", 4, ), # Range samples per bin for each channel ("ping_per_profile", "u2"), # Number of pings per profile ("avg_pings", "u2"), # Flag indicating whether the pings average in time ("num_acq_pings", "u2"), # Pings acquired in the burst ("ping_period", "u2"), # Ping period in seconds ("first_ping", "u2"), ("last_ping", "u2"), ( "data_type", "u1", 4, ), # Datatype for each channel 1=Avg unpacked_data (5bytes), 0=raw (2bytes) ("data_error", "u2"), # Error number is an error occurred ("phase", "u1"), # Phase number used to acquire this profile ("overrun", "u1"), # 1 if an overrun occurred ("num_chan", "u1"), # 1, 2, 3, or 4 ("gain", "u1", 4), # gain channel 1-4 ("spare_chan", "u1"), # spare channel ("pulse_length", "u2", 4), # Pulse length chan 1-4 uS ("board_num", "u2", 4), # The board the data came from channel 1-4 ("frequency", "u2", 4), # frequency for channel 1-4 in kHz ( "sensor_flag", "u2", ), # Flag indicating if pressure sensor or temperature sensor is available ("ancillary", "u2", 5), # Tilt-X, Y, Battery, Pressure, Temperature ("ad", "u2", 2), # AD channel 6 and 7 ) return _fields def _print_status(self): """Prints message to console giving information about the raw file being parsed.""" filename = os.path.basename(self.source_file) timestamp = dt( self.unpacked_data["year"][0], self.unpacked_data["month"][0], self.unpacked_data["day"][0], self.unpacked_data["hour"][0], self.unpacked_data["minute"][0], int( self.unpacked_data["second"][0] + self.unpacked_data["hundredths"][0] / 100 ), ) timestr = timestamp.strftime("%Y-%b-%d %H:%M:%S") pathstr, xml_name = os.path.split(self.xml_path) print( f"{dt.now().strftime('%H:%M:%S')} parsing file {filename} with {xml_name}, " f"time of first ping: {timestr}" ) def _split_header(self, raw, header_unpacked): """Splits the header information into a dictionary. Modifies self.unpacked_data Parameters ---------- raw open binary file header_unpacked output of struct unpack of raw file Returns ------- True or False depending on whether the unpacking was successful """ FILE_TYPE = 64770 # Instrument specific constant fields = self._get_fields() if ( header_unpacked[0] != FILE_TYPE ): # first field should match hard-coded FILE_TYPE from manufacturer check_eof = raw.read(1) if check_eof: print("Error: Unknown file type") return False header_byte_cnt = 0 # fields with num_freq data still takes 4 bytes, # the extra bytes contain random numbers firmware_freq_len = 4 field_w_freq = ( "dig_rate", "lockout_index", "num_bins", "range_samples_per_bin", # fields with num_freq data "data_type", "gain", "pulse_length", "board_num", "frequency", ) for field in fields: if field[0] in field_w_freq: # fields with num_freq data self.unpacked_data[field[0]].append( header_unpacked[ header_byte_cnt : header_byte_cnt + self.parameters["num_freq"] ] ) header_byte_cnt += firmware_freq_len elif len(field) == 3: # other longer fields ('ancillary' and 'ad') self.unpacked_data[field[0]].append( header_unpacked[header_byte_cnt : header_byte_cnt + field[2]] ) header_byte_cnt += field[2] else: self.unpacked_data[field[0]].append(header_unpacked[header_byte_cnt]) header_byte_cnt += 1 return True def _add_counts(self, raw, ping_num): """Unpacks the echosounder raw data. Modifies self.unpacked_data.""" vv_tmp = [[]] * self.unpacked_data["num_chan"][ping_num] for freq_ch in range(self.unpacked_data["num_chan"][ping_num]): counts_byte_size = self.unpacked_data["num_bins"][ping_num][freq_ch] if self.unpacked_data["data_type"][ping_num][freq_ch]: if self.unpacked_data["avg_pings"][ ping_num ]: # if pings are averaged over time divisor = ( self.unpacked_data["ping_per_profile"][ping_num] * self.unpacked_data["range_samples_per_bin"][ping_num][freq_ch] ) else: divisor = self.unpacked_data["range_samples_per_bin"][ping_num][ freq_ch ] ls = unpack( ">" + "I" * counts_byte_size, raw.read(counts_byte_size * 4) ) # Linear sum lso = unpack( ">" + "B" * counts_byte_size, raw.read(counts_byte_size * 1) ) # linear sum overflow v = (np.array(ls) + np.array(lso) * 4294967295) / divisor v = (np.log10(v) - 2.5) * (8 * 65535) * self.parameters["DS"][freq_ch] v[np.isinf(v)] = 0 vv_tmp[freq_ch] = v else: counts_chunk = raw.read(counts_byte_size * 2) counts_unpacked = unpack(">" + "H" * counts_byte_size, counts_chunk) vv_tmp[freq_ch] = counts_unpacked self.unpacked_data["counts"].append(vv_tmp) def _check_uniqueness(self): """Check for ping-by-ping consistency of sampling parameters and reduce if identical.""" if not self.unpacked_data: self.parse_raw() if ( np.array(self.unpacked_data["profile_flag"]).size != 1 ): # Only check uniqueness once. # fields with num_freq data field_w_freq = ( "dig_rate", "lockout_index", "num_bins", "range_samples_per_bin", "data_type", "gain", "pulse_length", "board_num", "frequency", ) # fields to reduce size if the same for all pings field_include = ( "profile_flag", "serial_number", "burst_int", "ping_per_profile", "avg_pings", "ping_period", "phase", "num_chan", "spare_chan", ) for field in field_w_freq: uniq = np.unique(self.unpacked_data[field], axis=0) if uniq.shape[0] == 1: self.unpacked_data[field] = uniq.squeeze() else: raise ValueError( f"Header value {field} is not constant for each ping" ) for field in field_include: uniq = np.unique(self.unpacked_data[field]) if uniq.shape[0] == 1: self.unpacked_data[field] = uniq.squeeze() else: raise ValueError( f"Header value {field} is not constant for each ping" ) def _get_ping_time(self): """Assemble ping time from parsed values.""" if not self.unpacked_data: self.parse_raw() ping_time = [] for ping_num, year in enumerate(self.unpacked_data["year"]): ping_time.append( np.datetime64( dt( year, self.unpacked_data["month"][ping_num], self.unpacked_data["day"][ping_num], self.unpacked_data["hour"][ping_num], self.unpacked_data["minute"][ping_num], int( self.unpacked_data["second"][ping_num] + self.unpacked_data["hundredths"][ping_num] / 100 ), ).replace(tzinfo=None), "[ms]", ) ) self.ping_time = ping_time @staticmethod def _calc_Sv_offset(f, pulse_length): """Calculate the compensation factor for Sv calculation.""" # TODO: this method seems should be in echopype.process if f > 38000: if pulse_length == 300: return 1.1 elif pulse_length == 500: return 0.8 elif pulse_length == 700: return 0.5 elif pulse_length == 900: return 0.3 elif pulse_length == 1000: return 0.3 else: if pulse_length == 500: return 1.1 elif pulse_length == 1000: return 0.7
# -*- coding: utf-8 -*- """ This module provides a wrapper around the VSO API. """ import os import re import cgi import socket import datetime import warnings import itertools import inspect from functools import partial from collections import defaultdict from urllib.error import URLError, HTTPError from urllib.request import urlopen import zeep from parfive import Downloader, Results from zeep.helpers import serialize_object import astropy.units as u from astropy.table import QTable as Table from sunpy import config from sunpy.net.attr import and_ from sunpy.net.base_client import BaseClient, BaseQueryResponse from sunpy.net.vso import attrs from sunpy.net.vso.attrs import _TIMEFORMAT as TIMEFORMAT from sunpy.net.vso.attrs import _walker as walker from sunpy.time import TimeRange, parse_time from sunpy.util.decorators import deprecated from sunpy.util.exceptions import SunpyUserWarning from sunpy.util.net import slugify from .. import _attrs as core_attrs from .zeep_plugins import SunPyLoggingZeepPlugin from .exceptions import * TIME_FORMAT = config.get("general", "time_format") DEFAULT_URL_PORT = [{'url': 'http://docs.virtualsolar.org/WSDL/VSOi_rpc_literal.wsdl', 'port': 'nsoVSOi'}, {'url': 'https://sdac.virtualsolar.org/API/VSOi_rpc_literal.wsdl', 'port': 'sdacVSOi'}] RANGE = re.compile(r'(\d+)(\s*-\s*(\d+))?(\s*([a-zA-Z]+))?') class _Str(str): """ Subclass of string that contains a meta attribute for the record_item associated with the file. """ pass # ---------------------------------------- def _parse_waverange(string): min_, max_, unit = RANGE.match(string).groups()[::2] return { 'wave_wavemin': min_, 'wave_wavemax': min_ if max_ is None else max_, 'wave_waveunit': 'Angstrom' if unit is None else unit, } def _parse_date(string): start, end = string.split(' - ') return {'time_start': start.strip(), 'time_end': end.strip()} def iter_records(response): for prov_item in response.provideritem: if not hasattr(prov_item, 'record') or not prov_item.record: continue yield from prov_item.record.recorditem def iter_errors(response): for prov_item in response.provideritem: if not hasattr(prov_item, 'record') or not prov_item.record: yield prov_item def check_connection(url): try: return urlopen(url).getcode() == 200 except (socket.error, socket.timeout, HTTPError, URLError) as e: warnings.warn(f"Connection to {url} failed with error {e}. Retrying with different url and port.", SunpyUserWarning) return None def get_online_vso_url(): """ Return the first VSO url and port combination that is online. """ for mirror in DEFAULT_URL_PORT: if check_connection(mirror['url']): return mirror def build_client(url=None, port_name=None, **kwargs): """ Construct a `zeep.Client` object to connect to VSO. Parameters ---------- url : `str` The URL to connect to. port_name : `str` The "port" to use. kwargs : `dict` All extra keyword arguments are passed to `zeep.Client`. Returns ------- `zeep.Client` """ if url is None and port_name is None: mirror = get_online_vso_url() if mirror is None: raise ConnectionError("No online VSO mirrors could be found.") url = mirror['url'] port_name = mirror['port'] elif url and port_name: if not check_connection(url): raise ConnectionError(f"Can't connect to url {url}") else: raise ValueError("Both url and port_name must be specified if either is.") if "plugins" not in kwargs: kwargs["plugins"] = [SunPyLoggingZeepPlugin()] client = zeep.Client(url, port_name=port_name, **kwargs) client.set_ns_prefix('VSO', 'http://virtualsolar.org/VSO/VSOi') return client class QueryResponse(BaseQueryResponse): """ A container for VSO Records returned from VSO Searches. """ def __init__(self, lst, queryresult=None): super().__init__() self._data = lst self.queryresult = queryresult self.errors = [] self._client = VSOClient() def __getitem__(self, item): # Always index so a list comes back if isinstance(item, int): item = slice(item, item+1) return type(self)(self._data[item], queryresult=self.queryresult) def __len__(self): return len(self._data) def __iter__(self): for block in self._data: yield block @property def blocks(self): return self._data @property def client(self): return self._client @client.setter def client(self, client): self._client = client def search(self, *query): """ Furtherly reduce the query response by matching it against another query, e.g. response.search(attrs.Instrument('aia')). """ query = and_(*query) return QueryResponse( attrs._filter_results(query, self), self.queryresult ) @classmethod def create(cls, queryresult): return cls(list(iter_records(queryresult)), queryresult) def total_size(self): """ Total size of data in KB. May be less than the actual size because of inaccurate data providers. """ # Warn about -1 values? return sum(record.size for record in self if record.size > 0) def time_range(self): """ Return total time-range all records span across. """ return TimeRange(min(record.time.start for record in self if record.time.start is not None), max(record.time.end for record in self if record.time.end is not None)) def build_table(self): """ Create a human readable table. Returns ------- table : `astropy.table.QTable` """ keywords = ['Start Time', 'End Time', 'Source', 'Instrument', 'Type', 'Wavelength'] record_items = {} for key in keywords: record_items[key] = [] def validate_time(time): # Handle if the time is None when coming back from VSO if time is None: return ['None'] if record.time.start is not None: return [parse_time(time).strftime(TIME_FORMAT)] else: return ['N/A'] for record in self: record_items['Start Time'].append(validate_time(record.time.start)) record_items['End Time'].append(validate_time(record.time.end)) record_items['Source'].append(str(record.source)) record_items['Instrument'].append(str(record.instrument)) record_items['Type'].append(str(record.extent.type) if record.extent.type is not None else ['N/A']) # If we have a start and end Wavelength, make a quantity if hasattr(record, 'wave') and record.wave.wavemin and record.wave.wavemax: unit = record.wave.waveunit # Convert this so astropy units parses it correctly if unit == "kev": unit = "keV" record_items['Wavelength'].append(u.Quantity([float(record.wave.wavemin), float(record.wave.wavemax)], unit=unit)) # If not save None else: record_items['Wavelength'].append(None) # If we have no wavelengths for the whole list, drop the col if all([a is None for a in record_items['Wavelength']]): record_items.pop('Wavelength') keywords.remove('Wavelength') else: # Make whole column a quantity try: with u.set_enabled_equivalencies(u.spectral()): record_items['Wavelength'] = u.Quantity(record_items['Wavelength']) # If we have mixed units or some Nones just represent as strings except (u.UnitConversionError, TypeError): record_items['Wavelength'] = [str(a) for a in record_items['Wavelength']] return Table(record_items)[keywords] def add_error(self, exception): self.errors.append(exception) def response_block_properties(self): """ Returns a set of class attributes on all the response blocks. Returns ------- s : `set` List of strings, containing attribute names in the response blocks. """ s = {a if not a.startswith('_') else None for a in dir(self[0])} for resp in self[1:]: s = s.intersection({a if not a.startswith('_') else None for a in dir(resp)}) s.remove(None) return s class VSOClient(BaseClient): """ VSO Client Parameters ---------- url : `str`, optional The VSO url to use. If not specified will use the first online known URL. port : `str`, optional The VSO port name to use. If not specified will use the first online known URL. api : `zeep.Client`, optional The `zeep.Client` instance to use for interacting with the VSO. If not specified one will be created. """ method_order = [ 'URL-FILE_Rice', 'URL-FILE', 'URL-packaged', 'URL-TAR_GZ', 'URL-ZIP', 'URL-TAR', ] def __init__(self, url=None, port=None, api=None): if not isinstance(api, zeep.Client): api = build_client(url, port) if api is None: raise ConnectionError("Cannot find an online VSO mirror.") self.api = api def make(self, atype, **kwargs): """ Create a new SOAP object. """ obj = self.api.get_type(f"VSO:{atype}") return obj(**kwargs) def search(self, *query): """ Query data from the VSO with the new API. Takes a variable number of attributes as parameter, which are chained together using AND. The new query language allows complex queries to be easily formed. Examples -------- Query all data from eit or aia between 2010-01-01T00:00 and 2010-01-01T01:00. >>> from datetime import datetime >>> from sunpy.net import vso, attrs as a >>> client = vso.VSOClient() # doctest: +REMOTE_DATA >>> client.search( ... a.Time(datetime(2010, 1, 1), datetime(2010, 1, 1, 1)), ... a.Instrument('eit') | a.Instrument('aia')) # doctest: +REMOTE_DATA <sunpy.net.vso.vso.QueryResponse object at ...> Start Time [1] End Time [1] Source ... Type Wavelength [2] ... Angstrom ------------------- ------------------- ------ ... -------- -------------- 2010-01-01 00:00:08 2010-01-01 00:00:20 SOHO ... FULLDISK 195.0 .. 195.0 2010-01-01 00:12:08 2010-01-01 00:12:20 SOHO ... FULLDISK 195.0 .. 195.0 2010-01-01 00:24:10 2010-01-01 00:24:22 SOHO ... FULLDISK 195.0 .. 195.0 2010-01-01 00:36:08 2010-01-01 00:36:20 SOHO ... FULLDISK 195.0 .. 195.0 2010-01-01 00:48:09 2010-01-01 00:48:21 SOHO ... FULLDISK 195.0 .. 195.0 Returns ------- out : :py:class:`QueryResult` (enhanced list) Matched items. Return value is of same type as the one of :py:meth:`VSOClient.search`. """ query = and_(*query) QueryRequest = self.api.get_type('VSO:QueryRequest') VSOQueryResponse = self.api.get_type('VSO:QueryResponse') responses = [] for block in walker.create(query, self.api): try: query_response = self.api.service.Query( QueryRequest(block=block) ) for resp in query_response: if resp["error"]: warnings.warn(resp["error"], SunpyUserWarning) responses.append( VSOQueryResponse(query_response) ) except Exception as ex: response = QueryResponse.create(self.merge(responses)) response.add_error(ex) return QueryResponse.create(self.merge(responses)) def merge(self, queryresponses): """ Merge responses into one. """ if len(queryresponses) == 1: return queryresponses[0] fileids = set() providers = {} for queryresponse in queryresponses: for provideritem in queryresponse.provideritem: provider = provideritem.provider if not hasattr(provideritem, 'record'): continue if not hasattr(provideritem.record, 'recorditem'): continue if provideritem.provider not in providers: providers[provider] = provideritem fileids |= { record_item.fileid for record_item in provideritem.record.recorditem } else: for record_item in provideritem.record.recorditem: if record_item.fileid not in fileids: fileids.add(record_item.fileid) providers[provider].record.recorditem.append( record_item ) providers[provider].no_of_records_found += 1 providers[provider].no_of_records_returned += 1 return self.make('QueryResponse', provideritem=list(providers.values())) @staticmethod def mk_filename(pattern, queryresponse, resp, url): """ Generate the best possible (or least-worse) filename for a VSO download. * Use the ``content-disposition`` header. * Use `fileid` to generate a file name if content-disposition fails * If everything else fails use the last segment of the URL and hope. """ name = None if resp: cdheader = resp.headers.get("Content-Disposition", None) if cdheader: value, params = cgi.parse_header(cdheader) name = params.get('filename', "") # Work around https://github.com/sunpy/sunpy/issues/3372 if name.count('"') >= 2: name = name.split('"')[1] if name is None: # Advice from the VSO is to fallback to providerid + fileid # As it's possible multiple providers give the same fileid. # However, I haven't implemented this yet as it would be a breaking # change to the filenames we expect. # I don't know if we still need this bytes check in Python 3 only # land, but I don't dare remove it. if isinstance(queryresponse.fileid, bytes): fileid = queryresponse.fileid.decode("ascii", "ignore") else: fileid = queryresponse.fileid # Some providers make fileid a path # Some also don't specify a file extension, but not a lot we can do # about that. name = fileid.split("/")[-1] # If somehow we have got this far with an empty string, fallback to url segment if not name: name = url.split('/')[-1] # Remove any not-filename appropriate characters name = slugify(name) # If absolutely everything else fails make a filename based on download time if not name: name = f"vso_file_{datetime.datetime.now().strftime("%Y%m%d%H%M%S%f")}" fname = pattern.format(file=name, **serialize_object(queryresponse)) return fname @deprecated("1.0", alternative="sunpy.net.Fido") def query_legacy(self, tstart=None, tend=None, **kwargs): """ Query data from the VSO mocking the IDL API as close as possible. Either tstart and tend or date_start and date_end or date have to be supplied. Parameters ---------- tstart : datetime.datetime Start of the time-range in which records are searched. tend : datetime.datetime Start of the time-range in which records are searched. date : str (start date) - (end date) start_date : datetime the start date end_date : datetime the end date wave : str (min) - (max) (unit) min_wave : str minimum spectral range max_wave : str maximum spectral range unit_wave : str spectral range units (Angstrom, GHz, keV) extent : str VSO 'extent type' ... (FULLDISK, CORONA, LIMB, etc) physobj : str VSO 'physical observable' provider : str VSO ID for the data provider (SDAC, NSO, SHA, MSU, etc) source : str spacecraft or observatory (SOHO, YOHKOH, BBSO, etc) synonyms : spacecraft, observatory instrument : str instrument ID (EIT, SXI-0, SXT, etc) synonyms : telescope, inst detector : str detector ID (C3, EUVI, COR2, etc.) layout : str layout of the data (image, spectrum, time_series, etc.) level : str level of the data product (numeric range, see below) pixels : str number of pixels (numeric range, see below) resolution : str effective resolution (1 = full, 0.5 = 2x2 binned, etc) numeric range, see below. pscale : str pixel scale, in arcseconds (numeric range, see below) near_time : datetime return record closest to the time. See below. sample : int attempt to return only one record per SAMPLE seconds. See below. Numeric Ranges: - May be entered as a string or any numeric type for equality matching - May be a string of the format '(min) - (max)' for range matching - May be a string of the form '(operator) (number)' where operator is one of: lt gt le ge < > <= >= Examples -------- Query all data from eit between 2010-01-01T00:00 and 2010-01-01T01:00. >>> from datetime import datetime >>> from sunpy.net import vso >>> client = vso.VSOClient() # doctest: +SKIP >>> qr = client.query_legacy(datetime(2010, 1, 1), ... datetime(2010, 1, 1, 1), ... instrument='eit') # doctest: +SKIP Returns ------- out : :py:class:`QueryResult` (enhanced list) Matched items. Return value is of same type as the one of :py:class:`VSOClient.search`. """ def sdk(key): return partial(lambda key, value: {key: value}, key) ALIASES = { 'wave_min': sdk('wave_wavemin'), 'wave_max': sdk('wave_wavemax'), 'wave_type': sdk('wave_wavetype'), 'wave_unit': sdk('wave_waveunit'), 'min_wave': sdk('wave_wavemin'), 'max_wave': sdk('wave_wavemax'), 'type_wave': sdk('wave_wavetype'), 'unit_wave': sdk('wave_waveunit'), 'wave': _parse_waverange, 'inst': sdk('instrument'), 'telescope': sdk('instrument'), 'spacecraft': sdk('source'), 'observatory': sdk('source'), 'start_date': sdk('time_start'), 'end_date': sdk('time_end'), 'start': sdk('time_start'), 'end': sdk('time_end'), 'near_time': sdk('time_near'), 'date': _parse_date, 'layout': sdk('datatype'), } if tstart is not None: kwargs.update({'time_start': tstart}) if tend is not None: kwargs.update({'time_end': tend}) QueryRequest = self.api.get_type('VSO:QueryRequest') VSOQueryResponse = self.api.get_type('VSO:QueryResponse') block = self.api.get_type('VSO:QueryRequestBlock')() for key, value in kwargs.items(): for k, v in ALIASES.get(key, sdk(key))(value).items(): if k.startswith('time'): v = parse_time(v).strftime(TIMEFORMAT) attr = k.split('_') lst = attr[-1] rest = attr[:-1] for elem in rest: try: if block[elem] is None: block[elem] = {} block = block[elem] except KeyError: raise ValueError( f"Unexpected argument {key!s}.") if lst in block and block[lst]: raise ValueError( f"Got multiple values for {k!s}.") block[lst] = v return QueryResponse.create(VSOQueryResponse( self.api.service.Query(QueryRequest(block=block)))) @deprecated("1.0") def latest(self): """ Return newest record (limited to last week). """ from datetime import datetime, timedelta return self.query_legacy( datetime.utcnow() - timedelta(7), datetime.utcnow(), time_near=datetime.utcnow() ) def fetch(self, query_response, path=None, methods=None, site=None, progress=True, overwrite=False, downloader=None, wait=True): """ Download data specified in the query_response. Parameters ---------- query_response : sunpy.net.vso.QueryResponse QueryResponse containing the items to be downloaded. path : str Specify where the data is to be downloaded. Can refer to arbitrary fields of the QueryResponseItem (instrument, source, time, ...) via string formatting, moreover the file-name of the file downloaded can be referred to as file, e.g. "{source}/{instrument}/{time.start}/{file}". methods : {list of str} Download methods, defaults to URL-FILE_Rice then URL-FILE. Methods are a concatenation of one PREFIX followed by any number of SUFFIXES i.e. `PREFIX-SUFFIX_SUFFIX2_SUFFIX3`. The full list of `PREFIXES <https://sdac.virtualsolar.org/cgi/show_details?keyword=METHOD_PREFIX>`_ and `SUFFIXES <https://sdac.virtualsolar.org/cgi/show_details?keyword=METHOD_SUFFIX>`_ are listed on the VSO site. site : str There are a number of caching mirrors for SDO and other instruments, some available ones are listed below. =============== ======================================================== NSO National Solar Observatory, Tucson (US) SAO (aka CFA) Smithonian Astronomical Observatory, Harvard U. (US) SDAC (aka GSFC) Solar Data Analysis Center, NASA/GSFC (US) ROB Royal Observatory of Belgium (Belgium) MPS Max Planck Institute for Solar System Research (Germany) UCLan University of Central Lancashire (UK) IAS Institut Aeronautique et Spatial (France) KIS Kiepenheuer-Institut fur Sonnenphysik Germany) NMSU New Mexico State University (US) =============== ======================================================== progress : `bool`, optional If `True` show a progress bar showing how many of the total files have been downloaded. If `False`, no progress bars will be shown at all. overwrite : `bool` or `str`, optional Determine how to handle downloading if a file already exists with the same name. If `False` the file download will be skipped and the path returned to the existing file, if `True` the file will be downloaded and the existing file will be overwritten, if `'unique'` the filename will be modified to be unique. downloader : `parfive.Downloader`, optional The download manager to use. wait : `bool`, optional If `False` ``downloader.download()`` will not be called. Only has any effect if `downloader` is not `None`. Returns ------- out : `parfive.Results` Object that supplies a list of filenames and any errors. Examples -------- >>> files = fetch(qr) # doctest:+SKIP """ if path is None: path = os.path.join(config.get('downloads', 'download_dir'), '{file}') elif isinstance(path, str) and '{file}' not in path: path = os.path.join(path, '{file}') path = os.path.expanduser(path) dl_set = True if not downloader: dl_set = False downloader = Downloader(progress=progress) fileids = VSOClient.by_fileid(query_response) if not fileids: return downloader.download() if wait else Results() # Adding the site parameter to the info info = {} if site is not None: info['site'] = site VSOGetDataResponse = self.api.get_type("VSO:VSOGetDataResponse") data_request = self.make_getdatarequest(query_response, methods, info) data_response = VSOGetDataResponse(self.api.service.GetData(data_request)) err_results = self.download_all(data_response, methods, downloader, path, fileids) if dl_set and not wait: return err_results results = downloader.download() results += err_results results._errors += err_results.errors return results @staticmethod def link(query_response, maps): """ Return list of paths with records associated with them in the meta attribute. """ if not maps: return [] ret = [] for record_item in query_response: try: item = _Str(maps[record_item.fileid]['path']) except KeyError: continue # pylint: disable=W0201 item.meta = record_item ret.append(item) return ret def make_getdatarequest(self, response, methods=None, info=None): """ Make datarequest with methods from response. """ if methods is None: methods = self.method_order + ['URL'] return self.create_getdatarequest( {k: [x.fileid for x in v] for k, v in self.by_provider(response).items()}, methods, info ) def create_getdatarequest(self, maps, methods, info=None): """ Create datarequest from maps mapping data provider to fileids and methods, """ if info is None: info = {} if 'email' not in info: info['email'] = 'sunpy' # For the JSOC provider we need to make a DataRequestItem for each # series, not just one for the whole provider. # Remove JSOC provider items from the map jsoc = maps.pop('JSOC', []) # Make DRIs for everything that's not JSOC one per provider dris = [self.make('DataRequestItem', provider=k, fileiditem={'fileid': v}) for k, v in maps.items()] def series_func(x): """ Extract the series from the fileid. """ return x.split(':')[0] # Sort the JSOC fileids by series # This is a precursor to groupby as recommended by the groupby docs series_sorted = sorted(jsoc, key=series_func) # Iterate over the series and make a DRI for each. # groupby creates an iterator based on a key function, in this case # based on the series (the part before the first ':') for series, fileids in itertools.groupby(series_sorted, key=series_func): dris.append(self.make('DataRequestItem', provider='JSOC', fileiditem={'fileid': list(fileids)})) request = {'method': {'methodtype': methods}, 'info': info, 'datacontainer': {'datarequestitem': dris} } return self.make('VSOGetDataRequest', request=request) # pylint: disable=R0913,R0912 def download_all(self, response, methods, downloader, path, qr, info=None): results = Results() GET_VERSION = [ ('0.8', (5, 8)), ('0.7', (1, 4)), ('0.6', (0, 3)), ] for dresponse in response.getdataresponseitem: for version, (from_, to) in GET_VERSION: if getattr(dresponse, version, '0.6') >= version: break else: results.add_error('', UnknownVersion(dresponse)) continue # If from_ and to are uninitialized, the else block of the loop # continues the outer loop and thus this code is never reached. # pylint: disable=W0631 code = ( dresponse.status[from_:to] if getattr(dresponse, 'status', None) else '200' ) if code == '200': for dataitem in dresponse.getdataitem.dataitem: try: self.download( dresponse.method.methodtype[0], dataitem.url, downloader, path, qr[dataitem.fileiditem.fileid[0]] ) except NoData: results.add_error('', '', DownloadFailed(dresponse)) continue elif code == '300' or code == '412' or code == '405': if code == '300': try: methods = self.multiple_choices( dresponse.method.methodtype, dresponse ) except NoData: results.add_error('', '', MultipleChoices(dresponse)) continue elif code == '412': try: info = self.missing_information( info, dresponse.info ) except NoData: results.add_error('', '', MissingInformation(dresponse)) continue elif code == '405': try: methods = self.unknown_method(dresponse) except NoData: results.add_error('', '', UnknownMethod(dresponse)) continue files = [] for dataitem in dresponse.getdataitem.dataitem: files.extend(dataitem.fileiditem.fileid) request = self.create_getdatarequest( {dresponse.provider: files}, methods, info ) self.download_all( self.api.service.GetData(request), methods, downloader, path, qr, info ) else: results.add_error('', '', UnknownStatus(dresponse)) return results def download(self, method, url, downloader, *args): """ Enqueue a file to be downloaded, extra args are passed to ``mk_filename``""" if method.startswith('URL'): return downloader.enqueue_file(url, filename=partial(self.mk_filename, *args)) raise NoData @staticmethod def by_provider(response): """ Returns a dictionary of provider corresponding to records in the response. """ map_ = defaultdict(list) for record in response: map_[record.provider].append(record) return map_ @staticmethod def by_fileid(response): """ Returns a dictionary of fileids corresponding to records in the response. """ return { record.fileid: record for record in response } # pylint: disable=W0613 def multiple_choices(self, choices, response): """ Override to pick between multiple download choices. """ for elem in self.method_order: if elem in choices: return [elem] raise NoData # pylint: disable=W0613 def missing_information(self, info, field): """ Override to provide missing information. """ raise NoData # pylint: disable=W0613 def unknown_method(self, response): """ Override to pick a new method if the current one is unknown. """ raise NoData @classmethod def _can_handle_query(cls, *query): required = {core_attrs.Time} # Get all classes in core_attrs and attrs optional = {value for (name, value) in inspect.getmembers(core_attrs) if name in core_attrs.__all__} optional.update(value for (name, value) in inspect.getmembers(attrs) if name in attrs.__all__) return cls.check_attr_types_in_query(query, required, optional) @classmethod def _attrs_module(cls): return 'vso', 'sunpy.net.vso.attrs' def __del__(self): self.api.transport.session.close()
# -*- coding: utf-8 -*- """ This module provides a wrapper around the VSO API. """ import os import re import cgi import socket import datetime import warnings import itertools import inspect from functools import partial from collections import defaultdict from urllib.error import URLError, HTTPError from urllib.request import urlopen import zeep from parfive import Downloader, Results from zeep.helpers import serialize_object import astropy.units as u from astropy.table import QTable as Table from sunpy import config from sunpy.net.attr import and_ from sunpy.net.base_client import BaseClient, BaseQueryResponse from sunpy.net.vso import attrs from sunpy.net.vso.attrs import _TIMEFORMAT as TIMEFORMAT from sunpy.net.vso.attrs import _walker as walker from sunpy.time import TimeRange, parse_time from sunpy.util.decorators import deprecated from sunpy.util.exceptions import SunpyUserWarning from sunpy.util.net import slugify from .. import _attrs as core_attrs from .zeep_plugins import SunPyLoggingZeepPlugin from .exceptions import * TIME_FORMAT = config.get("general", "time_format") DEFAULT_URL_PORT = [{'url': 'http://docs.virtualsolar.org/WSDL/VSOi_rpc_literal.wsdl', 'port': 'nsoVSOi'}, {'url': 'https://sdac.virtualsolar.org/API/VSOi_rpc_literal.wsdl', 'port': 'sdacVSOi'}] RANGE = re.compile(r'(\d+)(\s*-\s*(\d+))?(\s*([a-zA-Z]+))?') class _Str(str): """ Subclass of string that contains a meta attribute for the record_item associated with the file. """ pass # ---------------------------------------- def _parse_waverange(string): min_, max_, unit = RANGE.match(string).groups()[::2] return { 'wave_wavemin': min_, 'wave_wavemax': min_ if max_ is None else max_, 'wave_waveunit': 'Angstrom' if unit is None else unit, } def _parse_date(string): start, end = string.split(' - ') return {'time_start': start.strip(), 'time_end': end.strip()} def iter_records(response): for prov_item in response.provideritem: if not hasattr(prov_item, 'record') or not prov_item.record: continue yield from prov_item.record.recorditem def iter_errors(response): for prov_item in response.provideritem: if not hasattr(prov_item, 'record') or not prov_item.record: yield prov_item def check_connection(url): try: return urlopen(url).getcode() == 200 except (socket.error, socket.timeout, HTTPError, URLError) as e: warnings.warn(f"Connection to {url} failed with error {e}. Retrying with different url and port.", SunpyUserWarning) return None def get_online_vso_url(): """ Return the first VSO url and port combination that is online. """ for mirror in DEFAULT_URL_PORT: if check_connection(mirror['url']): return mirror def build_client(url=None, port_name=None, **kwargs): """ Construct a `zeep.Client` object to connect to VSO. Parameters ---------- url : `str` The URL to connect to. port_name : `str` The "port" to use. kwargs : `dict` All extra keyword arguments are passed to `zeep.Client`. Returns ------- `zeep.Client` """ if url is None and port_name is None: mirror = get_online_vso_url() if mirror is None: raise ConnectionError("No online VSO mirrors could be found.") url = mirror['url'] port_name = mirror['port'] elif url and port_name: if not check_connection(url): raise ConnectionError(f"Can't connect to url {url}") else: raise ValueError("Both url and port_name must be specified if either is.") if "plugins" not in kwargs: kwargs["plugins"] = [SunPyLoggingZeepPlugin()] client = zeep.Client(url, port_name=port_name, **kwargs) client.set_ns_prefix('VSO', 'http://virtualsolar.org/VSO/VSOi') return client class QueryResponse(BaseQueryResponse): """ A container for VSO Records returned from VSO Searches. """ def __init__(self, lst, queryresult=None): super().__init__() self._data = lst self.queryresult = queryresult self.errors = [] self._client = VSOClient() def __getitem__(self, item): # Always index so a list comes back if isinstance(item, int): item = slice(item, item+1) return type(self)(self._data[item], queryresult=self.queryresult) def __len__(self): return len(self._data) def __iter__(self): for block in self._data: yield block @property def blocks(self): return self._data @property def client(self): return self._client @client.setter def client(self, client): self._client = client def search(self, *query): """ Furtherly reduce the query response by matching it against another query, e.g. response.search(attrs.Instrument('aia')). """ query = and_(*query) return QueryResponse( attrs._filter_results(query, self), self.queryresult ) @classmethod def create(cls, queryresult): return cls(list(iter_records(queryresult)), queryresult) def total_size(self): """ Total size of data in KB. May be less than the actual size because of inaccurate data providers. """ # Warn about -1 values? return sum(record.size for record in self if record.size > 0) def time_range(self): """ Return total time-range all records span across. """ return TimeRange(min(record.time.start for record in self if record.time.start is not None), max(record.time.end for record in self if record.time.end is not None)) def build_table(self): """ Create a human readable table. Returns ------- table : `astropy.table.QTable` """ keywords = ['Start Time', 'End Time', 'Source', 'Instrument', 'Type', 'Wavelength'] record_items = {} for key in keywords: record_items[key] = [] def validate_time(time): # Handle if the time is None when coming back from VSO if time is None: return ['None'] if record.time.start is not None: return [parse_time(time).strftime(TIME_FORMAT)] else: return ['N/A'] for record in self: record_items['Start Time'].append(validate_time(record.time.start)) record_items['End Time'].append(validate_time(record.time.end)) record_items['Source'].append(str(record.source)) record_items['Instrument'].append(str(record.instrument)) record_items['Type'].append(str(record.extent.type) if record.extent.type is not None else ['N/A']) # If we have a start and end Wavelength, make a quantity if hasattr(record, 'wave') and record.wave.wavemin and record.wave.wavemax: unit = record.wave.waveunit # Convert this so astropy units parses it correctly if unit == "kev": unit = "keV" record_items['Wavelength'].append(u.Quantity([float(record.wave.wavemin), float(record.wave.wavemax)], unit=unit)) # If not save None else: record_items['Wavelength'].append(None) # If we have no wavelengths for the whole list, drop the col if all([a is None for a in record_items['Wavelength']]): record_items.pop('Wavelength') keywords.remove('Wavelength') else: # Make whole column a quantity try: with u.set_enabled_equivalencies(u.spectral()): record_items['Wavelength'] = u.Quantity(record_items['Wavelength']) # If we have mixed units or some Nones just represent as strings except (u.UnitConversionError, TypeError): record_items['Wavelength'] = [str(a) for a in record_items['Wavelength']] return Table(record_items)[keywords] def add_error(self, exception): self.errors.append(exception) def response_block_properties(self): """ Returns a set of class attributes on all the response blocks. Returns ------- s : `set` List of strings, containing attribute names in the response blocks. """ s = {a if not a.startswith('_') else None for a in dir(self[0])} for resp in self[1:]: s = s.intersection({a if not a.startswith('_') else None for a in dir(resp)}) s.remove(None) return s class VSOClient(BaseClient): """ VSO Client Parameters ---------- url : `str`, optional The VSO url to use. If not specified will use the first online known URL. port : `str`, optional The VSO port name to use. If not specified will use the first online known URL. api : `zeep.Client`, optional The `zeep.Client` instance to use for interacting with the VSO. If not specified one will be created. """ method_order = [ 'URL-FILE_Rice', 'URL-FILE', 'URL-packaged', 'URL-TAR_GZ', 'URL-ZIP', 'URL-TAR', ] def __init__(self, url=None, port=None, api=None): if not isinstance(api, zeep.Client): api = build_client(url, port) if api is None: raise ConnectionError("Cannot find an online VSO mirror.") self.api = api def make(self, atype, **kwargs): """ Create a new SOAP object. """ obj = self.api.get_type(f"VSO:{atype}") return obj(**kwargs) def search(self, *query): """ Query data from the VSO with the new API. Takes a variable number of attributes as parameter, which are chained together using AND. The new query language allows complex queries to be easily formed. Examples -------- Query all data from eit or aia between 2010-01-01T00:00 and 2010-01-01T01:00. >>> from datetime import datetime >>> from sunpy.net import vso, attrs as a >>> client = vso.VSOClient() # doctest: +REMOTE_DATA >>> client.search( ... a.Time(datetime(2010, 1, 1), datetime(2010, 1, 1, 1)), ... a.Instrument('eit') | a.Instrument('aia')) # doctest: +REMOTE_DATA <sunpy.net.vso.vso.QueryResponse object at ...> Start Time [1] End Time [1] Source ... Type Wavelength [2] ... Angstrom ------------------- ------------------- ------ ... -------- -------------- 2010-01-01 00:00:08 2010-01-01 00:00:20 SOHO ... FULLDISK 195.0 .. 195.0 2010-01-01 00:12:08 2010-01-01 00:12:20 SOHO ... FULLDISK 195.0 .. 195.0 2010-01-01 00:24:10 2010-01-01 00:24:22 SOHO ... FULLDISK 195.0 .. 195.0 2010-01-01 00:36:08 2010-01-01 00:36:20 SOHO ... FULLDISK 195.0 .. 195.0 2010-01-01 00:48:09 2010-01-01 00:48:21 SOHO ... FULLDISK 195.0 .. 195.0 Returns ------- out : :py:class:`QueryResult` (enhanced list) Matched items. Return value is of same type as the one of :py:meth:`VSOClient.search`. """ query = and_(*query) QueryRequest = self.api.get_type('VSO:QueryRequest') VSOQueryResponse = self.api.get_type('VSO:QueryResponse') responses = [] for block in walker.create(query, self.api): try: query_response = self.api.service.Query( QueryRequest(block=block) ) for resp in query_response: if resp["error"]: warnings.warn(resp["error"], SunpyUserWarning) responses.append( VSOQueryResponse(query_response) ) except Exception as ex: response = QueryResponse.create(self.merge(responses)) response.add_error(ex) return QueryResponse.create(self.merge(responses)) def merge(self, queryresponses): """ Merge responses into one. """ if len(queryresponses) == 1: return queryresponses[0] fileids = set() providers = {} for queryresponse in queryresponses: for provideritem in queryresponse.provideritem: provider = provideritem.provider if not hasattr(provideritem, 'record'): continue if not hasattr(provideritem.record, 'recorditem'): continue if provideritem.provider not in providers: providers[provider] = provideritem fileids |= { record_item.fileid for record_item in provideritem.record.recorditem } else: for record_item in provideritem.record.recorditem: if record_item.fileid not in fileids: fileids.add(record_item.fileid) providers[provider].record.recorditem.append( record_item ) providers[provider].no_of_records_found += 1 providers[provider].no_of_records_returned += 1 return self.make('QueryResponse', provideritem=list(providers.values())) @staticmethod def mk_filename(pattern, queryresponse, resp, url): """ Generate the best possible (or least-worse) filename for a VSO download. * Use the ``content-disposition`` header. * Use `fileid` to generate a file name if content-disposition fails * If everything else fails use the last segment of the URL and hope. """ name = None if resp: cdheader = resp.headers.get("Content-Disposition", None) if cdheader: value, params = cgi.parse_header(cdheader) name = params.get('filename', "") # Work around https://github.com/sunpy/sunpy/issues/3372 if name.count('"') >= 2: name = name.split('"')[1] if name is None: # Advice from the VSO is to fallback to providerid + fileid # As it's possible multiple providers give the same fileid. # However, I haven't implemented this yet as it would be a breaking # change to the filenames we expect. # I don't know if we still need this bytes check in Python 3 only # land, but I don't dare remove it. if isinstance(queryresponse.fileid, bytes): fileid = queryresponse.fileid.decode("ascii", "ignore") else: fileid = queryresponse.fileid # Some providers make fileid a path # Some also don't specify a file extension, but not a lot we can do # about that. name = fileid.split("/")[-1] # If somehow we have got this far with an empty string, fallback to url segment if not name: name = url.split('/')[-1] # Remove any not-filename appropriate characters name = slugify(name) # If absolutely everything else fails make a filename based on download time if not name: name = f"vso_file_{datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')}" fname = pattern.format(file=name, **serialize_object(queryresponse)) return fname @deprecated("1.0", alternative="sunpy.net.Fido") def query_legacy(self, tstart=None, tend=None, **kwargs): """ Query data from the VSO mocking the IDL API as close as possible. Either tstart and tend or date_start and date_end or date have to be supplied. Parameters ---------- tstart : datetime.datetime Start of the time-range in which records are searched. tend : datetime.datetime Start of the time-range in which records are searched. date : str (start date) - (end date) start_date : datetime the start date end_date : datetime the end date wave : str (min) - (max) (unit) min_wave : str minimum spectral range max_wave : str maximum spectral range unit_wave : str spectral range units (Angstrom, GHz, keV) extent : str VSO 'extent type' ... (FULLDISK, CORONA, LIMB, etc) physobj : str VSO 'physical observable' provider : str VSO ID for the data provider (SDAC, NSO, SHA, MSU, etc) source : str spacecraft or observatory (SOHO, YOHKOH, BBSO, etc) synonyms : spacecraft, observatory instrument : str instrument ID (EIT, SXI-0, SXT, etc) synonyms : telescope, inst detector : str detector ID (C3, EUVI, COR2, etc.) layout : str layout of the data (image, spectrum, time_series, etc.) level : str level of the data product (numeric range, see below) pixels : str number of pixels (numeric range, see below) resolution : str effective resolution (1 = full, 0.5 = 2x2 binned, etc) numeric range, see below. pscale : str pixel scale, in arcseconds (numeric range, see below) near_time : datetime return record closest to the time. See below. sample : int attempt to return only one record per SAMPLE seconds. See below. Numeric Ranges: - May be entered as a string or any numeric type for equality matching - May be a string of the format '(min) - (max)' for range matching - May be a string of the form '(operator) (number)' where operator is one of: lt gt le ge < > <= >= Examples -------- Query all data from eit between 2010-01-01T00:00 and 2010-01-01T01:00. >>> from datetime import datetime >>> from sunpy.net import vso >>> client = vso.VSOClient() # doctest: +SKIP >>> qr = client.query_legacy(datetime(2010, 1, 1), ... datetime(2010, 1, 1, 1), ... instrument='eit') # doctest: +SKIP Returns ------- out : :py:class:`QueryResult` (enhanced list) Matched items. Return value is of same type as the one of :py:class:`VSOClient.search`. """ def sdk(key): return partial(lambda key, value: {key: value}, key) ALIASES = { 'wave_min': sdk('wave_wavemin'), 'wave_max': sdk('wave_wavemax'), 'wave_type': sdk('wave_wavetype'), 'wave_unit': sdk('wave_waveunit'), 'min_wave': sdk('wave_wavemin'), 'max_wave': sdk('wave_wavemax'), 'type_wave': sdk('wave_wavetype'), 'unit_wave': sdk('wave_waveunit'), 'wave': _parse_waverange, 'inst': sdk('instrument'), 'telescope': sdk('instrument'), 'spacecraft': sdk('source'), 'observatory': sdk('source'), 'start_date': sdk('time_start'), 'end_date': sdk('time_end'), 'start': sdk('time_start'), 'end': sdk('time_end'), 'near_time': sdk('time_near'), 'date': _parse_date, 'layout': sdk('datatype'), } if tstart is not None: kwargs.update({'time_start': tstart}) if tend is not None: kwargs.update({'time_end': tend}) QueryRequest = self.api.get_type('VSO:QueryRequest') VSOQueryResponse = self.api.get_type('VSO:QueryResponse') block = self.api.get_type('VSO:QueryRequestBlock')() for key, value in kwargs.items(): for k, v in ALIASES.get(key, sdk(key))(value).items(): if k.startswith('time'): v = parse_time(v).strftime(TIMEFORMAT) attr = k.split('_') lst = attr[-1] rest = attr[:-1] for elem in rest: try: if block[elem] is None: block[elem] = {} block = block[elem] except KeyError: raise ValueError( f"Unexpected argument {key!s}.") if lst in block and block[lst]: raise ValueError( f"Got multiple values for {k!s}.") block[lst] = v return QueryResponse.create(VSOQueryResponse( self.api.service.Query(QueryRequest(block=block)))) @deprecated("1.0") def latest(self): """ Return newest record (limited to last week). """ from datetime import datetime, timedelta return self.query_legacy( datetime.utcnow() - timedelta(7), datetime.utcnow(), time_near=datetime.utcnow() ) def fetch(self, query_response, path=None, methods=None, site=None, progress=True, overwrite=False, downloader=None, wait=True): """ Download data specified in the query_response. Parameters ---------- query_response : sunpy.net.vso.QueryResponse QueryResponse containing the items to be downloaded. path : str Specify where the data is to be downloaded. Can refer to arbitrary fields of the QueryResponseItem (instrument, source, time, ...) via string formatting, moreover the file-name of the file downloaded can be referred to as file, e.g. "{source}/{instrument}/{time.start}/{file}". methods : {list of str} Download methods, defaults to URL-FILE_Rice then URL-FILE. Methods are a concatenation of one PREFIX followed by any number of SUFFIXES i.e. `PREFIX-SUFFIX_SUFFIX2_SUFFIX3`. The full list of `PREFIXES <https://sdac.virtualsolar.org/cgi/show_details?keyword=METHOD_PREFIX>`_ and `SUFFIXES <https://sdac.virtualsolar.org/cgi/show_details?keyword=METHOD_SUFFIX>`_ are listed on the VSO site. site : str There are a number of caching mirrors for SDO and other instruments, some available ones are listed below. =============== ======================================================== NSO National Solar Observatory, Tucson (US) SAO (aka CFA) Smithonian Astronomical Observatory, Harvard U. (US) SDAC (aka GSFC) Solar Data Analysis Center, NASA/GSFC (US) ROB Royal Observatory of Belgium (Belgium) MPS Max Planck Institute for Solar System Research (Germany) UCLan University of Central Lancashire (UK) IAS Institut Aeronautique et Spatial (France) KIS Kiepenheuer-Institut fur Sonnenphysik Germany) NMSU New Mexico State University (US) =============== ======================================================== progress : `bool`, optional If `True` show a progress bar showing how many of the total files have been downloaded. If `False`, no progress bars will be shown at all. overwrite : `bool` or `str`, optional Determine how to handle downloading if a file already exists with the same name. If `False` the file download will be skipped and the path returned to the existing file, if `True` the file will be downloaded and the existing file will be overwritten, if `'unique'` the filename will be modified to be unique. downloader : `parfive.Downloader`, optional The download manager to use. wait : `bool`, optional If `False` ``downloader.download()`` will not be called. Only has any effect if `downloader` is not `None`. Returns ------- out : `parfive.Results` Object that supplies a list of filenames and any errors. Examples -------- >>> files = fetch(qr) # doctest:+SKIP """ if path is None: path = os.path.join(config.get('downloads', 'download_dir'), '{file}') elif isinstance(path, str) and '{file}' not in path: path = os.path.join(path, '{file}') path = os.path.expanduser(path) dl_set = True if not downloader: dl_set = False downloader = Downloader(progress=progress) fileids = VSOClient.by_fileid(query_response) if not fileids: return downloader.download() if wait else Results() # Adding the site parameter to the info info = {} if site is not None: info['site'] = site VSOGetDataResponse = self.api.get_type("VSO:VSOGetDataResponse") data_request = self.make_getdatarequest(query_response, methods, info) data_response = VSOGetDataResponse(self.api.service.GetData(data_request)) err_results = self.download_all(data_response, methods, downloader, path, fileids) if dl_set and not wait: return err_results results = downloader.download() results += err_results results._errors += err_results.errors return results @staticmethod def link(query_response, maps): """ Return list of paths with records associated with them in the meta attribute. """ if not maps: return [] ret = [] for record_item in query_response: try: item = _Str(maps[record_item.fileid]['path']) except KeyError: continue # pylint: disable=W0201 item.meta = record_item ret.append(item) return ret def make_getdatarequest(self, response, methods=None, info=None): """ Make datarequest with methods from response. """ if methods is None: methods = self.method_order + ['URL'] return self.create_getdatarequest( {k: [x.fileid for x in v] for k, v in self.by_provider(response).items()}, methods, info ) def create_getdatarequest(self, maps, methods, info=None): """ Create datarequest from maps mapping data provider to fileids and methods, """ if info is None: info = {} if 'email' not in info: info['email'] = 'sunpy' # For the JSOC provider we need to make a DataRequestItem for each # series, not just one for the whole provider. # Remove JSOC provider items from the map jsoc = maps.pop('JSOC', []) # Make DRIs for everything that's not JSOC one per provider dris = [self.make('DataRequestItem', provider=k, fileiditem={'fileid': v}) for k, v in maps.items()] def series_func(x): """ Extract the series from the fileid. """ return x.split(':')[0] # Sort the JSOC fileids by series # This is a precursor to groupby as recommended by the groupby docs series_sorted = sorted(jsoc, key=series_func) # Iterate over the series and make a DRI for each. # groupby creates an iterator based on a key function, in this case # based on the series (the part before the first ':') for series, fileids in itertools.groupby(series_sorted, key=series_func): dris.append(self.make('DataRequestItem', provider='JSOC', fileiditem={'fileid': list(fileids)})) request = {'method': {'methodtype': methods}, 'info': info, 'datacontainer': {'datarequestitem': dris} } return self.make('VSOGetDataRequest', request=request) # pylint: disable=R0913,R0912 def download_all(self, response, methods, downloader, path, qr, info=None): results = Results() GET_VERSION = [ ('0.8', (5, 8)), ('0.7', (1, 4)), ('0.6', (0, 3)), ] for dresponse in response.getdataresponseitem: for version, (from_, to) in GET_VERSION: if getattr(dresponse, version, '0.6') >= version: break else: results.add_error('', UnknownVersion(dresponse)) continue # If from_ and to are uninitialized, the else block of the loop # continues the outer loop and thus this code is never reached. # pylint: disable=W0631 code = ( dresponse.status[from_:to] if getattr(dresponse, 'status', None) else '200' ) if code == '200': for dataitem in dresponse.getdataitem.dataitem: try: self.download( dresponse.method.methodtype[0], dataitem.url, downloader, path, qr[dataitem.fileiditem.fileid[0]] ) except NoData: results.add_error('', '', DownloadFailed(dresponse)) continue elif code == '300' or code == '412' or code == '405': if code == '300': try: methods = self.multiple_choices( dresponse.method.methodtype, dresponse ) except NoData: results.add_error('', '', MultipleChoices(dresponse)) continue elif code == '412': try: info = self.missing_information( info, dresponse.info ) except NoData: results.add_error('', '', MissingInformation(dresponse)) continue elif code == '405': try: methods = self.unknown_method(dresponse) except NoData: results.add_error('', '', UnknownMethod(dresponse)) continue files = [] for dataitem in dresponse.getdataitem.dataitem: files.extend(dataitem.fileiditem.fileid) request = self.create_getdatarequest( {dresponse.provider: files}, methods, info ) self.download_all( self.api.service.GetData(request), methods, downloader, path, qr, info ) else: results.add_error('', '', UnknownStatus(dresponse)) return results def download(self, method, url, downloader, *args): """ Enqueue a file to be downloaded, extra args are passed to ``mk_filename``""" if method.startswith('URL'): return downloader.enqueue_file(url, filename=partial(self.mk_filename, *args)) raise NoData @staticmethod def by_provider(response): """ Returns a dictionary of provider corresponding to records in the response. """ map_ = defaultdict(list) for record in response: map_[record.provider].append(record) return map_ @staticmethod def by_fileid(response): """ Returns a dictionary of fileids corresponding to records in the response. """ return { record.fileid: record for record in response } # pylint: disable=W0613 def multiple_choices(self, choices, response): """ Override to pick between multiple download choices. """ for elem in self.method_order: if elem in choices: return [elem] raise NoData # pylint: disable=W0613 def missing_information(self, info, field): """ Override to provide missing information. """ raise NoData # pylint: disable=W0613 def unknown_method(self, response): """ Override to pick a new method if the current one is unknown. """ raise NoData @classmethod def _can_handle_query(cls, *query): required = {core_attrs.Time} # Get all classes in core_attrs and attrs optional = {value for (name, value) in inspect.getmembers(core_attrs) if name in core_attrs.__all__} optional.update(value for (name, value) in inspect.getmembers(attrs) if name in attrs.__all__) return cls.check_attr_types_in_query(query, required, optional) @classmethod def _attrs_module(cls): return 'vso', 'sunpy.net.vso.attrs' def __del__(self): self.api.transport.session.close()
""" To-do: - WSC requires free-form generation - ReCoRD """ import numpy as np import sklearn import transformers.data.metrics.squad_metrics as squad_metrics from . common import HFTask, yesno from lm_eval.base import rf from ..metrics import mean, acc_all, metric_max_over_ground_truths from ..utils import general_detokenize class BoolQ(HFTask): DATASET_PATH = "super_glue" DATASET_NAME = "boolq" def has_training_docs(self): return True def has_validation_docs(self): return True def has_test_docs(self): return False def fewshot_description(self): # TODO: figure out actual description return "Read the following passages and answer each question with a yes or a no." def doc_to_text(self, doc): return f"{doc["passage"]}\nQuestion: {doc["question"]}\nAnswer:" def doc_to_target(self, doc): return " " + yesno(doc['label']) def construct_requests(self, doc, ctx): ll_yes, _ = rf.loglikelihood(ctx, ' yes') ll_no, _ = rf.loglikelihood(ctx, ' no') return ll_yes, ll_no def process_results(self, doc, results): ll_yes, ll_no = results gold = doc["label"] acc = 1. if (ll_yes > ll_no) == gold else 0. return { "acc": acc } def higher_is_better(self): return { "acc": True } def aggregation(self): return { "acc": mean } class CommitmentBank(HFTask): DATASET_PATH = "super_glue" DATASET_NAME = "cb" def has_training_docs(self): return True def has_validation_docs(self): return True def has_test_docs(self): return False def fewshot_description(self): # TODO: figure out actual description return "Given a premise and a hypothesis, classify whether the author of the premise is committed" \ "to the truth of the hypothesis. The three possible labels are true, false or neither." def doc_to_text(self, doc): return "{}\nQuestion: {}. True, False or Neither?\nAnswer:".format( doc["premise"], doc["hypothesis"], ) def doc_to_target(self, doc): # True = entailment # False = contradiction # Neither = neutral return " {}".format({0: "True", 1: "Neither", 2: "False"}[doc["label"]]) def construct_requests(self, doc, ctx): ll_true, _ = rf.loglikelihood(ctx, ' True') ll_neither, _ = rf.loglikelihood(ctx, ' Neither') ll_false, _ = rf.loglikelihood(ctx, ' False') return ll_true, ll_neither, ll_false def process_results(self, doc, results): gold = doc["label"] pred = np.argmax(results) acc = 1. if pred == gold else 0. return { "acc": acc, "f1": (pred, gold) } def higher_is_better(self): return { "acc": True, "f1": True } @classmethod def cb_multi_fi(cls, items): preds, golds = zip(*items) preds = np.array(preds) golds = np.array(golds) f11 = sklearn.metrics.f1_score(y_true=golds == 0, y_pred=preds == 0) f12 = sklearn.metrics.f1_score(y_true=golds == 1, y_pred=preds == 1) f13 = sklearn.metrics.f1_score(y_true=golds == 2, y_pred=preds == 2) avg_f1 = mean([f11, f12, f13]) return avg_f1 def aggregation(self): return { "acc": mean, "f1": self.cb_multi_fi, } class Copa(HFTask): DATASET_PATH = "super_glue" DATASET_NAME = "copa" def has_training_docs(self): return True def has_validation_docs(self): return True def has_test_docs(self): return False def fewshot_description(self): # TODO: figure out actual description return "Given a premise and one alternative with a causal relation to the premise and another without," \ "choose the more plausible alternative" def doc_to_text(self, doc): # Drop the period connector = { "cause": "because", "effect": "therefore", }[doc["question"]] return doc["premise"].strip()[:-1] + f" {connector}" def doc_to_target(self, doc): correct_choice = doc["choice1"] if doc["label"] == 0 else doc["choice2"] # Connect the sentences return " " + self.convert_choice(correct_choice) def construct_requests(self, doc, ctx): choice1 = " " + self.convert_choice(doc["choice1"]) choice2 = " " + self.convert_choice(doc["choice2"]) ll_choice1, _ = rf.loglikelihood(ctx, choice1) ll_choice2, _ = rf.loglikelihood(ctx, choice2) return ll_choice1, ll_choice2 def process_results(self, doc, results): gold = doc["label"] pred = np.argmax(results) acc = 1. if pred == gold else 0. return { "acc": acc } def higher_is_better(self): return { "acc": True } def aggregation(self): return { "acc": mean } @staticmethod def convert_choice(choice): return choice[0].lower() + choice[1:] class MultiRC(HFTask): DATASET_PATH = "super_glue" DATASET_NAME = "multirc" def has_training_docs(self): return True def has_validation_docs(self): return True def has_test_docs(self): return False def fewshot_description(self): # TODO: figure out actual description return "READING COMPREHENSION ANSWER KEY" def doc_to_text(self, doc): return f"{doc["paragraph"]}\nQuestion: {doc["question"]}\nAnswer:" def doc_to_target(self, doc): return " " + self.format_answer(answer=doc["answer"], label=doc["label"]) @staticmethod def format_answer(answer, label): label_str = "yes" if label else "no" return f"{label_str}, {answer}" def construct_requests(self, doc, ctx): true_choice = self.format_answer(answer=doc["answer"], label=True) false_choice = self.format_answer(answer=doc["answer"], label=False) ll_true_choice, _ = rf.loglikelihood(ctx, f' {true_choice}') ll_false_choice, _ = rf.loglikelihood(ctx, f' {false_choice}') return ll_true_choice, ll_false_choice def process_results(self, doc, results): pred = np.argmax(results) return { "acc": (pred, doc) } def higher_is_better(self): return { "acc": True } def aggregation(self): return { "acc": acc_all } class ReCoRD(HFTask): DATASET_PATH = "super_glue" DATASET_NAME = "record" def has_training_docs(self): return True def has_validation_docs(self): return True def has_test_docs(self): return False def fewshot_description(self): # TODO: figure out actual description return "" def training_docs(self): # In ReCoRD, each doc manifests multiple "examples" in the context of few shot example packing. # Each doc consists of multiple answer candidates, each of which is scored yes/no. if self._training_docs is None: self._training_docs = [] for doc in self.data["train"]: self._training_docs.append(self._process_doc(doc)) return self._training_docs def validation_docs(self): # See: training_docs for doc in self.data["validation"]: yield self._process_doc(doc) @classmethod def _process_doc(cls, doc): return { "passage": doc["passage"], "query": doc["query"], "entities": sorted(list(set(doc["entities"]))), "answers": sorted(list(set(doc["answers"]))), } def doc_to_text(self, doc): initial_text, *highlights = doc["passage"].strip().split("\n@highlight\n") text = initial_text + "\n\n" for highlight in highlights: text += f" - {highlight}.\n" return text @classmethod def format_answer(cls, query, entity): return f' - {query}'.replace("@placeholder", entity) def doc_to_target(self, doc): # We only output the first correct entity in a doc return self.format_answer(query=doc["query"], entity=doc["answers"][0]) def construct_requests(self, doc, ctx): requests = [ rf.loglikelihood(ctx, self.format_answer(query=doc["query"], entity=entity)) for entity in doc["entities"] ] return requests def process_results(self, doc, results): # ReCoRD's evaluation is actually deceptively simple: # - Pick the maximum likelihood prediction entity # - Evaluate the accuracy and token F1 PER EXAMPLE # - Average over all examples max_idx = np.argmax(np.array([result[0] for result in results])) prediction = doc["entities"][max_idx] gold_label_set = doc["answers"] f1 = metric_max_over_ground_truths(squad_metrics.compute_f1, prediction, gold_label_set) em = metric_max_over_ground_truths(squad_metrics.compute_exact, prediction, gold_label_set) return { "f1": f1, "em": em, } def higher_is_better(self): return { "f1": True, "em": True, } def aggregation(self): return { "f1": mean, "em": mean, } class WordsInContext(HFTask): DATASET_PATH = "super_glue" DATASET_NAME = "wic" def has_training_docs(self): return True def has_validation_docs(self): return True def has_test_docs(self): return False def fewshot_description(self): # TODO: figure out actual description return "" def doc_to_text(self, doc): return "Sentence 1: {}\nSentence 2: {}\nQuestion: Is the word '{}' used in the same way in the" \ " two sentences above?\nAnswer:".format( doc["sentence1"], doc["sentence2"], doc["sentence1"][doc["start1"]:doc["end1"]], ) def doc_to_target(self, doc): return " {}".format({0: "no", 1: "yes"}[doc["label"]]) def construct_requests(self, doc, ctx): ll_yes, _ = rf.loglikelihood(ctx, ' yes') ll_no, _ = rf.loglikelihood(ctx, ' no') return ll_yes, ll_no def process_results(self, doc, results): ll_yes, ll_no = results gold = doc["label"] acc = 1. if (ll_yes > ll_no) == gold else 0. return { "acc": acc } def higher_is_better(self): return { "acc": True } def aggregation(self): return { "acc": mean } class SGWinogradSchemaChallenge(HFTask): # Note: This implementation differs from Fig G.32 because this is the SuperGLUE, # binary version of the task. DATASET_PATH = "super_glue" DATASET_NAME = "wsc" def has_training_docs(self): return True def has_validation_docs(self): return True def has_test_docs(self): return True def training_docs(self): if self.has_training_docs(): if self._training_docs is None: # GPT-3 Paper's format only uses positive examples for fewshot "training" self._training_docs = [ doc for doc in self.data["train"] if doc["label"] ] return self._training_docs def fewshot_description(self): return "Final Exam with Answer Key\n" \ "Instructions: Please carefully read the following passages. " \ "For each passage, you must identify which noun the pronoun marked in *bold*" \ " refers to.\n=====" def doc_to_text(self, doc): raw_passage = doc["text"] # NOTE: HuggingFace span indices are word-based not character-based. pre = " ".join(raw_passage.split()[:doc["span2_index"]]) post = raw_passage[len(pre) + len(doc["span2_text"]) + 1:] passage = general_detokenize(pre + " *{}*".format(doc['span2_text']) + post) noun = doc["span1_text"] pronoun = doc["span2_text"] text = ( f"Passage: {passage}\n" + f"Question: In the passage above, does the pronoun \"*{pronoun}*\" refer to \"*{noun}*\"?\n" + "Answer:" ) return text def doc_to_target(self, doc): return " " + yesno(doc['label']) def construct_requests(self, doc, ctx): ll_yes, _ = rf.loglikelihood(ctx, ' yes') ll_no, _ = rf.loglikelihood(ctx, ' no') return ll_yes, ll_no def process_results(self, doc, results): ll_yes, ll_no = results gold = doc["label"] acc = 1. if (ll_yes > ll_no) == gold else 0. return { "acc": acc } def higher_is_better(self): return { "acc": True } def aggregation(self): return { "acc": mean }
""" To-do: - WSC requires free-form generation - ReCoRD """ import numpy as np import sklearn import transformers.data.metrics.squad_metrics as squad_metrics from . common import HFTask, yesno from lm_eval.base import rf from ..metrics import mean, acc_all, metric_max_over_ground_truths from ..utils import general_detokenize class BoolQ(HFTask): DATASET_PATH = "super_glue" DATASET_NAME = "boolq" def has_training_docs(self): return True def has_validation_docs(self): return True def has_test_docs(self): return False def fewshot_description(self): # TODO: figure out actual description return "Read the following passages and answer each question with a yes or a no." def doc_to_text(self, doc): return f"{doc['passage']}\nQuestion: {doc['question']}\nAnswer:" def doc_to_target(self, doc): return " " + yesno(doc['label']) def construct_requests(self, doc, ctx): ll_yes, _ = rf.loglikelihood(ctx, ' yes') ll_no, _ = rf.loglikelihood(ctx, ' no') return ll_yes, ll_no def process_results(self, doc, results): ll_yes, ll_no = results gold = doc["label"] acc = 1. if (ll_yes > ll_no) == gold else 0. return { "acc": acc } def higher_is_better(self): return { "acc": True } def aggregation(self): return { "acc": mean } class CommitmentBank(HFTask): DATASET_PATH = "super_glue" DATASET_NAME = "cb" def has_training_docs(self): return True def has_validation_docs(self): return True def has_test_docs(self): return False def fewshot_description(self): # TODO: figure out actual description return "Given a premise and a hypothesis, classify whether the author of the premise is committed" \ "to the truth of the hypothesis. The three possible labels are true, false or neither." def doc_to_text(self, doc): return "{}\nQuestion: {}. True, False or Neither?\nAnswer:".format( doc["premise"], doc["hypothesis"], ) def doc_to_target(self, doc): # True = entailment # False = contradiction # Neither = neutral return " {}".format({0: "True", 1: "Neither", 2: "False"}[doc["label"]]) def construct_requests(self, doc, ctx): ll_true, _ = rf.loglikelihood(ctx, ' True') ll_neither, _ = rf.loglikelihood(ctx, ' Neither') ll_false, _ = rf.loglikelihood(ctx, ' False') return ll_true, ll_neither, ll_false def process_results(self, doc, results): gold = doc["label"] pred = np.argmax(results) acc = 1. if pred == gold else 0. return { "acc": acc, "f1": (pred, gold) } def higher_is_better(self): return { "acc": True, "f1": True } @classmethod def cb_multi_fi(cls, items): preds, golds = zip(*items) preds = np.array(preds) golds = np.array(golds) f11 = sklearn.metrics.f1_score(y_true=golds == 0, y_pred=preds == 0) f12 = sklearn.metrics.f1_score(y_true=golds == 1, y_pred=preds == 1) f13 = sklearn.metrics.f1_score(y_true=golds == 2, y_pred=preds == 2) avg_f1 = mean([f11, f12, f13]) return avg_f1 def aggregation(self): return { "acc": mean, "f1": self.cb_multi_fi, } class Copa(HFTask): DATASET_PATH = "super_glue" DATASET_NAME = "copa" def has_training_docs(self): return True def has_validation_docs(self): return True def has_test_docs(self): return False def fewshot_description(self): # TODO: figure out actual description return "Given a premise and one alternative with a causal relation to the premise and another without," \ "choose the more plausible alternative" def doc_to_text(self, doc): # Drop the period connector = { "cause": "because", "effect": "therefore", }[doc["question"]] return doc["premise"].strip()[:-1] + f" {connector}" def doc_to_target(self, doc): correct_choice = doc["choice1"] if doc["label"] == 0 else doc["choice2"] # Connect the sentences return " " + self.convert_choice(correct_choice) def construct_requests(self, doc, ctx): choice1 = " " + self.convert_choice(doc["choice1"]) choice2 = " " + self.convert_choice(doc["choice2"]) ll_choice1, _ = rf.loglikelihood(ctx, choice1) ll_choice2, _ = rf.loglikelihood(ctx, choice2) return ll_choice1, ll_choice2 def process_results(self, doc, results): gold = doc["label"] pred = np.argmax(results) acc = 1. if pred == gold else 0. return { "acc": acc } def higher_is_better(self): return { "acc": True } def aggregation(self): return { "acc": mean } @staticmethod def convert_choice(choice): return choice[0].lower() + choice[1:] class MultiRC(HFTask): DATASET_PATH = "super_glue" DATASET_NAME = "multirc" def has_training_docs(self): return True def has_validation_docs(self): return True def has_test_docs(self): return False def fewshot_description(self): # TODO: figure out actual description return "READING COMPREHENSION ANSWER KEY" def doc_to_text(self, doc): return f"{doc['paragraph']}\nQuestion: {doc['question']}\nAnswer:" def doc_to_target(self, doc): return " " + self.format_answer(answer=doc["answer"], label=doc["label"]) @staticmethod def format_answer(answer, label): label_str = "yes" if label else "no" return f"{label_str}, {answer}" def construct_requests(self, doc, ctx): true_choice = self.format_answer(answer=doc["answer"], label=True) false_choice = self.format_answer(answer=doc["answer"], label=False) ll_true_choice, _ = rf.loglikelihood(ctx, f' {true_choice}') ll_false_choice, _ = rf.loglikelihood(ctx, f' {false_choice}') return ll_true_choice, ll_false_choice def process_results(self, doc, results): pred = np.argmax(results) return { "acc": (pred, doc) } def higher_is_better(self): return { "acc": True } def aggregation(self): return { "acc": acc_all } class ReCoRD(HFTask): DATASET_PATH = "super_glue" DATASET_NAME = "record" def has_training_docs(self): return True def has_validation_docs(self): return True def has_test_docs(self): return False def fewshot_description(self): # TODO: figure out actual description return "" def training_docs(self): # In ReCoRD, each doc manifests multiple "examples" in the context of few shot example packing. # Each doc consists of multiple answer candidates, each of which is scored yes/no. if self._training_docs is None: self._training_docs = [] for doc in self.data["train"]: self._training_docs.append(self._process_doc(doc)) return self._training_docs def validation_docs(self): # See: training_docs for doc in self.data["validation"]: yield self._process_doc(doc) @classmethod def _process_doc(cls, doc): return { "passage": doc["passage"], "query": doc["query"], "entities": sorted(list(set(doc["entities"]))), "answers": sorted(list(set(doc["answers"]))), } def doc_to_text(self, doc): initial_text, *highlights = doc["passage"].strip().split("\n@highlight\n") text = initial_text + "\n\n" for highlight in highlights: text += f" - {highlight}.\n" return text @classmethod def format_answer(cls, query, entity): return f' - {query}'.replace("@placeholder", entity) def doc_to_target(self, doc): # We only output the first correct entity in a doc return self.format_answer(query=doc["query"], entity=doc["answers"][0]) def construct_requests(self, doc, ctx): requests = [ rf.loglikelihood(ctx, self.format_answer(query=doc["query"], entity=entity)) for entity in doc["entities"] ] return requests def process_results(self, doc, results): # ReCoRD's evaluation is actually deceptively simple: # - Pick the maximum likelihood prediction entity # - Evaluate the accuracy and token F1 PER EXAMPLE # - Average over all examples max_idx = np.argmax(np.array([result[0] for result in results])) prediction = doc["entities"][max_idx] gold_label_set = doc["answers"] f1 = metric_max_over_ground_truths(squad_metrics.compute_f1, prediction, gold_label_set) em = metric_max_over_ground_truths(squad_metrics.compute_exact, prediction, gold_label_set) return { "f1": f1, "em": em, } def higher_is_better(self): return { "f1": True, "em": True, } def aggregation(self): return { "f1": mean, "em": mean, } class WordsInContext(HFTask): DATASET_PATH = "super_glue" DATASET_NAME = "wic" def has_training_docs(self): return True def has_validation_docs(self): return True def has_test_docs(self): return False def fewshot_description(self): # TODO: figure out actual description return "" def doc_to_text(self, doc): return "Sentence 1: {}\nSentence 2: {}\nQuestion: Is the word '{}' used in the same way in the" \ " two sentences above?\nAnswer:".format( doc["sentence1"], doc["sentence2"], doc["sentence1"][doc["start1"]:doc["end1"]], ) def doc_to_target(self, doc): return " {}".format({0: "no", 1: "yes"}[doc["label"]]) def construct_requests(self, doc, ctx): ll_yes, _ = rf.loglikelihood(ctx, ' yes') ll_no, _ = rf.loglikelihood(ctx, ' no') return ll_yes, ll_no def process_results(self, doc, results): ll_yes, ll_no = results gold = doc["label"] acc = 1. if (ll_yes > ll_no) == gold else 0. return { "acc": acc } def higher_is_better(self): return { "acc": True } def aggregation(self): return { "acc": mean } class SGWinogradSchemaChallenge(HFTask): # Note: This implementation differs from Fig G.32 because this is the SuperGLUE, # binary version of the task. DATASET_PATH = "super_glue" DATASET_NAME = "wsc" def has_training_docs(self): return True def has_validation_docs(self): return True def has_test_docs(self): return True def training_docs(self): if self.has_training_docs(): if self._training_docs is None: # GPT-3 Paper's format only uses positive examples for fewshot "training" self._training_docs = [ doc for doc in self.data["train"] if doc["label"] ] return self._training_docs def fewshot_description(self): return "Final Exam with Answer Key\n" \ "Instructions: Please carefully read the following passages. " \ "For each passage, you must identify which noun the pronoun marked in *bold*" \ " refers to.\n=====" def doc_to_text(self, doc): raw_passage = doc["text"] # NOTE: HuggingFace span indices are word-based not character-based. pre = " ".join(raw_passage.split()[:doc["span2_index"]]) post = raw_passage[len(pre) + len(doc["span2_text"]) + 1:] passage = general_detokenize(pre + " *{}*".format(doc['span2_text']) + post) noun = doc["span1_text"] pronoun = doc["span2_text"] text = ( f"Passage: {passage}\n" + f"Question: In the passage above, does the pronoun \"*{pronoun}*\" refer to \"*{noun}*\"?\n" + "Answer:" ) return text def doc_to_target(self, doc): return " " + yesno(doc['label']) def construct_requests(self, doc, ctx): ll_yes, _ = rf.loglikelihood(ctx, ' yes') ll_no, _ = rf.loglikelihood(ctx, ' no') return ll_yes, ll_no def process_results(self, doc, results): ll_yes, ll_no = results gold = doc["label"] acc = 1. if (ll_yes > ll_no) == gold else 0. return { "acc": acc } def higher_is_better(self): return { "acc": True } def aggregation(self): return { "acc": mean }
import insightconnect_plugin_runtime from .schema import ConnectionSchema, Input # Custom imports below import requests from requests.auth import HTTPBasicAuth from icon_servicenow.util.request_helper import RequestHelper from insightconnect_plugin_runtime.exceptions import ConnectionTestException class Connection(insightconnect_plugin_runtime.Connection): def __init__(self): super(self.__class__, self).__init__(input=ConnectionSchema()) def connect(self, params): self.logger.info("Connect: Connecting...") api_route = "api/now/" incident_table = "incident" self.base_url = params.get(Input.URL, "") if not self.base_url.endswith("/"): self.base_url = f"{self.base_url}/" username = params[Input.CLIENT_LOGIN].get("username", "") password = params[Input.CLIENT_LOGIN].get("password", "") self.session = requests.Session() self.session.auth = HTTPBasicAuth(username, password) self.request = RequestHelper(self.session, self.logger) self.table_url = f"{self.base_url}{api_route}table/" self.incident_url = f"{self.table_url}{incident_table}" self.attachment_url = f"{self.base_url}{api_route}attachment" self.timeout = params.get("timeout", 30) def test(self): url = f"{self.table_url}cmdb_ci" query = {"sysparm_limit": 1} method = "get" request = RequestHelper(self.session, self.logger) response = request.make_request(url, method, params=query) if response.get("status", 0) in range(200, 299): return {"success": True} else: raise ConnectionTestException( preset=ConnectionTestException.Preset.UNKNOWN, data=f'{response.get('status', 'Not available')}, ' f'{response.get('text', 'Not available')}', )
import insightconnect_plugin_runtime from .schema import ConnectionSchema, Input # Custom imports below import requests from requests.auth import HTTPBasicAuth from icon_servicenow.util.request_helper import RequestHelper from insightconnect_plugin_runtime.exceptions import ConnectionTestException class Connection(insightconnect_plugin_runtime.Connection): def __init__(self): super(self.__class__, self).__init__(input=ConnectionSchema()) def connect(self, params): self.logger.info("Connect: Connecting...") api_route = "api/now/" incident_table = "incident" self.base_url = params.get(Input.URL, "") if not self.base_url.endswith("/"): self.base_url = f"{self.base_url}/" username = params[Input.CLIENT_LOGIN].get("username", "") password = params[Input.CLIENT_LOGIN].get("password", "") self.session = requests.Session() self.session.auth = HTTPBasicAuth(username, password) self.request = RequestHelper(self.session, self.logger) self.table_url = f"{self.base_url}{api_route}table/" self.incident_url = f"{self.table_url}{incident_table}" self.attachment_url = f"{self.base_url}{api_route}attachment" self.timeout = params.get("timeout", 30) def test(self): url = f"{self.table_url}cmdb_ci" query = {"sysparm_limit": 1} method = "get" request = RequestHelper(self.session, self.logger) response = request.make_request(url, method, params=query) if response.get("status", 0) in range(200, 299): return {"success": True} else: raise ConnectionTestException( preset=ConnectionTestException.Preset.UNKNOWN, data=f'{response.get("status", "Not available")}, ' f'{response.get("text", "Not available")}', )
import uuid from typing import Dict, List, Optional import pandas as pd from feast import RedshiftSource from feast.data_source import DataSource from feast.infra.offline_stores.redshift import RedshiftOfflineStoreConfig from feast.infra.offline_stores.redshift_source import SavedDatasetRedshiftStorage from feast.infra.utils import aws_utils from feast.repo_config import FeastConfigBaseModel from tests.integration.feature_repos.universal.data_source_creator import ( DataSourceCreator, ) class RedshiftDataSourceCreator(DataSourceCreator): tables: List[str] = [] def __init__(self, project_name: str): super().__init__(project_name) self.client = aws_utils.get_redshift_data_client("us-west-2") self.s3 = aws_utils.get_s3_resource("us-west-2") self.offline_store_config = RedshiftOfflineStoreConfig( cluster_id="feast-integration-tests", region="us-west-2", user="admin", database="feast", s3_staging_location="s3://feast-integration-tests/redshift/tests/ingestion", iam_role="arn:aws:iam::402087665549:role/redshift_s3_access_role", ) def create_data_source( self, df: pd.DataFrame, destination_name: str, suffix: Optional[str] = None, timestamp_field="ts", created_timestamp_column="created_ts", field_mapping: Dict[str, str] = None, ) -> DataSource: destination_name = self.get_prefixed_table_name(destination_name) aws_utils.upload_df_to_redshift( self.client, self.offline_store_config.cluster_id, self.offline_store_config.database, self.offline_store_config.user, self.s3, f"{self.offline_store_config.s3_staging_location}/copy/{destination_name}.parquet", self.offline_store_config.iam_role, destination_name, df, ) self.tables.append(destination_name) return RedshiftSource( table=destination_name, timestamp_field=timestamp_field, created_timestamp_column=created_timestamp_column, field_mapping=field_mapping or {"ts_1": "ts"}, database=self.offline_store_config.database, ) def create_saved_dataset_destination(self) -> SavedDatasetRedshiftStorage: table = self.get_prefixed_table_name( f"persisted_ds_{str(uuid.uuid4()).replace("-", "_")}" ) self.tables.append(table) return SavedDatasetRedshiftStorage(table_ref=table) def create_offline_store_config(self) -> FeastConfigBaseModel: return self.offline_store_config def get_prefixed_table_name(self, suffix: str) -> str: return f"{self.project_name}_{suffix}" def teardown(self): for table in self.tables: aws_utils.execute_redshift_statement( self.client, self.offline_store_config.cluster_id, self.offline_store_config.database, self.offline_store_config.user, f"DROP TABLE IF EXISTS {table}", )
import uuid from typing import Dict, List, Optional import pandas as pd from feast import RedshiftSource from feast.data_source import DataSource from feast.infra.offline_stores.redshift import RedshiftOfflineStoreConfig from feast.infra.offline_stores.redshift_source import SavedDatasetRedshiftStorage from feast.infra.utils import aws_utils from feast.repo_config import FeastConfigBaseModel from tests.integration.feature_repos.universal.data_source_creator import ( DataSourceCreator, ) class RedshiftDataSourceCreator(DataSourceCreator): tables: List[str] = [] def __init__(self, project_name: str): super().__init__(project_name) self.client = aws_utils.get_redshift_data_client("us-west-2") self.s3 = aws_utils.get_s3_resource("us-west-2") self.offline_store_config = RedshiftOfflineStoreConfig( cluster_id="feast-integration-tests", region="us-west-2", user="admin", database="feast", s3_staging_location="s3://feast-integration-tests/redshift/tests/ingestion", iam_role="arn:aws:iam::402087665549:role/redshift_s3_access_role", ) def create_data_source( self, df: pd.DataFrame, destination_name: str, suffix: Optional[str] = None, timestamp_field="ts", created_timestamp_column="created_ts", field_mapping: Dict[str, str] = None, ) -> DataSource: destination_name = self.get_prefixed_table_name(destination_name) aws_utils.upload_df_to_redshift( self.client, self.offline_store_config.cluster_id, self.offline_store_config.database, self.offline_store_config.user, self.s3, f"{self.offline_store_config.s3_staging_location}/copy/{destination_name}.parquet", self.offline_store_config.iam_role, destination_name, df, ) self.tables.append(destination_name) return RedshiftSource( table=destination_name, timestamp_field=timestamp_field, created_timestamp_column=created_timestamp_column, field_mapping=field_mapping or {"ts_1": "ts"}, database=self.offline_store_config.database, ) def create_saved_dataset_destination(self) -> SavedDatasetRedshiftStorage: table = self.get_prefixed_table_name( f"persisted_ds_{str(uuid.uuid4()).replace('-', '_')}" ) self.tables.append(table) return SavedDatasetRedshiftStorage(table_ref=table) def create_offline_store_config(self) -> FeastConfigBaseModel: return self.offline_store_config def get_prefixed_table_name(self, suffix: str) -> str: return f"{self.project_name}_{suffix}" def teardown(self): for table in self.tables: aws_utils.execute_redshift_statement( self.client, self.offline_store_config.cluster_id, self.offline_store_config.database, self.offline_store_config.user, f"DROP TABLE IF EXISTS {table}", )
#!/usr/bin/env python3 import json import os import urllib import requests from unidiff import PatchSet from env_helper import GITHUB_REPOSITORY, GITHUB_SERVER_URL, GITHUB_RUN_ID, GITHUB_EVENT_PATH DIFF_IN_DOCUMENTATION_EXT = [".html", ".md", ".yml", ".txt", ".css", ".js", ".xml", ".ico", ".conf", ".svg", ".png", ".jpg", ".py", ".sh", ".json"] def get_pr_for_commit(sha, ref): try_get_pr_url = f"https://api.github.com/repos/{GITHUB_REPOSITORY}/commits/{sha}/pulls" try: response = requests.get(try_get_pr_url) response.raise_for_status() data = response.json() if len(data) > 1: print("Got more than one pr for commit", sha) for pr in data: # refs for pushes looks like refs/head/XX # refs for RPs looks like XX if pr['head']['ref'] in ref: return pr print("Cannot find PR with required ref", ref, "returning first one") first_pr = data[0] return first_pr except Exception as ex: print("Cannot fetch PR info from commit", ex) return None class PRInfo: def __init__(self, github_event=None, need_orgs=False, need_changed_files=False, labels_from_api=False): if not github_event: if GITHUB_EVENT_PATH: with open(GITHUB_EVENT_PATH, 'r', encoding='utf-8') as event_file: github_event = json.load(event_file) else: github_event = {'commits': 1, 'after': 'HEAD', 'ref': None} self.event = github_event self.changed_files = set([]) if 'pull_request' in github_event: # pull request and other similar events self.number = github_event['number'] if 'after' in github_event: self.sha = github_event['after'] else: self.sha = github_event['pull_request']['head']['sha'] repo_prefix = f"{GITHUB_SERVER_URL}/{GITHUB_REPOSITORY}" self.task_url = f"{repo_prefix}/actions/runs/{GITHUB_RUN_ID or "0"}" self.repo_full_name = GITHUB_REPOSITORY self.commit_html_url = f"{repo_prefix}/commits/{self.sha}" self.pr_html_url = f"{repo_prefix}/pull/{self.number}" self.base_ref = github_event['pull_request']['base']['ref'] self.base_name = github_event['pull_request']['base']['repo']['full_name'] self.head_ref = github_event['pull_request']['head']['ref'] self.head_name = github_event['pull_request']['head']['repo']['full_name'] if labels_from_api: response = requests.get(f"https://api.github.com/repos/{GITHUB_REPOSITORY}/issues/{self.number}/labels") self.labels = {l['name'] for l in response.json()} else: self.labels = {l['name'] for l in github_event['pull_request']['labels']} self.user_login = github_event['pull_request']['user']['login'] self.user_orgs = set([]) if need_orgs: user_orgs_response = requests.get(github_event['pull_request']['user']['organizations_url']) if user_orgs_response.ok: response_json = user_orgs_response.json() self.user_orgs = set(org['id'] for org in response_json) self.diff_url = github_event['pull_request']['diff_url'] elif 'commits' in github_event: self.sha = github_event['after'] pull_request = get_pr_for_commit(self.sha, github_event['ref']) repo_prefix = f"{GITHUB_SERVER_URL}/{GITHUB_REPOSITORY}" self.task_url = f"{repo_prefix}/actions/runs/{GITHUB_RUN_ID or "0"}" self.commit_html_url = f"{repo_prefix}/commits/{self.sha}" self.repo_full_name = GITHUB_REPOSITORY if pull_request is None or pull_request['state'] == 'closed': # it's merged PR to master self.number = 0 self.labels = {} self.pr_html_url = f"{repo_prefix}/commits/master" self.base_ref = "master" self.base_name = self.repo_full_name self.head_ref = "master" self.head_name = self.repo_full_name self.diff_url = \ f"https://api.github.com/repos/{GITHUB_REPOSITORY}/compare/{github_event["before"]}...{self.sha}" else: self.number = pull_request['number'] if labels_from_api: response = requests.get(f"https://api.github.com/repos/{GITHUB_REPOSITORY}/issues/{self.number}/labels") self.labels = {l['name'] for l in response.json()} else: self.labels = {l['name'] for l in pull_request['labels']} self.base_ref = pull_request['base']['ref'] self.base_name = pull_request['base']['repo']['full_name'] self.head_ref = pull_request['head']['ref'] self.head_name = pull_request['head']['repo']['full_name'] self.pr_html_url = pull_request['html_url'] if 'pr-backport' in self.labels: self.diff_url = f"https://github.com/{GITHUB_REPOSITORY}/compare/master...{self.head_ref}.diff" else: self.diff_url = pull_request['diff_url'] else: raise Exception("Cannot detect type of event") if need_changed_files: self.fetch_changed_files() def fetch_changed_files(self): if 'commits' in self.event and self.number == 0: response = requests.get(self.diff_url) response.raise_for_status() diff = response.json() if 'files' in diff: self.changed_files = [f['filename'] for f in diff['files']] else: diff = urllib.request.urlopen(self.diff_url) diff_object = PatchSet(diff, diff.headers.get_charsets()[0]) self.changed_files = {f.path for f in diff_object} def get_dict(self): return { 'sha': self.sha, 'number': self.number, 'labels': self.labels, 'user_login': self.user_login, 'user_orgs': self.user_orgs, } def has_changes_in_documentation(self): # If the list wasn't built yet the best we can do is to # assume that there were changes. if self.changed_files is None or not self.changed_files: return True for f in self.changed_files: _, ext = os.path.splitext(f) path_in_docs = 'docs' in f path_in_website = 'website' in f if (ext in DIFF_IN_DOCUMENTATION_EXT and (path_in_docs or path_in_website)) or 'docker/docs' in f: return True return False def can_skip_builds_and_use_version_from_master(self): if 'force tests' in self.labels: return False if self.changed_files is None or not self.changed_files: return False for f in self.changed_files: if (not f.startswith('tests/queries') or not f.startswith('tests/integration') or not f.startswith('tests/performance')): return False return True def can_skip_integration_tests(self): if 'force tests' in self.labels: return False if self.changed_files is None or not self.changed_files: return False for f in self.changed_files: if not f.startswith('tests/queries') or not f.startswith('tests/performance'): return False return True def can_skip_functional_tests(self): if 'force tests' in self.labels: return False if self.changed_files is None or not self.changed_files: return False for f in self.changed_files: if not f.startswith('tests/integration') or not f.startswith('tests/performance'): return False return True class FakePRInfo: def __init__(self): self.number = 11111 self.sha = "xxxxxxxxxxxxxxxxxx"
#!/usr/bin/env python3 import json import os import urllib import requests from unidiff import PatchSet from env_helper import GITHUB_REPOSITORY, GITHUB_SERVER_URL, GITHUB_RUN_ID, GITHUB_EVENT_PATH DIFF_IN_DOCUMENTATION_EXT = [".html", ".md", ".yml", ".txt", ".css", ".js", ".xml", ".ico", ".conf", ".svg", ".png", ".jpg", ".py", ".sh", ".json"] def get_pr_for_commit(sha, ref): try_get_pr_url = f"https://api.github.com/repos/{GITHUB_REPOSITORY}/commits/{sha}/pulls" try: response = requests.get(try_get_pr_url) response.raise_for_status() data = response.json() if len(data) > 1: print("Got more than one pr for commit", sha) for pr in data: # refs for pushes looks like refs/head/XX # refs for RPs looks like XX if pr['head']['ref'] in ref: return pr print("Cannot find PR with required ref", ref, "returning first one") first_pr = data[0] return first_pr except Exception as ex: print("Cannot fetch PR info from commit", ex) return None class PRInfo: def __init__(self, github_event=None, need_orgs=False, need_changed_files=False, labels_from_api=False): if not github_event: if GITHUB_EVENT_PATH: with open(GITHUB_EVENT_PATH, 'r', encoding='utf-8') as event_file: github_event = json.load(event_file) else: github_event = {'commits': 1, 'after': 'HEAD', 'ref': None} self.event = github_event self.changed_files = set([]) if 'pull_request' in github_event: # pull request and other similar events self.number = github_event['number'] if 'after' in github_event: self.sha = github_event['after'] else: self.sha = github_event['pull_request']['head']['sha'] repo_prefix = f"{GITHUB_SERVER_URL}/{GITHUB_REPOSITORY}" self.task_url = f"{repo_prefix}/actions/runs/{GITHUB_RUN_ID or '0'}" self.repo_full_name = GITHUB_REPOSITORY self.commit_html_url = f"{repo_prefix}/commits/{self.sha}" self.pr_html_url = f"{repo_prefix}/pull/{self.number}" self.base_ref = github_event['pull_request']['base']['ref'] self.base_name = github_event['pull_request']['base']['repo']['full_name'] self.head_ref = github_event['pull_request']['head']['ref'] self.head_name = github_event['pull_request']['head']['repo']['full_name'] if labels_from_api: response = requests.get(f"https://api.github.com/repos/{GITHUB_REPOSITORY}/issues/{self.number}/labels") self.labels = {l['name'] for l in response.json()} else: self.labels = {l['name'] for l in github_event['pull_request']['labels']} self.user_login = github_event['pull_request']['user']['login'] self.user_orgs = set([]) if need_orgs: user_orgs_response = requests.get(github_event['pull_request']['user']['organizations_url']) if user_orgs_response.ok: response_json = user_orgs_response.json() self.user_orgs = set(org['id'] for org in response_json) self.diff_url = github_event['pull_request']['diff_url'] elif 'commits' in github_event: self.sha = github_event['after'] pull_request = get_pr_for_commit(self.sha, github_event['ref']) repo_prefix = f"{GITHUB_SERVER_URL}/{GITHUB_REPOSITORY}" self.task_url = f"{repo_prefix}/actions/runs/{GITHUB_RUN_ID or '0'}" self.commit_html_url = f"{repo_prefix}/commits/{self.sha}" self.repo_full_name = GITHUB_REPOSITORY if pull_request is None or pull_request['state'] == 'closed': # it's merged PR to master self.number = 0 self.labels = {} self.pr_html_url = f"{repo_prefix}/commits/master" self.base_ref = "master" self.base_name = self.repo_full_name self.head_ref = "master" self.head_name = self.repo_full_name self.diff_url = \ f"https://api.github.com/repos/{GITHUB_REPOSITORY}/compare/{github_event['before']}...{self.sha}" else: self.number = pull_request['number'] if labels_from_api: response = requests.get(f"https://api.github.com/repos/{GITHUB_REPOSITORY}/issues/{self.number}/labels") self.labels = {l['name'] for l in response.json()} else: self.labels = {l['name'] for l in pull_request['labels']} self.base_ref = pull_request['base']['ref'] self.base_name = pull_request['base']['repo']['full_name'] self.head_ref = pull_request['head']['ref'] self.head_name = pull_request['head']['repo']['full_name'] self.pr_html_url = pull_request['html_url'] if 'pr-backport' in self.labels: self.diff_url = f"https://github.com/{GITHUB_REPOSITORY}/compare/master...{self.head_ref}.diff" else: self.diff_url = pull_request['diff_url'] else: raise Exception("Cannot detect type of event") if need_changed_files: self.fetch_changed_files() def fetch_changed_files(self): if 'commits' in self.event and self.number == 0: response = requests.get(self.diff_url) response.raise_for_status() diff = response.json() if 'files' in diff: self.changed_files = [f['filename'] for f in diff['files']] else: diff = urllib.request.urlopen(self.diff_url) diff_object = PatchSet(diff, diff.headers.get_charsets()[0]) self.changed_files = {f.path for f in diff_object} def get_dict(self): return { 'sha': self.sha, 'number': self.number, 'labels': self.labels, 'user_login': self.user_login, 'user_orgs': self.user_orgs, } def has_changes_in_documentation(self): # If the list wasn't built yet the best we can do is to # assume that there were changes. if self.changed_files is None or not self.changed_files: return True for f in self.changed_files: _, ext = os.path.splitext(f) path_in_docs = 'docs' in f path_in_website = 'website' in f if (ext in DIFF_IN_DOCUMENTATION_EXT and (path_in_docs or path_in_website)) or 'docker/docs' in f: return True return False def can_skip_builds_and_use_version_from_master(self): if 'force tests' in self.labels: return False if self.changed_files is None or not self.changed_files: return False for f in self.changed_files: if (not f.startswith('tests/queries') or not f.startswith('tests/integration') or not f.startswith('tests/performance')): return False return True def can_skip_integration_tests(self): if 'force tests' in self.labels: return False if self.changed_files is None or not self.changed_files: return False for f in self.changed_files: if not f.startswith('tests/queries') or not f.startswith('tests/performance'): return False return True def can_skip_functional_tests(self): if 'force tests' in self.labels: return False if self.changed_files is None or not self.changed_files: return False for f in self.changed_files: if not f.startswith('tests/integration') or not f.startswith('tests/performance'): return False return True class FakePRInfo: def __init__(self): self.number = 11111 self.sha = "xxxxxxxxxxxxxxxxxx"
import abc import copy import warnings from collections import OrderedDict from typing import Any from vyper import ast as vy_ast from vyper.exceptions import CompilerPanic, InvalidType from vyper.utils import BASE_TYPES, ceil32 # Data structure for a type class NodeType(abc.ABC): def __eq__(self, other: Any) -> bool: return type(self) is type(other) and self.eq(other) @abc.abstractmethod def eq(self, other: "NodeType") -> bool: # pragma: no cover """ Checks whether or not additional properties of a ``NodeType`` subclass instance make it equal to another instance of the same type. """ pass # Data structure for a type that represents a 32-byte object class BaseType(NodeType): def __init__( self, typ, unit=False, positional=False, override_signature=False, is_literal=False ): self.typ = typ if unit or positional: raise CompilerPanic("Units are no longer supported") self.override_signature = override_signature self.is_literal = is_literal def eq(self, other): return self.typ == other.typ def __repr__(self): return str(self.typ) class InterfaceType(BaseType): def __init__(self, name): super().__init__("address") self.name = name def __eq__(self, other: Any) -> bool: return isinstance(other, BaseType) and other.typ == "address" class ByteArrayLike(NodeType): def __init__(self, maxlen, is_literal=False): self.maxlen = maxlen self.is_literal = is_literal def eq(self, other): return self.maxlen == other.maxlen def eq_base(self, other): return type(self) is type(other) class StringType(ByteArrayLike): def __repr__(self): return f"String[{self.maxlen}]" # Data structure for a byte array class ByteArrayType(ByteArrayLike): def __repr__(self): return f"Bytes[{self.maxlen}]" # Data structure for a list with some fixed length class ListType(NodeType): def __init__(self, subtype, count, is_literal=False): self.subtype = subtype self.count = count self.is_literal = is_literal def eq(self, other): return other.subtype == self.subtype and other.count == self.count def __repr__(self): return repr(self.subtype) + "[" + str(self.count) + "]" # Data structure for a key-value mapping class MappingType(NodeType): def __init__(self, keytype, valuetype): if not isinstance(keytype, (BaseType, ByteArrayLike)): raise InvalidType("Dictionary keys must be a base type") self.keytype = keytype self.valuetype = valuetype def eq(self, other): return other.keytype == self.keytype and other.valuetype == self.valuetype def __repr__(self): return "HashMap[" + repr(self.valuetype) + ", " + repr(self.keytype) + "]" # Type which has heterogeneous members, i.e. Tuples and Structs class TupleLike(NodeType): def tuple_members(self): return [v for (_k, v) in self.tuple_items()] def tuple_keys(self): return [k for (k, _v) in self.tuple_items()] def tuple_items(self): raise NotImplementedError("compiler panic!: tuple_items must be implemented by TupleLike") # Data structure for a struct, e.g. {a: <type>, b: <type>} # struct can be named or anonymous. name=None indicates anonymous. class StructType(TupleLike): def __init__(self, members, name, is_literal=False): self.members = copy.copy(members) self.name = name self.is_literal = is_literal def eq(self, other): return other.name == self.name and other.members == self.members def __repr__(self): if self.name: return "struct " + self.name else: # Anonymous struct return ( "struct {" + ", ".join([k + ": " + repr(v) for k, v in self.members.items()]) + "}" ) def tuple_items(self): return list(self.members.items()) # Data structure for a list with heterogeneous types, e.g. [int128, bytes32, bytes] class TupleType(TupleLike): def __init__(self, members, is_literal=False): self.members = copy.copy(members) self.is_literal = is_literal def eq(self, other): return other.members == self.members def __repr__(self): return "(" + ", ".join([repr(m) for m in self.members]) + ")" def tuple_items(self): return list(enumerate(self.members)) # Convert type into common form used in ABI def canonicalize_type(t, is_indexed=False): if isinstance(t, ByteArrayLike): # Check to see if maxlen is small enough for events byte_type = "string" if isinstance(t, StringType) else "bytes" return byte_type if isinstance(t, ListType): if not isinstance(t.subtype, (ListType, BaseType)): raise InvalidType(f"List of {t.subtype} not allowed") return canonicalize_type(t.subtype) + f"[{t.count}]" if isinstance(t, TupleLike): return f"({",".join(canonicalize_type(x) for x in t.tuple_members())})" if not isinstance(t, BaseType): raise InvalidType(f"Cannot canonicalize non-base type: {t}") t = t.typ if t in ("int128", "int256", "uint256", "bool", "address", "bytes32"): return t elif t == "decimal": return "fixed168x10" raise InvalidType(f"Invalid or unsupported type: {repr(t)}") # TODO location is unused def make_struct_type(name, location, sigs, members, custom_structs): o = OrderedDict() for key, value in members: if not isinstance(key, vy_ast.Name): raise InvalidType( f"Invalid member variable for struct {key.id}, expected a name.", key, ) o[key.id] = parse_type(value, location, sigs=sigs, custom_structs=custom_structs) return StructType(o, name) # Parses an expression representing a type. Annotation refers to whether # the type is to be located in memory or storage # TODO: location is unused # TODO: rename me to "lll_type_from_annotation" def parse_type(item, location=None, sigs=None, custom_structs=None): # Base and custom types, e.g. num if isinstance(item, vy_ast.Name): if item.id in BASE_TYPES: return BaseType(item.id) elif (sigs is not None) and item.id in sigs: return InterfaceType(item.id) elif (custom_structs is not None) and (item.id in custom_structs): return make_struct_type( item.id, location, sigs, custom_structs[item.id], custom_structs, ) else: raise InvalidType("Invalid base type: " + item.id, item) # Units, e.g. num (1/sec) or contracts elif isinstance(item, vy_ast.Call) and isinstance(item.func, vy_ast.Name): # Contract_types if item.func.id == "address": if sigs and item.args[0].id in sigs: return InterfaceType(item.args[0].id) # Struct types if (custom_structs is not None) and (item.func.id in custom_structs): return make_struct_type( item.id, location, sigs, custom_structs[item.id], custom_structs, ) raise InvalidType("Units are no longer supported", item) # Subscripts elif isinstance(item, vy_ast.Subscript): # Fixed size lists or bytearrays, e.g. num[100] if isinstance(item.slice.value, vy_ast.Int): n_val = item.slice.value.n if not isinstance(n_val, int) or n_val <= 0: raise InvalidType( "Arrays / ByteArrays must have a positive integral number of elements", item.slice.value, ) # ByteArray if getattr(item.value, "id", None) == "Bytes": return ByteArrayType(n_val) elif getattr(item.value, "id", None) == "String": return StringType(n_val) # List else: return ListType( parse_type( item.value, location, sigs, custom_structs=custom_structs, ), n_val, ) elif item.value.id in ("HashMap",) and isinstance(item.slice.value, vy_ast.Tuple): keytype = parse_type( item.slice.value.elements[0], None, sigs, custom_structs=custom_structs, ) return MappingType( keytype, parse_type( item.slice.value.elements[1], location, sigs, custom_structs=custom_structs, ), ) # Mappings, e.g. num[address] else: raise InvalidType("Unknown list type.", item) # Dicts, used to represent mappings, e.g. {uint: uint}. Key must be a base type elif isinstance(item, vy_ast.Dict): warnings.warn( "Anonymous structs have been removed in" " favor of named structs, see VIP300", DeprecationWarning, ) raise InvalidType("Invalid type", item) elif isinstance(item, vy_ast.Tuple): members = [parse_type(x, location, custom_structs=custom_structs) for x in item.elements] return TupleType(members) else: raise InvalidType("Invalid type", item) # byte array overhead, in words. (it should really be 1, but there are # some places in our calling convention where the layout expects 2) BYTE_ARRAY_OVERHEAD = 1 # Gets the maximum number of memory or storage keys needed to ABI-encode # a given type def get_size_of_type(typ): if isinstance(typ, BaseType): return 1 elif isinstance(typ, ByteArrayLike): # 1 word for offset (in static section), 1 word for length, # up to maxlen words for actual data. return ceil32(typ.maxlen) // 32 + BYTE_ARRAY_OVERHEAD elif isinstance(typ, ListType): return get_size_of_type(typ.subtype) * typ.count elif isinstance(typ, MappingType): raise InvalidType("Maps are not supported for function arguments or outputs.") elif isinstance(typ, TupleLike): return sum([get_size_of_type(v) for v in typ.tuple_members()]) else: raise InvalidType(f"Can not get size of type, Unexpected type: {repr(typ)}") def get_type_for_exact_size(n_bytes): """Create a type which will take up exactly n_bytes. Used for allocating internal buffers. Parameters: n_bytes: the number of bytes to allocate Returns: type: A type which can be passed to context.new_variable """ return ByteArrayType(n_bytes - 32 * BYTE_ARRAY_OVERHEAD) def get_type(input): if not hasattr(input, "typ"): typ, len = "num_literal", 32 elif hasattr(input.typ, "maxlen"): typ, len = "Bytes", input.typ.maxlen else: typ, len = input.typ.typ, 32 return typ, len # Is a type representing a number? def is_numeric_type(typ): return isinstance(typ, BaseType) and typ.typ in ("int128", "int256", "uint256", "decimal") # Is a type representing some particular base type? def is_base_type(typ, btypes): if not isinstance(btypes, tuple): btypes = (btypes,) return isinstance(typ, BaseType) and typ.typ in btypes
import abc import copy import warnings from collections import OrderedDict from typing import Any from vyper import ast as vy_ast from vyper.exceptions import CompilerPanic, InvalidType from vyper.utils import BASE_TYPES, ceil32 # Data structure for a type class NodeType(abc.ABC): def __eq__(self, other: Any) -> bool: return type(self) is type(other) and self.eq(other) @abc.abstractmethod def eq(self, other: "NodeType") -> bool: # pragma: no cover """ Checks whether or not additional properties of a ``NodeType`` subclass instance make it equal to another instance of the same type. """ pass # Data structure for a type that represents a 32-byte object class BaseType(NodeType): def __init__( self, typ, unit=False, positional=False, override_signature=False, is_literal=False ): self.typ = typ if unit or positional: raise CompilerPanic("Units are no longer supported") self.override_signature = override_signature self.is_literal = is_literal def eq(self, other): return self.typ == other.typ def __repr__(self): return str(self.typ) class InterfaceType(BaseType): def __init__(self, name): super().__init__("address") self.name = name def __eq__(self, other: Any) -> bool: return isinstance(other, BaseType) and other.typ == "address" class ByteArrayLike(NodeType): def __init__(self, maxlen, is_literal=False): self.maxlen = maxlen self.is_literal = is_literal def eq(self, other): return self.maxlen == other.maxlen def eq_base(self, other): return type(self) is type(other) class StringType(ByteArrayLike): def __repr__(self): return f"String[{self.maxlen}]" # Data structure for a byte array class ByteArrayType(ByteArrayLike): def __repr__(self): return f"Bytes[{self.maxlen}]" # Data structure for a list with some fixed length class ListType(NodeType): def __init__(self, subtype, count, is_literal=False): self.subtype = subtype self.count = count self.is_literal = is_literal def eq(self, other): return other.subtype == self.subtype and other.count == self.count def __repr__(self): return repr(self.subtype) + "[" + str(self.count) + "]" # Data structure for a key-value mapping class MappingType(NodeType): def __init__(self, keytype, valuetype): if not isinstance(keytype, (BaseType, ByteArrayLike)): raise InvalidType("Dictionary keys must be a base type") self.keytype = keytype self.valuetype = valuetype def eq(self, other): return other.keytype == self.keytype and other.valuetype == self.valuetype def __repr__(self): return "HashMap[" + repr(self.valuetype) + ", " + repr(self.keytype) + "]" # Type which has heterogeneous members, i.e. Tuples and Structs class TupleLike(NodeType): def tuple_members(self): return [v for (_k, v) in self.tuple_items()] def tuple_keys(self): return [k for (k, _v) in self.tuple_items()] def tuple_items(self): raise NotImplementedError("compiler panic!: tuple_items must be implemented by TupleLike") # Data structure for a struct, e.g. {a: <type>, b: <type>} # struct can be named or anonymous. name=None indicates anonymous. class StructType(TupleLike): def __init__(self, members, name, is_literal=False): self.members = copy.copy(members) self.name = name self.is_literal = is_literal def eq(self, other): return other.name == self.name and other.members == self.members def __repr__(self): if self.name: return "struct " + self.name else: # Anonymous struct return ( "struct {" + ", ".join([k + ": " + repr(v) for k, v in self.members.items()]) + "}" ) def tuple_items(self): return list(self.members.items()) # Data structure for a list with heterogeneous types, e.g. [int128, bytes32, bytes] class TupleType(TupleLike): def __init__(self, members, is_literal=False): self.members = copy.copy(members) self.is_literal = is_literal def eq(self, other): return other.members == self.members def __repr__(self): return "(" + ", ".join([repr(m) for m in self.members]) + ")" def tuple_items(self): return list(enumerate(self.members)) # Convert type into common form used in ABI def canonicalize_type(t, is_indexed=False): if isinstance(t, ByteArrayLike): # Check to see if maxlen is small enough for events byte_type = "string" if isinstance(t, StringType) else "bytes" return byte_type if isinstance(t, ListType): if not isinstance(t.subtype, (ListType, BaseType)): raise InvalidType(f"List of {t.subtype} not allowed") return canonicalize_type(t.subtype) + f"[{t.count}]" if isinstance(t, TupleLike): return f"({','.join(canonicalize_type(x) for x in t.tuple_members())})" if not isinstance(t, BaseType): raise InvalidType(f"Cannot canonicalize non-base type: {t}") t = t.typ if t in ("int128", "int256", "uint256", "bool", "address", "bytes32"): return t elif t == "decimal": return "fixed168x10" raise InvalidType(f"Invalid or unsupported type: {repr(t)}") # TODO location is unused def make_struct_type(name, location, sigs, members, custom_structs): o = OrderedDict() for key, value in members: if not isinstance(key, vy_ast.Name): raise InvalidType( f"Invalid member variable for struct {key.id}, expected a name.", key, ) o[key.id] = parse_type(value, location, sigs=sigs, custom_structs=custom_structs) return StructType(o, name) # Parses an expression representing a type. Annotation refers to whether # the type is to be located in memory or storage # TODO: location is unused # TODO: rename me to "lll_type_from_annotation" def parse_type(item, location=None, sigs=None, custom_structs=None): # Base and custom types, e.g. num if isinstance(item, vy_ast.Name): if item.id in BASE_TYPES: return BaseType(item.id) elif (sigs is not None) and item.id in sigs: return InterfaceType(item.id) elif (custom_structs is not None) and (item.id in custom_structs): return make_struct_type( item.id, location, sigs, custom_structs[item.id], custom_structs, ) else: raise InvalidType("Invalid base type: " + item.id, item) # Units, e.g. num (1/sec) or contracts elif isinstance(item, vy_ast.Call) and isinstance(item.func, vy_ast.Name): # Contract_types if item.func.id == "address": if sigs and item.args[0].id in sigs: return InterfaceType(item.args[0].id) # Struct types if (custom_structs is not None) and (item.func.id in custom_structs): return make_struct_type( item.id, location, sigs, custom_structs[item.id], custom_structs, ) raise InvalidType("Units are no longer supported", item) # Subscripts elif isinstance(item, vy_ast.Subscript): # Fixed size lists or bytearrays, e.g. num[100] if isinstance(item.slice.value, vy_ast.Int): n_val = item.slice.value.n if not isinstance(n_val, int) or n_val <= 0: raise InvalidType( "Arrays / ByteArrays must have a positive integral number of elements", item.slice.value, ) # ByteArray if getattr(item.value, "id", None) == "Bytes": return ByteArrayType(n_val) elif getattr(item.value, "id", None) == "String": return StringType(n_val) # List else: return ListType( parse_type( item.value, location, sigs, custom_structs=custom_structs, ), n_val, ) elif item.value.id in ("HashMap",) and isinstance(item.slice.value, vy_ast.Tuple): keytype = parse_type( item.slice.value.elements[0], None, sigs, custom_structs=custom_structs, ) return MappingType( keytype, parse_type( item.slice.value.elements[1], location, sigs, custom_structs=custom_structs, ), ) # Mappings, e.g. num[address] else: raise InvalidType("Unknown list type.", item) # Dicts, used to represent mappings, e.g. {uint: uint}. Key must be a base type elif isinstance(item, vy_ast.Dict): warnings.warn( "Anonymous structs have been removed in" " favor of named structs, see VIP300", DeprecationWarning, ) raise InvalidType("Invalid type", item) elif isinstance(item, vy_ast.Tuple): members = [parse_type(x, location, custom_structs=custom_structs) for x in item.elements] return TupleType(members) else: raise InvalidType("Invalid type", item) # byte array overhead, in words. (it should really be 1, but there are # some places in our calling convention where the layout expects 2) BYTE_ARRAY_OVERHEAD = 1 # Gets the maximum number of memory or storage keys needed to ABI-encode # a given type def get_size_of_type(typ): if isinstance(typ, BaseType): return 1 elif isinstance(typ, ByteArrayLike): # 1 word for offset (in static section), 1 word for length, # up to maxlen words for actual data. return ceil32(typ.maxlen) // 32 + BYTE_ARRAY_OVERHEAD elif isinstance(typ, ListType): return get_size_of_type(typ.subtype) * typ.count elif isinstance(typ, MappingType): raise InvalidType("Maps are not supported for function arguments or outputs.") elif isinstance(typ, TupleLike): return sum([get_size_of_type(v) for v in typ.tuple_members()]) else: raise InvalidType(f"Can not get size of type, Unexpected type: {repr(typ)}") def get_type_for_exact_size(n_bytes): """Create a type which will take up exactly n_bytes. Used for allocating internal buffers. Parameters: n_bytes: the number of bytes to allocate Returns: type: A type which can be passed to context.new_variable """ return ByteArrayType(n_bytes - 32 * BYTE_ARRAY_OVERHEAD) def get_type(input): if not hasattr(input, "typ"): typ, len = "num_literal", 32 elif hasattr(input.typ, "maxlen"): typ, len = "Bytes", input.typ.maxlen else: typ, len = input.typ.typ, 32 return typ, len # Is a type representing a number? def is_numeric_type(typ): return isinstance(typ, BaseType) and typ.typ in ("int128", "int256", "uint256", "decimal") # Is a type representing some particular base type? def is_base_type(typ, btypes): if not isinstance(btypes, tuple): btypes = (btypes,) return isinstance(typ, BaseType) and typ.typ in btypes
import argparse from typing import ( Any, Dict, List, Optional, Sequence, Set, Tuple, Type, Union, TYPE_CHECKING, ) if TYPE_CHECKING: from ..config import PoeConfig ArgParams = Dict[str, Any] ArgsDef = Union[List[str], List[ArgParams], Dict[str, ArgParams]] arg_param_schema: Dict[str, Union[Type, Tuple[Type, ...]]] = { "default": (str, int, float, bool), "help": str, "name": str, "options": (list, tuple), "positional": (bool, str), "required": bool, "type": str, } arg_types: Dict[str, Type] = { "string": str, "float": float, "integer": int, "boolean": bool, } class PoeTaskArgs: _args: Tuple[ArgParams, ...] def __init__(self, args_def: ArgsDef, task_name: str): self._args = self._normalize_args_def(args_def) self._task_name = task_name @classmethod def _normalize_args_def(cls, args_def: ArgsDef) -> Tuple[ArgParams, ...]: """ args_def can be defined as a dictionary of ArgParams, or a list of strings, or ArgParams. Here we normalize it to a list of ArgParams, assuming that it has already been validated. """ result = [] if isinstance(args_def, list): for item in args_def: if isinstance(item, str): result.append({"name": item, "options": (f"--{item}",)}) else: result.append( dict( item, options=cls._get_arg_options_list(item), ) ) else: for name, params in args_def.items(): result.append( dict( params, name=name, options=cls._get_arg_options_list(params, name), ) ) return tuple(result) @staticmethod def _get_arg_options_list(arg: ArgParams, name: Optional[str] = None): position = arg.get("positional", False) name = name or arg["name"] if position: if isinstance(position, str): return [position] return [name] return tuple(arg.get("options", (f"--{name}",))) @classmethod def get_help_content( cls, args_def: Optional[ArgsDef] ) -> List[Tuple[Tuple[str, ...], str]]: if args_def is None: return [] return [ (arg["options"], arg.get("help", "")) for arg in cls._normalize_args_def(args_def) ] @classmethod def validate_def(cls, task_name: str, args_def: ArgsDef) -> Optional[str]: arg_names: Set[str] = set() if isinstance(args_def, list): for item in args_def: # can be a list of strings (just arg name) or ArgConfig dictionaries if isinstance(item, str): arg_name = item elif isinstance(item, dict): arg_name = item.get("name", "") error = cls._validate_params(item, arg_name, task_name) if error: return error else: return f"Arg {item!r} of task {task_name!r} has invlaid type" error = cls._validate_name(arg_name, task_name, arg_names) if error: return error elif isinstance(args_def, dict): for arg_name, params in args_def.items(): error = cls._validate_name(arg_name, task_name, arg_names) if error: return error if "name" in params: return ( f"Unexpected 'name' option for arg {arg_name!r} of task " f"{task_name!r}" ) error = cls._validate_params(params, arg_name, task_name) if error: return error error = cls._validate_type(params, arg_name, task_name) if error: return error return None @classmethod def _validate_name( cls, name: Any, task_name: str, arg_names: Set[str] ) -> Optional[str]: if not isinstance(name, str): return f"Arg name {name!r} of task {task_name!r} should be a string" if not name.replace("-", "_").isidentifier(): return ( f"Arg name {name!r} of task {task_name!r} is not a valid 'identifier'" f"see the following documentation for details" f"https://docs.python.org/3/reference/lexical_analysis.html#identifiers" ) if name in arg_names: return f"Duplicate arg name {name!r} for task {task_name!r}" arg_names.add(name) return None @classmethod def _validate_params( cls, params: ArgParams, arg_name: str, task_name: str ) -> Optional[str]: for param, value in params.items(): if param not in arg_param_schema: return ( f"Invalid option {param!r} for arg {arg_name!r} of task " f"{task_name!r}" ) if not isinstance(value, arg_param_schema[param]): return ( f"Invalid value for option {param!r} of arg {arg_name!r} of" f" task {task_name!r}" ) positional = params.get("positional", False) if positional: if params.get("type") == "boolean": return ( f"Positional argument {arg_name!r} of task {task_name!r} may not" "have type 'boolean'" ) if params.get("options") is not None: return ( f"Positional argument {arg_name!r} of task {task_name!r} may not" "have options defined" ) if isinstance(positional, str) and not positional.isidentifier(): return ( f"positional name {positional!r} for arg {arg_name!r} of task " f"{task_name!r} is not a valid 'identifier' see the following " "documentation for details" "https://docs.python.org/3/reference/lexical_analysis.html#identifiers" ) return None @classmethod def _validate_type( cls, params: ArgParams, arg_name: str, task_name: str ) -> Optional[str]: if "type" in params and params["type"] not in arg_types: return ( f"{params["type"]!r} is not a valid type for arg {arg_name!r} of task " f"{task_name!r}. Choose one of " "{" f'{' '.join(sorted(str_type for str_type in arg_types.keys()))}' "}" ) return None def build_parser(self) -> argparse.ArgumentParser: parser = argparse.ArgumentParser( prog=f"poe {self._task_name}", add_help=False, allow_abbrev=False ) for arg in self._args: parser.add_argument( *arg["options"], **self._get_argument_params(arg), ) return parser def _get_argument_params(self, arg: ArgParams): default = arg.get("default") result = { "default": default, "help": arg.get("help", ""), } required = arg.get("required", False) arg_type = str(arg.get("type")) if arg.get("positional", False): if not required: result["nargs"] = "?" else: result["dest"] = arg["name"] result["required"] = required if arg_type == "boolean": result["action"] = "store_false" if default else "store_true" else: result["type"] = arg_types.get(arg_type, str) return result def parse(self, extra_args: Sequence[str]): parsed_args = vars(self.build_parser().parse_args(extra_args)) # Ensure positional args are still exposed by name even if the were parsed with # alternate identifiers for arg in self._args: if isinstance(arg.get("positional"), str): parsed_args[arg["name"]] = parsed_args[arg["positional"]] del parsed_args[arg["positional"]] # args named with dash case are converted to snake case before being exposed return {name.replace("-", "_"): value for name, value in parsed_args.items()}
import argparse from typing import ( Any, Dict, List, Optional, Sequence, Set, Tuple, Type, Union, TYPE_CHECKING, ) if TYPE_CHECKING: from ..config import PoeConfig ArgParams = Dict[str, Any] ArgsDef = Union[List[str], List[ArgParams], Dict[str, ArgParams]] arg_param_schema: Dict[str, Union[Type, Tuple[Type, ...]]] = { "default": (str, int, float, bool), "help": str, "name": str, "options": (list, tuple), "positional": (bool, str), "required": bool, "type": str, } arg_types: Dict[str, Type] = { "string": str, "float": float, "integer": int, "boolean": bool, } class PoeTaskArgs: _args: Tuple[ArgParams, ...] def __init__(self, args_def: ArgsDef, task_name: str): self._args = self._normalize_args_def(args_def) self._task_name = task_name @classmethod def _normalize_args_def(cls, args_def: ArgsDef) -> Tuple[ArgParams, ...]: """ args_def can be defined as a dictionary of ArgParams, or a list of strings, or ArgParams. Here we normalize it to a list of ArgParams, assuming that it has already been validated. """ result = [] if isinstance(args_def, list): for item in args_def: if isinstance(item, str): result.append({"name": item, "options": (f"--{item}",)}) else: result.append( dict( item, options=cls._get_arg_options_list(item), ) ) else: for name, params in args_def.items(): result.append( dict( params, name=name, options=cls._get_arg_options_list(params, name), ) ) return tuple(result) @staticmethod def _get_arg_options_list(arg: ArgParams, name: Optional[str] = None): position = arg.get("positional", False) name = name or arg["name"] if position: if isinstance(position, str): return [position] return [name] return tuple(arg.get("options", (f"--{name}",))) @classmethod def get_help_content( cls, args_def: Optional[ArgsDef] ) -> List[Tuple[Tuple[str, ...], str]]: if args_def is None: return [] return [ (arg["options"], arg.get("help", "")) for arg in cls._normalize_args_def(args_def) ] @classmethod def validate_def(cls, task_name: str, args_def: ArgsDef) -> Optional[str]: arg_names: Set[str] = set() if isinstance(args_def, list): for item in args_def: # can be a list of strings (just arg name) or ArgConfig dictionaries if isinstance(item, str): arg_name = item elif isinstance(item, dict): arg_name = item.get("name", "") error = cls._validate_params(item, arg_name, task_name) if error: return error else: return f"Arg {item!r} of task {task_name!r} has invlaid type" error = cls._validate_name(arg_name, task_name, arg_names) if error: return error elif isinstance(args_def, dict): for arg_name, params in args_def.items(): error = cls._validate_name(arg_name, task_name, arg_names) if error: return error if "name" in params: return ( f"Unexpected 'name' option for arg {arg_name!r} of task " f"{task_name!r}" ) error = cls._validate_params(params, arg_name, task_name) if error: return error error = cls._validate_type(params, arg_name, task_name) if error: return error return None @classmethod def _validate_name( cls, name: Any, task_name: str, arg_names: Set[str] ) -> Optional[str]: if not isinstance(name, str): return f"Arg name {name!r} of task {task_name!r} should be a string" if not name.replace("-", "_").isidentifier(): return ( f"Arg name {name!r} of task {task_name!r} is not a valid 'identifier'" f"see the following documentation for details" f"https://docs.python.org/3/reference/lexical_analysis.html#identifiers" ) if name in arg_names: return f"Duplicate arg name {name!r} for task {task_name!r}" arg_names.add(name) return None @classmethod def _validate_params( cls, params: ArgParams, arg_name: str, task_name: str ) -> Optional[str]: for param, value in params.items(): if param not in arg_param_schema: return ( f"Invalid option {param!r} for arg {arg_name!r} of task " f"{task_name!r}" ) if not isinstance(value, arg_param_schema[param]): return ( f"Invalid value for option {param!r} of arg {arg_name!r} of" f" task {task_name!r}" ) positional = params.get("positional", False) if positional: if params.get("type") == "boolean": return ( f"Positional argument {arg_name!r} of task {task_name!r} may not" "have type 'boolean'" ) if params.get("options") is not None: return ( f"Positional argument {arg_name!r} of task {task_name!r} may not" "have options defined" ) if isinstance(positional, str) and not positional.isidentifier(): return ( f"positional name {positional!r} for arg {arg_name!r} of task " f"{task_name!r} is not a valid 'identifier' see the following " "documentation for details" "https://docs.python.org/3/reference/lexical_analysis.html#identifiers" ) return None @classmethod def _validate_type( cls, params: ArgParams, arg_name: str, task_name: str ) -> Optional[str]: if "type" in params and params["type"] not in arg_types: return ( f"{params['type']!r} is not a valid type for arg {arg_name!r} of task " f"{task_name!r}. Choose one of " "{" f'{" ".join(sorted(str_type for str_type in arg_types.keys()))}' "}" ) return None def build_parser(self) -> argparse.ArgumentParser: parser = argparse.ArgumentParser( prog=f"poe {self._task_name}", add_help=False, allow_abbrev=False ) for arg in self._args: parser.add_argument( *arg["options"], **self._get_argument_params(arg), ) return parser def _get_argument_params(self, arg: ArgParams): default = arg.get("default") result = { "default": default, "help": arg.get("help", ""), } required = arg.get("required", False) arg_type = str(arg.get("type")) if arg.get("positional", False): if not required: result["nargs"] = "?" else: result["dest"] = arg["name"] result["required"] = required if arg_type == "boolean": result["action"] = "store_false" if default else "store_true" else: result["type"] = arg_types.get(arg_type, str) return result def parse(self, extra_args: Sequence[str]): parsed_args = vars(self.build_parser().parse_args(extra_args)) # Ensure positional args are still exposed by name even if the were parsed with # alternate identifiers for arg in self._args: if isinstance(arg.get("positional"), str): parsed_args[arg["name"]] = parsed_args[arg["positional"]] del parsed_args[arg["positional"]] # args named with dash case are converted to snake case before being exposed return {name.replace("-", "_"): value for name, value in parsed_args.items()}
from bokeh.embed import json_item from bokeh.plotting import figure from bokeh.models import FactorRange, ColumnDataSource, HoverTool, NumeralTickFormatter from django.http import JsonResponse from .helpers import * def _get_plot_data(_data_type): if _data_type == 'infections': df_dict = get_dataframe('confirmed_US') else: df_dict = get_dataframe('deaths_US') return df_dict def plot_affiliation(request, frequency='daily', rolling_window=14, exclude_states=[], data_type='infections'): """ Plots data based on 'red' and 'blue' affiliation of states. Relies on global variable from helpers.py that lists the political affiliation per state. :param request: The HTML request that should include values for 'frequency', 'rolling_window', 'data_type' and 'exclude_states'. See the parameter descriptions below for contraints and defaults for each parameter. :param frequency: (optional) Default is 'daily'. Plot 'daily' or 'cumulative' values. :param rolling_window: (optional) Default 14. The number of days to use when drawing the daily average line in the plot. :param exclude_states: (optional) Default is None. A list of states to exclude from the plotted values. :param data_type: (optional) Default is 'infections. Plot 'infections' data or 'deaths' data. :return: A Bokeh JSON formatted plot that can be handled by JavaScript for HTML presentation. """ if request is not None: frequency = request.GET.get('frequency', 'infections').lower() rolling_window = int(request.GET.get('rolling_window', 15)) exclude_states = request.GET.get('exclude_states', False) data_type = request.GET.get('data_type', 'infections').lower() if exclude_states == 'null': exclude_counties = False # for p in [frequency, rolling_window, exclude_states, data_type]: # print(p) # df = get_dataframe('confirmed_US') if data_type == 'infections' else get_dataframe('deaths_US') df_dict = _get_plot_data(data_type) # _, date_cols_text, date_cols_dates = get_column_groups(df) df = df_dict['df'] date_cols_text = df_dict['date_cols_text'] date_cols_dates = df_dict['date_cols_dates'] if frequency == 'daily': all_data = get_by_day(df) else: all_data = df.copy() plot_data_red = all_data[all_data.political_affiliation == 'red'].sum()[date_cols_text].values plot_data_blue = all_data[all_data.political_affiliation == 'blue'].sum()[date_cols_text].values plot_data_purple = all_data[all_data.political_affiliation == 'purple'].sum()[date_cols_text].values # setup x axis groupings factors = [(str(c.year), c.month_name(), str(c.day)) for c in date_cols_dates] # setup Hover tool hover = HoverTool() hover.tooltips = [ ("Date", "@date"), (f"{data_type.capitalize()}", "@val{0,0}"), (f"{rolling_window}-day Avg", "@rolling_avg{0,0.0}") ] # setup figure p = figure(x_range=FactorRange(*factors), sizing_mode='stretch_both', #plot_height=500, plot_width=900, y_axis_label=data_type, output_backend="webgl", toolbar_location=None, tools=[hover], title=f"New Infections{" by Day" if frequency=="daily" else ""}") p.title.text_font_size = '12pt' p.yaxis.formatter = NumeralTickFormatter(format="0,000") source_red = ColumnDataSource(data=dict(date=factors, val=plot_data_red, rolling_avg=pd.Series(plot_data_red).rolling(rolling_window).mean().values)) source_blue = ColumnDataSource(data=dict(date=factors, val=plot_data_blue, rolling_avg=pd.Series(plot_data_blue).rolling( rolling_window).mean().values)) if plot_data_purple.any(): source_purple = ColumnDataSource(data=dict(date=factors, val=plot_data_purple, rolling_avg=pd.Series(plot_data_purple).rolling( rolling_window).mean().values)) b_red = p.vbar(x='date', top='val', source=source_red, color='red', width=.5, alpha=.5) b_blue = p.vbar(x='date', top='val', source=source_blue, color='blue', width=.5, alpha=.5) if frequency == 'daily': l_red = p.line(x='date', y='rolling_avg', source=source_red, color='red', width=3, legend_label=f"{rolling_window}-Day Rolling Average Red") l_blue = p.line(x='date', y='rolling_avg', source=source_blue, color='blue', width=3, legend_label=f"{rolling_window}-Day Rolling Average Blue") if plot_data_purple.any(): l_purple = p.line(x='date', y='rolling_avg', source=source_purple, color='purple', width=3, legend_label=f"{rolling_window}-Day Rolling Average Purple") p.legend.location = 'top_left' p.xaxis.major_label_orientation = 1 p.xaxis.group_text_font_size = "10pt" # months size p.xaxis.major_label_text_font_size = "3pt" # date size p.xaxis.major_tick_line_color = None p.yaxis.major_label_orientation = 1 p.xgrid.grid_line_color = None return JsonResponse(json_item(p))
from bokeh.embed import json_item from bokeh.plotting import figure from bokeh.models import FactorRange, ColumnDataSource, HoverTool, NumeralTickFormatter from django.http import JsonResponse from .helpers import * def _get_plot_data(_data_type): if _data_type == 'infections': df_dict = get_dataframe('confirmed_US') else: df_dict = get_dataframe('deaths_US') return df_dict def plot_affiliation(request, frequency='daily', rolling_window=14, exclude_states=[], data_type='infections'): """ Plots data based on 'red' and 'blue' affiliation of states. Relies on global variable from helpers.py that lists the political affiliation per state. :param request: The HTML request that should include values for 'frequency', 'rolling_window', 'data_type' and 'exclude_states'. See the parameter descriptions below for contraints and defaults for each parameter. :param frequency: (optional) Default is 'daily'. Plot 'daily' or 'cumulative' values. :param rolling_window: (optional) Default 14. The number of days to use when drawing the daily average line in the plot. :param exclude_states: (optional) Default is None. A list of states to exclude from the plotted values. :param data_type: (optional) Default is 'infections. Plot 'infections' data or 'deaths' data. :return: A Bokeh JSON formatted plot that can be handled by JavaScript for HTML presentation. """ if request is not None: frequency = request.GET.get('frequency', 'infections').lower() rolling_window = int(request.GET.get('rolling_window', 15)) exclude_states = request.GET.get('exclude_states', False) data_type = request.GET.get('data_type', 'infections').lower() if exclude_states == 'null': exclude_counties = False # for p in [frequency, rolling_window, exclude_states, data_type]: # print(p) # df = get_dataframe('confirmed_US') if data_type == 'infections' else get_dataframe('deaths_US') df_dict = _get_plot_data(data_type) # _, date_cols_text, date_cols_dates = get_column_groups(df) df = df_dict['df'] date_cols_text = df_dict['date_cols_text'] date_cols_dates = df_dict['date_cols_dates'] if frequency == 'daily': all_data = get_by_day(df) else: all_data = df.copy() plot_data_red = all_data[all_data.political_affiliation == 'red'].sum()[date_cols_text].values plot_data_blue = all_data[all_data.political_affiliation == 'blue'].sum()[date_cols_text].values plot_data_purple = all_data[all_data.political_affiliation == 'purple'].sum()[date_cols_text].values # setup x axis groupings factors = [(str(c.year), c.month_name(), str(c.day)) for c in date_cols_dates] # setup Hover tool hover = HoverTool() hover.tooltips = [ ("Date", "@date"), (f"{data_type.capitalize()}", "@val{0,0}"), (f"{rolling_window}-day Avg", "@rolling_avg{0,0.0}") ] # setup figure p = figure(x_range=FactorRange(*factors), sizing_mode='stretch_both', #plot_height=500, plot_width=900, y_axis_label=data_type, output_backend="webgl", toolbar_location=None, tools=[hover], title=f"New Infections{' by Day' if frequency=='daily' else ''}") p.title.text_font_size = '12pt' p.yaxis.formatter = NumeralTickFormatter(format="0,000") source_red = ColumnDataSource(data=dict(date=factors, val=plot_data_red, rolling_avg=pd.Series(plot_data_red).rolling(rolling_window).mean().values)) source_blue = ColumnDataSource(data=dict(date=factors, val=plot_data_blue, rolling_avg=pd.Series(plot_data_blue).rolling( rolling_window).mean().values)) if plot_data_purple.any(): source_purple = ColumnDataSource(data=dict(date=factors, val=plot_data_purple, rolling_avg=pd.Series(plot_data_purple).rolling( rolling_window).mean().values)) b_red = p.vbar(x='date', top='val', source=source_red, color='red', width=.5, alpha=.5) b_blue = p.vbar(x='date', top='val', source=source_blue, color='blue', width=.5, alpha=.5) if frequency == 'daily': l_red = p.line(x='date', y='rolling_avg', source=source_red, color='red', width=3, legend_label=f"{rolling_window}-Day Rolling Average Red") l_blue = p.line(x='date', y='rolling_avg', source=source_blue, color='blue', width=3, legend_label=f"{rolling_window}-Day Rolling Average Blue") if plot_data_purple.any(): l_purple = p.line(x='date', y='rolling_avg', source=source_purple, color='purple', width=3, legend_label=f"{rolling_window}-Day Rolling Average Purple") p.legend.location = 'top_left' p.xaxis.major_label_orientation = 1 p.xaxis.group_text_font_size = "10pt" # months size p.xaxis.major_label_text_font_size = "3pt" # date size p.xaxis.major_tick_line_color = None p.yaxis.major_label_orientation = 1 p.xgrid.grid_line_color = None return JsonResponse(json_item(p))
import argparse import ast import codecs import collections import contextlib import keyword import re import string import sys import tokenize import warnings from typing import Any from typing import cast from typing import Container from typing import Dict from typing import Generator from typing import Iterable from typing import List from typing import Match from typing import NamedTuple from typing import Optional from typing import Pattern from typing import Sequence from typing import Set from typing import Tuple from typing import Type from typing import Union from tokenize_rt import NON_CODING_TOKENS from tokenize_rt import Offset from tokenize_rt import parse_string_literal from tokenize_rt import reversed_enumerate from tokenize_rt import rfind_string_parts from tokenize_rt import src_to_tokens from tokenize_rt import Token from tokenize_rt import tokens_to_src from tokenize_rt import UNIMPORTANT_WS MinVersion = Tuple[int, ...] DotFormatPart = Tuple[str, Optional[str], Optional[str], Optional[str]] PercentFormatPart = Tuple[ Optional[str], Optional[str], Optional[str], Optional[str], str, ] PercentFormat = Tuple[str, Optional[PercentFormatPart]] ListCompOrGeneratorExp = Union[ast.ListComp, ast.GeneratorExp] ListOrTuple = Union[ast.List, ast.Tuple] NameOrAttr = Union[ast.Name, ast.Attribute] AnyFunctionDef = Union[ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda] SyncFunctionDef = Union[ast.FunctionDef, ast.Lambda] _stdlib_parse_format = string.Formatter().parse _KEYWORDS = frozenset(keyword.kwlist) _EXPR_NEEDS_PARENS: Tuple[Type[ast.expr], ...] = ( ast.Await, ast.BinOp, ast.BoolOp, ast.Compare, ast.GeneratorExp, ast.IfExp, ast.Lambda, ast.UnaryOp, ) if sys.version_info >= (3, 8): # pragma: no cover (py38+) _EXPR_NEEDS_PARENS += (ast.NamedExpr,) def parse_format(s: str) -> Tuple[DotFormatPart, ...]: """Makes the empty string not a special case. In the stdlib, there's loss of information (the type) on the empty string. """ parsed = tuple(_stdlib_parse_format(s)) if not parsed: return ((s, None, None, None),) else: return parsed def unparse_parsed_string(parsed: Sequence[DotFormatPart]) -> str: def _convert_tup(tup: DotFormatPart) -> str: ret, field_name, format_spec, conversion = tup ret = ret.replace('{', '{{') ret = ret.replace('}', '}}') if field_name is not None: ret += '{' + field_name if conversion: ret += '!' + conversion if format_spec: ret += ':' + format_spec ret += '}' return ret return ''.join(_convert_tup(tup) for tup in parsed) def _ast_to_offset(node: Union[ast.expr, ast.stmt]) -> Offset: return Offset(node.lineno, node.col_offset) def ast_parse(contents_text: str) -> ast.Module: # intentionally ignore warnings, we might be fixing warning-ridden syntax with warnings.catch_warnings(): warnings.simplefilter('ignore') return ast.parse(contents_text.encode()) def inty(s: str) -> bool: try: int(s) return True except (ValueError, TypeError): return False BRACES = {'(': ')', '[': ']', '{': '}'} OPENING, CLOSING = frozenset(BRACES), frozenset(BRACES.values()) SET_TRANSFORM = (ast.List, ast.ListComp, ast.GeneratorExp, ast.Tuple) def _is_wtf(func: str, tokens: List[Token], i: int) -> bool: return tokens[i].src != func or tokens[i + 1].src != '(' def _process_set_empty_literal(tokens: List[Token], start: int) -> None: if _is_wtf('set', tokens, start): return i = start + 2 brace_stack = ['('] while brace_stack: token = tokens[i].src if token == BRACES[brace_stack[-1]]: brace_stack.pop() elif token in BRACES: brace_stack.append(token) elif '\n' in token: # Contains a newline, could cause a SyntaxError, bail return i += 1 # Remove the inner tokens del tokens[start + 2:i - 1] def _search_until(tokens: List[Token], idx: int, arg: ast.expr) -> int: while ( idx < len(tokens) and not ( tokens[idx].line == arg.lineno and tokens[idx].utf8_byte_offset == arg.col_offset ) ): idx += 1 return idx if sys.version_info >= (3, 8): # pragma: no cover (py38+) # python 3.8 fixed the offsets of generators / tuples def _arg_token_index(tokens: List[Token], i: int, arg: ast.expr) -> int: idx = _search_until(tokens, i, arg) + 1 while idx < len(tokens) and tokens[idx].name in NON_CODING_TOKENS: idx += 1 return idx else: # pragma: no cover (<py38) def _arg_token_index(tokens: List[Token], i: int, arg: ast.expr) -> int: # lists containing non-tuples report the first element correctly if isinstance(arg, ast.List): # If the first element is a tuple, the ast lies to us about its col # offset. We must find the first `(` token after the start of the # list element. if isinstance(arg.elts[0], ast.Tuple): i = _search_until(tokens, i, arg) return _find_open_paren(tokens, i) else: return _search_until(tokens, i, arg.elts[0]) # others' start position points at their first child node already else: return _search_until(tokens, i, arg) class Victims(NamedTuple): starts: List[int] ends: List[int] first_comma_index: Optional[int] arg_index: int def _victims( tokens: List[Token], start: int, arg: ast.expr, gen: bool, ) -> Victims: starts = [start] start_depths = [1] ends: List[int] = [] first_comma_index = None arg_depth = None arg_index = _arg_token_index(tokens, start, arg) brace_stack = [tokens[start].src] i = start + 1 while brace_stack: token = tokens[i].src is_start_brace = token in BRACES is_end_brace = token == BRACES[brace_stack[-1]] if i == arg_index: arg_depth = len(brace_stack) if is_start_brace: brace_stack.append(token) # Remove all braces before the first element of the inner # comprehension's target. if is_start_brace and arg_depth is None: start_depths.append(len(brace_stack)) starts.append(i) if ( token == ',' and len(brace_stack) == arg_depth and first_comma_index is None ): first_comma_index = i if is_end_brace and len(brace_stack) in start_depths: if tokens[i - 2].src == ',' and tokens[i - 1].src == ' ': ends.extend((i - 2, i - 1, i)) elif tokens[i - 1].src == ',': ends.extend((i - 1, i)) else: ends.append(i) if len(brace_stack) > 1 and tokens[i + 1].src == ',': ends.append(i + 1) if is_end_brace: brace_stack.pop() i += 1 # May need to remove a trailing comma for a comprehension if gen: i -= 2 while tokens[i].name in NON_CODING_TOKENS: i -= 1 if tokens[i].src == ',': ends.append(i) return Victims(starts, sorted(set(ends)), first_comma_index, arg_index) def _find_token(tokens: List[Token], i: int, src: str) -> int: while tokens[i].src != src: i += 1 return i def _find_open_paren(tokens: List[Token], i: int) -> int: return _find_token(tokens, i, '(') def _is_on_a_line_by_self(tokens: List[Token], i: int) -> bool: return ( tokens[i - 2].name == 'NL' and tokens[i - 1].name == UNIMPORTANT_WS and tokens[i + 1].name == 'NL' ) def _remove_brace(tokens: List[Token], i: int) -> None: if _is_on_a_line_by_self(tokens, i): del tokens[i - 1:i + 2] else: del tokens[i] def _process_set_literal( tokens: List[Token], start: int, arg: ast.expr, ) -> None: if _is_wtf('set', tokens, start): return gen = isinstance(arg, ast.GeneratorExp) set_victims = _victims(tokens, start + 1, arg, gen=gen) del set_victims.starts[0] end_index = set_victims.ends.pop() tokens[end_index] = Token('OP', '}') for index in reversed(set_victims.starts + set_victims.ends): _remove_brace(tokens, index) tokens[start:start + 2] = [Token('OP', '{')] def _process_dict_comp( tokens: List[Token], start: int, arg: ListCompOrGeneratorExp, ) -> None: if _is_wtf('dict', tokens, start): return dict_victims = _victims(tokens, start + 1, arg, gen=True) elt_victims = _victims(tokens, dict_victims.arg_index, arg.elt, gen=True) del dict_victims.starts[0] end_index = dict_victims.ends.pop() tokens[end_index] = Token('OP', '}') for index in reversed(dict_victims.ends): _remove_brace(tokens, index) # See #6, Fix SyntaxError from rewriting dict((a, b)for a, b in y) if tokens[elt_victims.ends[-1] + 1].src == 'for': tokens.insert(elt_victims.ends[-1] + 1, Token(UNIMPORTANT_WS, ' ')) for index in reversed(elt_victims.ends): _remove_brace(tokens, index) assert elt_victims.first_comma_index is not None tokens[elt_victims.first_comma_index] = Token('OP', ':') for index in reversed(dict_victims.starts + elt_victims.starts): _remove_brace(tokens, index) tokens[start:start + 2] = [Token('OP', '{')] def _process_is_literal( tokens: List[Token], i: int, compare: Union[ast.Is, ast.IsNot], ) -> None: while tokens[i].src != 'is': i -= 1 if isinstance(compare, ast.Is): tokens[i] = tokens[i]._replace(src='==') else: tokens[i] = tokens[i]._replace(src='!=') # since we iterate backward, the dummy tokens keep the same length i += 1 while tokens[i].src != 'not': tokens[i] = Token('DUMMY', '') i += 1 tokens[i] = Token('DUMMY', '') LITERAL_TYPES = (ast.Str, ast.Num, ast.Bytes) class Py2CompatibleVisitor(ast.NodeVisitor): def __init__(self) -> None: self.dicts: Dict[Offset, ListCompOrGeneratorExp] = {} self.sets: Dict[Offset, ast.expr] = {} self.set_empty_literals: Dict[Offset, ListOrTuple] = {} self.is_literal: Dict[Offset, Union[ast.Is, ast.IsNot]] = {} def visit_Call(self, node: ast.Call) -> None: if ( isinstance(node.func, ast.Name) and node.func.id == 'set' and len(node.args) == 1 and not node.keywords and isinstance(node.args[0], SET_TRANSFORM) ): arg, = node.args key = _ast_to_offset(node.func) if isinstance(arg, (ast.List, ast.Tuple)) and not arg.elts: self.set_empty_literals[key] = arg else: self.sets[key] = arg elif ( isinstance(node.func, ast.Name) and node.func.id == 'dict' and len(node.args) == 1 and not node.keywords and isinstance(node.args[0], (ast.ListComp, ast.GeneratorExp)) and isinstance(node.args[0].elt, (ast.Tuple, ast.List)) and len(node.args[0].elt.elts) == 2 ): self.dicts[_ast_to_offset(node.func)] = node.args[0] self.generic_visit(node) def visit_Compare(self, node: ast.Compare) -> None: left = node.left for op, right in zip(node.ops, node.comparators): if ( isinstance(op, (ast.Is, ast.IsNot)) and ( isinstance(left, LITERAL_TYPES) or isinstance(right, LITERAL_TYPES) ) ): self.is_literal[_ast_to_offset(right)] = op left = right self.generic_visit(node) def _fix_py2_compatible(contents_text: str) -> str: try: ast_obj = ast_parse(contents_text) except SyntaxError: return contents_text visitor = Py2CompatibleVisitor() visitor.visit(ast_obj) if not any(( visitor.dicts, visitor.sets, visitor.set_empty_literals, visitor.is_literal, )): return contents_text try: tokens = src_to_tokens(contents_text) except tokenize.TokenError: # pragma: no cover (bpo-2180) return contents_text for i, token in reversed_enumerate(tokens): if token.offset in visitor.dicts: _process_dict_comp(tokens, i, visitor.dicts[token.offset]) elif token.offset in visitor.set_empty_literals: _process_set_empty_literal(tokens, i) elif token.offset in visitor.sets: _process_set_literal(tokens, i, visitor.sets[token.offset]) elif token.offset in visitor.is_literal: _process_is_literal(tokens, i, visitor.is_literal[token.offset]) return tokens_to_src(tokens) def _imports_future(contents_text: str, future_name: str) -> bool: try: ast_obj = ast_parse(contents_text) except SyntaxError: return False for node in ast_obj.body: # Docstring if isinstance(node, ast.Expr) and isinstance(node.value, ast.Str): continue elif isinstance(node, ast.ImportFrom): if ( node.level == 0 and node.module == '__future__' and any(name.name == future_name for name in node.names) ): return True elif node.module == '__future__': continue else: return False else: return False return False # https://docs.python.org/3/reference/lexical_analysis.html ESCAPE_STARTS = frozenset(( '\n', '\r', '\\', "'", '"', 'a', 'b', 'f', 'n', 'r', 't', 'v', '0', '1', '2', '3', '4', '5', '6', '7', # octal escapes 'x', # hex escapes )) ESCAPE_RE = re.compile(r'\\.', re.DOTALL) NAMED_ESCAPE_NAME = re.compile(r'\{[^}]+\}') def _fix_escape_sequences(token: Token) -> Token: prefix, rest = parse_string_literal(token.src) actual_prefix = prefix.lower() if 'r' in actual_prefix or '\\' not in rest: return token is_bytestring = 'b' in actual_prefix def _is_valid_escape(match: Match[str]) -> bool: c = match.group()[1] return ( c in ESCAPE_STARTS or (not is_bytestring and c in 'uU') or ( not is_bytestring and c == 'N' and bool(NAMED_ESCAPE_NAME.match(rest, match.end())) ) ) has_valid_escapes = False has_invalid_escapes = False for match in ESCAPE_RE.finditer(rest): if _is_valid_escape(match): has_valid_escapes = True else: has_invalid_escapes = True def cb(match: Match[str]) -> str: matched = match.group() if _is_valid_escape(match): return matched else: return fr'\{matched}' if has_invalid_escapes and (has_valid_escapes or 'u' in actual_prefix): return token._replace(src=prefix + ESCAPE_RE.sub(cb, rest)) elif has_invalid_escapes and not has_valid_escapes: return token._replace(src=prefix + 'r' + rest) else: return token def _remove_u_prefix(token: Token) -> Token: prefix, rest = parse_string_literal(token.src) if 'u' not in prefix.lower(): return token else: new_prefix = prefix.replace('u', '').replace('U', '') return token._replace(src=new_prefix + rest) def _fix_ur_literals(token: Token) -> Token: prefix, rest = parse_string_literal(token.src) if prefix.lower() != 'ur': return token else: def cb(match: Match[str]) -> str: escape = match.group() if escape[1].lower() == 'u': return escape else: return '\\' + match.group() rest = ESCAPE_RE.sub(cb, rest) prefix = prefix.replace('r', '').replace('R', '') return token._replace(src=prefix + rest) def _fix_long(src: str) -> str: return src.rstrip('lL') def _fix_octal(s: str) -> str: if not s.startswith('0') or not s.isdigit() or s == len(s) * '0': return s elif len(s) == 2: return s[1:] else: return '0o' + s[1:] def _fix_extraneous_parens(tokens: List[Token], i: int) -> None: # search forward for another non-coding token i += 1 while tokens[i].name in NON_CODING_TOKENS: i += 1 # if we did not find another brace, return immediately if tokens[i].src != '(': return start = i depth = 1 while depth: i += 1 # found comma or yield at depth 1: this is a tuple / coroutine if depth == 1 and tokens[i].src in {',', 'yield'}: return elif tokens[i].src in OPENING: depth += 1 elif tokens[i].src in CLOSING: depth -= 1 end = i # empty tuple if all(t.name in NON_CODING_TOKENS for t in tokens[start + 1:i]): return # search forward for the next non-coding token i += 1 while tokens[i].name in NON_CODING_TOKENS: i += 1 if tokens[i].src == ')': _remove_brace(tokens, end) _remove_brace(tokens, start) def _remove_fmt(tup: DotFormatPart) -> DotFormatPart: if tup[1] is None: return tup else: return (tup[0], '', tup[2], tup[3]) def _fix_format_literal(tokens: List[Token], end: int) -> None: parts = rfind_string_parts(tokens, end) parsed_parts = [] last_int = -1 for i in parts: # f'foo {0}'.format(...) would get turned into a SyntaxError prefix, _ = parse_string_literal(tokens[i].src) if 'f' in prefix.lower(): return try: parsed = parse_format(tokens[i].src) except ValueError: # the format literal was malformed, skip it return # The last segment will always be the end of the string and not a # format, slice avoids the `None` format key for _, fmtkey, spec, _ in parsed[:-1]: if ( fmtkey is not None and inty(fmtkey) and int(fmtkey) == last_int + 1 and spec is not None and '{' not in spec ): last_int += 1 else: return parsed_parts.append(tuple(_remove_fmt(tup) for tup in parsed)) for i, parsed in zip(parts, parsed_parts): tokens[i] = tokens[i]._replace(src=unparse_parsed_string(parsed)) def _fix_encode_to_binary(tokens: List[Token], i: int) -> None: # .encode() if ( i + 2 < len(tokens) and tokens[i + 1].src == '(' and tokens[i + 2].src == ')' ): victims = slice(i - 1, i + 3) latin1_ok = False # .encode('encoding') elif ( i + 3 < len(tokens) and tokens[i + 1].src == '(' and tokens[i + 2].name == 'STRING' and tokens[i + 3].src == ')' ): victims = slice(i - 1, i + 4) prefix, rest = parse_string_literal(tokens[i + 2].src) if 'f' in prefix.lower(): return encoding = ast.literal_eval(prefix + rest) if _is_codec(encoding, 'ascii') or _is_codec(encoding, 'utf-8'): latin1_ok = False elif _is_codec(encoding, 'iso8859-1'): latin1_ok = True else: return else: return parts = rfind_string_parts(tokens, i - 2) if not parts: return for part in parts: prefix, rest = parse_string_literal(tokens[part].src) escapes = set(ESCAPE_RE.findall(rest)) if ( not _is_ascii(rest) or '\\u' in escapes or '\\U' in escapes or '\\N' in escapes or ('\\x' in escapes and not latin1_ok) or 'f' in prefix.lower() ): return for part in parts: prefix, rest = parse_string_literal(tokens[part].src) prefix = 'b' + prefix.replace('u', '').replace('U', '') tokens[part] = tokens[part]._replace(src=prefix + rest) del tokens[victims] def _build_import_removals() -> Dict[MinVersion, Dict[str, Tuple[str, ...]]]: ret = {} future: Tuple[Tuple[MinVersion, Tuple[str, ...]], ...] = ( ((2, 7), ('nested_scopes', 'generators', 'with_statement')), ( (3,), ( 'absolute_import', 'division', 'print_function', 'unicode_literals', ), ), ((3, 6), ()), ((3, 7), ('generator_stop',)), ((3, 8), ()), ) prev: Tuple[str, ...] = () for min_version, names in future: prev += names ret[min_version] = {'__future__': prev} # see reorder_python_imports for k, v in ret.items(): if k >= (3,): v.update({ 'builtins': ( 'ascii', 'bytes', 'chr', 'dict', 'filter', 'hex', 'input', 'int', 'list', 'map', 'max', 'min', 'next', 'object', 'oct', 'open', 'pow', 'range', 'round', 'str', 'super', 'zip', '*', ), 'io': ('open',), 'six': ('callable', 'next'), 'six.moves': ('filter', 'input', 'map', 'range', 'zip'), }) return ret IMPORT_REMOVALS = _build_import_removals() def _fix_import_removals( tokens: List[Token], start: int, min_version: MinVersion, ) -> None: i = start + 1 name_parts = [] while tokens[i].src != 'import': if tokens[i].name in {'NAME', 'OP'}: name_parts.append(tokens[i].src) i += 1 modname = ''.join(name_parts) if modname not in IMPORT_REMOVALS[min_version]: return found: List[Optional[int]] = [] i += 1 while tokens[i].name not in {'NEWLINE', 'ENDMARKER'}: if tokens[i].name == 'NAME' or tokens[i].src == '*': # don't touch aliases if ( found and found[-1] is not None and tokens[found[-1]].src == 'as' ): found[-2:] = [None] else: found.append(i) i += 1 # depending on the version of python, some will not emit NEWLINE('') at the # end of a file which does not end with a newline (for example 3.6.5) if tokens[i].name == 'ENDMARKER': # pragma: no cover i -= 1 remove_names = IMPORT_REMOVALS[min_version][modname] to_remove = [ x for x in found if x is not None and tokens[x].src in remove_names ] if len(to_remove) == len(found): del tokens[start:i + 1] else: for idx in reversed(to_remove): if found[0] == idx: # look forward until next name and del j = idx + 1 while tokens[j].name != 'NAME': j += 1 del tokens[idx:j] else: # look backward for comma and del j = idx while tokens[j].src != ',': j -= 1 del tokens[j:idx + 1] def _fix_tokens(contents_text: str, min_version: MinVersion) -> str: remove_u = ( min_version >= (3,) or _imports_future(contents_text, 'unicode_literals') ) try: tokens = src_to_tokens(contents_text) except tokenize.TokenError: return contents_text for i, token in reversed_enumerate(tokens): if token.name == 'NUMBER': tokens[i] = token._replace(src=_fix_long(_fix_octal(token.src))) elif token.name == 'STRING': tokens[i] = _fix_ur_literals(tokens[i]) if remove_u: tokens[i] = _remove_u_prefix(tokens[i]) tokens[i] = _fix_escape_sequences(tokens[i]) elif token.src == '(': _fix_extraneous_parens(tokens, i) elif token.src == 'format' and i > 0 and tokens[i - 1].src == '.': _fix_format_literal(tokens, i - 2) elif token.src == 'encode' and i > 0 and tokens[i - 1].src == '.': _fix_encode_to_binary(tokens, i) elif ( min_version >= (3,) and token.utf8_byte_offset == 0 and token.line < 3 and token.name == 'COMMENT' and tokenize.cookie_re.match(token.src) ): del tokens[i] assert tokens[i].name == 'NL', tokens[i].name del tokens[i] elif token.src == 'from' and token.utf8_byte_offset == 0: _fix_import_removals(tokens, i, min_version) return tokens_to_src(tokens).lstrip() MAPPING_KEY_RE = re.compile(r'\(([^()]*)\)') CONVERSION_FLAG_RE = re.compile('[#0+ -]*') WIDTH_RE = re.compile(r'(?:\*|\d*)') PRECISION_RE = re.compile(r'(?:\.(?:\*|\d*))?') LENGTH_RE = re.compile('[hlL]?') def _must_match(regex: Pattern[str], string: str, pos: int) -> Match[str]: match = regex.match(string, pos) assert match is not None return match def parse_percent_format(s: str) -> Tuple[PercentFormat, ...]: def _parse_inner() -> Generator[PercentFormat, None, None]: string_start = 0 string_end = 0 in_fmt = False i = 0 while i < len(s): if not in_fmt: try: i = s.index('%', i) except ValueError: # no more % fields! yield s[string_start:], None return else: string_end = i i += 1 in_fmt = True else: key_match = MAPPING_KEY_RE.match(s, i) if key_match: key: Optional[str] = key_match.group(1) i = key_match.end() else: key = None conversion_flag_match = _must_match(CONVERSION_FLAG_RE, s, i) conversion_flag = conversion_flag_match.group() or None i = conversion_flag_match.end() width_match = _must_match(WIDTH_RE, s, i) width = width_match.group() or None i = width_match.end() precision_match = _must_match(PRECISION_RE, s, i) precision = precision_match.group() or None i = precision_match.end() # length modifier is ignored i = _must_match(LENGTH_RE, s, i).end() try: conversion = s[i] except IndexError: raise ValueError('end-of-string while parsing format') i += 1 fmt = (key, conversion_flag, width, precision, conversion) yield s[string_start:string_end], fmt in_fmt = False string_start = i if in_fmt: raise ValueError('end-of-string while parsing format') return tuple(_parse_inner()) class FindPercentFormats(ast.NodeVisitor): def __init__(self) -> None: self.found: Dict[Offset, ast.BinOp] = {} def visit_BinOp(self, node: ast.BinOp) -> None: if isinstance(node.op, ast.Mod) and isinstance(node.left, ast.Str): try: parsed = parse_percent_format(node.left.s) except ValueError: pass else: for _, fmt in parsed: if not fmt: continue key, conversion_flag, width, precision, conversion = fmt # timid: these require out-of-order parameter consumption if width == '*' or precision == '.*': break # these conversions require modification of parameters if conversion in {'d', 'i', 'u', 'c'}: break # timid: py2: %#o formats different from {:#o} (--py3?) if '#' in (conversion_flag or '') and conversion == 'o': break # no equivalent in format if key == '': break # timid: py2: conversion is subject to modifiers (--py3?) nontrivial_fmt = any((conversion_flag, width, precision)) if conversion == '%' and nontrivial_fmt: break # no equivalent in format if conversion in {'a', 'r'} and nontrivial_fmt: break # all dict substitutions must be named if isinstance(node.right, ast.Dict) and not key: break else: self.found[_ast_to_offset(node)] = node self.generic_visit(node) def _simplify_conversion_flag(flag: str) -> str: parts: List[str] = [] for c in flag: if c in parts: continue c = c.replace('-', '<') parts.append(c) if c == '<' and '0' in parts: parts.remove('0') elif c == '+' and ' ' in parts: parts.remove(' ') return ''.join(parts) def _percent_to_format(s: str) -> str: def _handle_part(part: PercentFormat) -> str: s, fmt = part s = s.replace('{', '{{').replace('}', '}}') if fmt is None: return s else: key, conversion_flag, width, precision, conversion = fmt if conversion == '%': return s + '%' parts = [s, '{'] if width and conversion == 's' and not conversion_flag: conversion_flag = '>' if conversion == 's': conversion = '' if key: parts.append(key) if conversion in {'r', 'a'}: converter = f'!{conversion}' conversion = '' else: converter = '' if any((conversion_flag, width, precision, conversion)): parts.append(':') if conversion_flag: parts.append(_simplify_conversion_flag(conversion_flag)) parts.extend(x for x in (width, precision, conversion) if x) parts.extend(converter) parts.append('}') return ''.join(parts) return ''.join(_handle_part(part) for part in parse_percent_format(s)) def _is_ascii(s: str) -> bool: if sys.version_info >= (3, 7): # pragma: no cover (py37+) return s.isascii() else: # pragma: no cover (<py37) return all(c in string.printable for c in s) def _fix_percent_format_tuple( tokens: List[Token], start: int, node: ast.BinOp, ) -> None: # TODO: this is overly timid paren = start + 4 if tokens_to_src(tokens[start + 1:paren + 1]) != ' % (': return victims = _victims(tokens, paren, node.right, gen=False) victims.ends.pop() for index in reversed(victims.starts + victims.ends): _remove_brace(tokens, index) newsrc = _percent_to_format(tokens[start].src) tokens[start] = tokens[start]._replace(src=newsrc) tokens[start + 1:paren] = [Token('Format', '.format'), Token('OP', '(')] def _fix_percent_format_dict( tokens: List[Token], start: int, node: ast.BinOp, ) -> None: seen_keys: Set[str] = set() keys = {} # the caller has enforced this assert isinstance(node.right, ast.Dict) for k in node.right.keys: # not a string key if not isinstance(k, ast.Str): return # duplicate key elif k.s in seen_keys: return # not an identifier elif not k.s.isidentifier(): return # a keyword elif k.s in _KEYWORDS: return seen_keys.add(k.s) keys[_ast_to_offset(k)] = k # TODO: this is overly timid brace = start + 4 if tokens_to_src(tokens[start + 1:brace + 1]) != ' % {': return victims = _victims(tokens, brace, node.right, gen=False) brace_end = victims.ends[-1] key_indices = [] for i, token in enumerate(tokens[brace:brace_end], brace): key = keys.pop(token.offset, None) if key is None: continue # we found the key, but the string didn't match (implicit join?) elif ast.literal_eval(token.src) != key.s: return # the map uses some strange syntax that's not `'key': value` elif tokens_to_src(tokens[i + 1:i + 3]) != ': ': return else: key_indices.append((i, key.s)) assert not keys, keys tokens[brace_end] = tokens[brace_end]._replace(src=')') for (key_index, s) in reversed(key_indices): tokens[key_index:key_index + 3] = [Token('CODE', f'{s}=')] newsrc = _percent_to_format(tokens[start].src) tokens[start] = tokens[start]._replace(src=newsrc) tokens[start + 1:brace + 1] = [Token('CODE', '.format'), Token('OP', '(')] def _fix_percent_format(contents_text: str) -> str: try: ast_obj = ast_parse(contents_text) except SyntaxError: return contents_text visitor = FindPercentFormats() visitor.visit(ast_obj) if not visitor.found: return contents_text try: tokens = src_to_tokens(contents_text) except tokenize.TokenError: # pragma: no cover (bpo-2180) return contents_text for i, token in reversed_enumerate(tokens): node = visitor.found.get(token.offset) if node is None: continue # TODO: handle \N escape sequences if r'\N' in token.src: continue if isinstance(node.right, ast.Tuple): _fix_percent_format_tuple(tokens, i, node) elif isinstance(node.right, ast.Dict): _fix_percent_format_dict(tokens, i, node) return tokens_to_src(tokens) SIX_SIMPLE_ATTRS = { 'text_type': 'str', 'binary_type': 'bytes', 'class_types': '(type,)', 'string_types': '(str,)', 'integer_types': '(int,)', 'unichr': 'chr', 'iterbytes': 'iter', 'print_': 'print', 'exec_': 'exec', 'advance_iterator': 'next', 'next': 'next', 'callable': 'callable', } SIX_TYPE_CTX_ATTRS = { 'class_types': 'type', 'string_types': 'str', 'integer_types': 'int', } SIX_CALLS = { 'u': '{args[0]}', 'byte2int': '{args[0]}[0]', 'indexbytes': '{args[0]}[{rest}]', 'iteritems': '{args[0]}.items()', 'iterkeys': '{args[0]}.keys()', 'itervalues': '{args[0]}.values()', 'viewitems': '{args[0]}.items()', 'viewkeys': '{args[0]}.keys()', 'viewvalues': '{args[0]}.values()', 'create_unbound_method': '{args[0]}', 'get_unbound_function': '{args[0]}', 'get_method_function': '{args[0]}.__func__', 'get_method_self': '{args[0]}.__self__', 'get_function_closure': '{args[0]}.__closure__', 'get_function_code': '{args[0]}.__code__', 'get_function_defaults': '{args[0]}.__defaults__', 'get_function_globals': '{args[0]}.__globals__', 'assertCountEqual': '{args[0]}.assertCountEqual({rest})', 'assertRaisesRegex': '{args[0]}.assertRaisesRegex({rest})', 'assertRegex': '{args[0]}.assertRegex({rest})', } SIX_INT2BYTE_TMPL = 'bytes(({args[0]},))' SIX_B_TMPL = 'b{args[0]}' WITH_METACLASS_NO_BASES_TMPL = 'metaclass={args[0]}' WITH_METACLASS_BASES_TMPL = '{rest}, metaclass={args[0]}' RAISE_FROM_TMPL = 'raise {args[0]} from {rest}' RERAISE_TMPL = 'raise' RERAISE_2_TMPL = 'raise {args[1]}.with_traceback(None)' RERAISE_3_TMPL = 'raise {args[1]}.with_traceback({args[2]})' SIX_NATIVE_STR = frozenset(('ensure_str', 'ensure_text', 'text_type')) U_MODE_REMOVE = frozenset(('U', 'Ur', 'rU', 'r', 'rt', 'tr')) U_MODE_REPLACE_R = frozenset(('Ub', 'bU')) U_MODE_REMOVE_U = frozenset(('rUb', 'Urb', 'rbU', 'Ubr', 'bUr', 'brU')) U_MODE_REPLACE = U_MODE_REPLACE_R | U_MODE_REMOVE_U PEP585_BUILTINS = { k: k.lower() for k in ('Dict', 'FrozenSet', 'List', 'Set', 'Tuple', 'Type') } def _all_isinstance( vals: Iterable[Any], tp: Union[Type[Any], Tuple[Type[Any], ...]], ) -> bool: return all(isinstance(v, tp) for v in vals) def fields_same(n1: ast.AST, n2: ast.AST) -> bool: for (a1, v1), (a2, v2) in zip(ast.iter_fields(n1), ast.iter_fields(n2)): # ignore ast attributes, they'll be covered by walk if a1 != a2: return False elif _all_isinstance((v1, v2), ast.AST): continue elif _all_isinstance((v1, v2), (list, tuple)): if len(v1) != len(v2): return False # ignore sequences which are all-ast, they'll be covered by walk elif _all_isinstance(v1, ast.AST) and _all_isinstance(v2, ast.AST): continue elif v1 != v2: return False elif v1 != v2: return False return True def targets_same(target: ast.AST, yield_value: ast.AST) -> bool: for t1, t2 in zip(ast.walk(target), ast.walk(yield_value)): # ignore `ast.Load` / `ast.Store` if _all_isinstance((t1, t2), ast.expr_context): continue elif type(t1) != type(t2): return False elif not fields_same(t1, t2): return False else: return True def _is_codec(encoding: str, name: str) -> bool: try: return codecs.lookup(encoding).name == name except LookupError: return False class FindPy3Plus(ast.NodeVisitor): OS_ERROR_ALIASES = frozenset(( 'EnvironmentError', 'IOError', 'WindowsError', )) OS_ERROR_ALIAS_MODULES = frozenset(( 'mmap', 'select', 'socket', )) FROM_IMPORTED_MODULES = OS_ERROR_ALIAS_MODULES.union(( 'functools', 'six', 'typing', )) MOCK_MODULES = frozenset(('mock', 'mock.mock')) class ClassInfo: def __init__(self, name: str) -> None: self.name = name self.def_depth = 0 self.first_arg_name = '' class Scope: def __init__(self) -> None: self.reads: Set[str] = set() self.writes: Set[str] = set() self.yield_from_fors: Set[Offset] = set() self.yield_from_names: Dict[str, Set[Offset]] self.yield_from_names = collections.defaultdict(set) def __init__(self, version: Tuple[int, ...], keep_mock: bool) -> None: self._version = version self._find_mock = not keep_mock self.bases_to_remove: Set[Offset] = set() self.encode_calls: Dict[Offset, ast.Call] = {} self._exc_info_imported = False self._version_info_imported = False self.if_py3_blocks: Set[Offset] = set() self.if_py2_blocks_else: Set[Offset] = set() self.if_py3_blocks_else: Set[Offset] = set() self.metaclass_type_assignments: Set[Offset] = set() self.native_literals: Set[Offset] = set() self._from_imports: Dict[str, Set[str]] = collections.defaultdict(set) self.io_open_calls: Set[Offset] = set() self.mock_mock: Set[Offset] = set() self.mock_absolute_imports: Set[Offset] = set() self.mock_relative_imports: Set[Offset] = set() self.open_mode_calls: Set[Offset] = set() self.os_error_alias_calls: Set[Offset] = set() self.os_error_alias_simple: Dict[Offset, NameOrAttr] = {} self.os_error_alias_excepts: Set[Offset] = set() self.six_add_metaclass: Set[Offset] = set() self.six_b: Set[Offset] = set() self.six_calls: Dict[Offset, ast.Call] = {} self.six_calls_int2byte: Set[Offset] = set() self.six_iter: Dict[Offset, ast.Call] = {} self._previous_node: Optional[ast.AST] = None self.six_raise_from: Set[Offset] = set() self.six_reraise: Set[Offset] = set() self.six_remove_decorators: Set[Offset] = set() self.six_simple: Dict[Offset, NameOrAttr] = {} self.six_type_ctx: Dict[Offset, NameOrAttr] = {} self.six_with_metaclass: Set[Offset] = set() self._in_type_annotation = False self.typing_builtin_renames: Dict[Offset, NameOrAttr] = {} self._class_info_stack: List[FindPy3Plus.ClassInfo] = [] self._in_comp = 0 self.super_calls: Dict[Offset, ast.Call] = {} self._in_async_def = False self._scope_stack: List[FindPy3Plus.Scope] = [] self.yield_from_fors: Set[Offset] = set() self.no_arg_decorators: Set[Offset] = set() def _is_six(self, node: ast.expr, names: Container[str]) -> bool: return ( isinstance(node, ast.Name) and node.id in names and node.id in self._from_imports['six'] ) or ( isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id == 'six' and node.attr in names ) def _is_star_sys_exc_info(self, node: ast.Call) -> bool: return ( len(node.args) == 1 and isinstance(node.args[0], ast.Starred) and isinstance(node.args[0].value, ast.Call) and self._is_exc_info(node.args[0].value.func) ) def _is_lru_cache(self, node: ast.expr) -> bool: return ( isinstance(node, ast.Name) and node.id == 'lru_cache' and node.id in self._from_imports['functools'] ) or ( isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id == 'functools' and node.attr == 'lru_cache' ) def _is_mock_mock(self, node: ast.expr) -> bool: return ( isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id == 'mock' and node.attr == 'mock' ) def _is_io_open(self, node: ast.expr) -> bool: return ( isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id == 'io' and node.attr == 'open' ) def _is_os_error_alias(self, node: Optional[ast.expr]) -> bool: return ( isinstance(node, ast.Name) and node.id in self.OS_ERROR_ALIASES ) or ( isinstance(node, ast.Name) and node.id == 'error' and ( node.id in self._from_imports['mmap'] or node.id in self._from_imports['select'] or node.id in self._from_imports['socket'] ) ) or ( isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id in self.OS_ERROR_ALIAS_MODULES and node.attr == 'error' ) def _is_exc_info(self, node: ast.expr) -> bool: return ( isinstance(node, ast.Name) and node.id == 'exc_info' and self._exc_info_imported ) or ( isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id == 'sys' and node.attr == 'exc_info' ) def _is_version_info(self, node: ast.expr) -> bool: return ( isinstance(node, ast.Name) and node.id == 'version_info' and self._version_info_imported ) or ( isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id == 'sys' and node.attr == 'version_info' ) def visit_ImportFrom(self, node: ast.ImportFrom) -> None: if not node.level: if node.module in self.FROM_IMPORTED_MODULES: for name in node.names: if not name.asname: self._from_imports[node.module].add(name.name) elif self._find_mock and node.module in self.MOCK_MODULES: self.mock_relative_imports.add(_ast_to_offset(node)) elif node.module == 'sys' and any( name.name == 'exc_info' and not name.asname for name in node.names ): self._exc_info_imported = True elif node.module == 'sys' and any( name.name == 'version_info' and not name.asname for name in node.names ): self._version_info_imported = True self.generic_visit(node) def visit_Import(self, node: ast.Import) -> None: if ( self._find_mock and len(node.names) == 1 and node.names[0].name in self.MOCK_MODULES ): self.mock_absolute_imports.add(_ast_to_offset(node)) self.generic_visit(node) def visit_ClassDef(self, node: ast.ClassDef) -> None: for decorator in node.decorator_list: if self._is_six(decorator, ('python_2_unicode_compatible',)): self.six_remove_decorators.add(_ast_to_offset(decorator)) elif ( isinstance(decorator, ast.Call) and self._is_six(decorator.func, ('add_metaclass',)) and not _starargs(decorator) ): self.six_add_metaclass.add(_ast_to_offset(decorator)) for base in node.bases: if isinstance(base, ast.Name) and base.id == 'object': self.bases_to_remove.add(_ast_to_offset(base)) elif self._is_six(base, ('Iterator',)): self.bases_to_remove.add(_ast_to_offset(base)) if ( len(node.bases) == 1 and isinstance(node.bases[0], ast.Call) and self._is_six(node.bases[0].func, ('with_metaclass',)) and not _starargs(node.bases[0]) ): self.six_with_metaclass.add(_ast_to_offset(node.bases[0])) self._class_info_stack.append(FindPy3Plus.ClassInfo(node.name)) self.generic_visit(node) self._class_info_stack.pop() @contextlib.contextmanager def _track_def_depth( self, node: AnyFunctionDef, ) -> Generator[None, None, None]: class_info = self._class_info_stack[-1] class_info.def_depth += 1 if class_info.def_depth == 1 and node.args.args: class_info.first_arg_name = node.args.args[0].arg try: yield finally: class_info.def_depth -= 1 @contextlib.contextmanager def _scope(self) -> Generator[None, None, None]: self._scope_stack.append(FindPy3Plus.Scope()) try: yield finally: info = self._scope_stack.pop() # discard any that were referenced outside of the loop for name in info.reads: offsets = info.yield_from_names[name] info.yield_from_fors.difference_update(offsets) self.yield_from_fors.update(info.yield_from_fors) if self._scope_stack: cell_reads = info.reads - info.writes self._scope_stack[-1].reads.update(cell_reads) def _visit_annotation(self, node: ast.AST) -> None: orig, self._in_type_annotation = self._in_type_annotation, True self.generic_visit(node) self._in_type_annotation = orig def _visit_func(self, node: AnyFunctionDef) -> None: with contextlib.ExitStack() as ctx, self._scope(): if self._class_info_stack: ctx.enter_context(self._track_def_depth(node)) if not isinstance(node, ast.Lambda) and node.returns is not None: self._visit_annotation(node.returns) self.generic_visit(node) def _visit_sync_func(self, node: SyncFunctionDef) -> None: self._in_async_def, orig = False, self._in_async_def self._visit_func(node) self._in_async_def = orig visit_FunctionDef = visit_Lambda = _visit_sync_func def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None: self._in_async_def, orig = True, self._in_async_def self._visit_func(node) self._in_async_def = orig def visit_arg(self, node: ast.arg) -> None: if node.annotation is not None: self._visit_annotation(node.annotation) self.generic_visit(node) def visit_AnnAssign(self, node: ast.AnnAssign) -> None: self._visit_annotation(node.annotation) self.generic_visit(node) def _visit_comp(self, node: ast.expr) -> None: self._in_comp += 1 with self._scope(): self.generic_visit(node) self._in_comp -= 1 visit_ListComp = visit_SetComp = _visit_comp visit_DictComp = visit_GeneratorExp = _visit_comp def visit_Attribute(self, node: ast.Attribute) -> None: if self._is_six(node, SIX_SIMPLE_ATTRS): self.six_simple[_ast_to_offset(node)] = node elif self._find_mock and self._is_mock_mock(node): self.mock_mock.add(_ast_to_offset(node)) elif ( ( self._version >= (3, 9) or self._in_type_annotation ) and isinstance(node.value, ast.Name) and node.value.id == 'typing' and node.attr in PEP585_BUILTINS ): self.typing_builtin_renames[_ast_to_offset(node)] = node self.generic_visit(node) def visit_Name(self, node: ast.Name) -> None: if self._is_six(node, SIX_SIMPLE_ATTRS): self.six_simple[_ast_to_offset(node)] = node elif ( ( self._version >= (3, 9) or self._in_type_annotation ) and node.id in PEP585_BUILTINS and node.id in self._from_imports['typing'] ): self.typing_builtin_renames[_ast_to_offset(node)] = node if self._scope_stack: if isinstance(node.ctx, ast.Load): self._scope_stack[-1].reads.add(node.id) elif isinstance(node.ctx, (ast.Store, ast.Del)): self._scope_stack[-1].writes.add(node.id) else: raise AssertionError(node) self.generic_visit(node) def visit_Try(self, node: ast.Try) -> None: for handler in node.handlers: htype = handler.type if self._is_os_error_alias(htype): assert isinstance(htype, (ast.Name, ast.Attribute)) self.os_error_alias_simple[_ast_to_offset(htype)] = htype elif ( isinstance(htype, ast.Tuple) and any( self._is_os_error_alias(elt) for elt in htype.elts ) ): self.os_error_alias_excepts.add(_ast_to_offset(htype)) self.generic_visit(node) def visit_Raise(self, node: ast.Raise) -> None: exc = node.exc if exc is not None and self._is_os_error_alias(exc): assert isinstance(exc, (ast.Name, ast.Attribute)) self.os_error_alias_simple[_ast_to_offset(exc)] = exc elif ( isinstance(exc, ast.Call) and self._is_os_error_alias(exc.func) ): self.os_error_alias_calls.add(_ast_to_offset(exc)) self.generic_visit(node) def visit_Call(self, node: ast.Call) -> None: if ( isinstance(node.func, ast.Name) and node.func.id in {'isinstance', 'issubclass'} and len(node.args) == 2 and self._is_six(node.args[1], SIX_TYPE_CTX_ATTRS) ): arg = node.args[1] # _is_six() enforces this assert isinstance(arg, (ast.Name, ast.Attribute)) self.six_type_ctx[_ast_to_offset(node.args[1])] = arg elif self._is_six(node.func, ('b', 'ensure_binary')): self.six_b.add(_ast_to_offset(node)) elif ( self._is_six(node.func, SIX_CALLS) and node.args and not _starargs(node) ): self.six_calls[_ast_to_offset(node)] = node elif ( self._is_six(node.func, ('int2byte',)) and node.args and not _starargs(node) ): self.six_calls_int2byte.add(_ast_to_offset(node)) elif ( isinstance(node.func, ast.Name) and node.func.id == 'next' and not _starargs(node) and len(node.args) == 1 and isinstance(node.args[0], ast.Call) and self._is_six( node.args[0].func, ('iteritems', 'iterkeys', 'itervalues'), ) and not _starargs(node.args[0]) ): self.six_iter[_ast_to_offset(node.args[0])] = node.args[0] elif ( isinstance(self._previous_node, ast.Expr) and self._is_six(node.func, ('raise_from',)) and not _starargs(node) ): self.six_raise_from.add(_ast_to_offset(node)) elif ( isinstance(self._previous_node, ast.Expr) and self._is_six(node.func, ('reraise',)) and (not _starargs(node) or self._is_star_sys_exc_info(node)) ): self.six_reraise.add(_ast_to_offset(node)) elif ( not self._in_comp and self._class_info_stack and self._class_info_stack[-1].def_depth == 1 and isinstance(node.func, ast.Name) and node.func.id == 'super' and len(node.args) == 2 and isinstance(node.args[0], ast.Name) and isinstance(node.args[1], ast.Name) and node.args[0].id == self._class_info_stack[-1].name and node.args[1].id == self._class_info_stack[-1].first_arg_name ): self.super_calls[_ast_to_offset(node)] = node elif ( ( self._is_six(node.func, SIX_NATIVE_STR) or isinstance(node.func, ast.Name) and node.func.id == 'str' ) and not node.keywords and not _starargs(node) and ( len(node.args) == 0 or ( len(node.args) == 1 and isinstance(node.args[0], ast.Str) ) ) ): self.native_literals.add(_ast_to_offset(node)) elif ( isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Str) and node.func.attr == 'encode' and not _starargs(node) and len(node.args) == 1 and isinstance(node.args[0], ast.Str) and _is_codec(node.args[0].s, 'utf-8') ): self.encode_calls[_ast_to_offset(node)] = node elif self._is_io_open(node.func): self.io_open_calls.add(_ast_to_offset(node)) elif ( isinstance(node.func, ast.Name) and node.func.id == 'open' and not _starargs(node) and len(node.args) >= 2 and isinstance(node.args[1], ast.Str) and ( node.args[1].s in U_MODE_REPLACE or (len(node.args) == 2 and node.args[1].s in U_MODE_REMOVE) ) ): self.open_mode_calls.add(_ast_to_offset(node)) elif ( not node.args and not node.keywords and self._is_lru_cache(node.func) ): self.no_arg_decorators.add(_ast_to_offset(node)) self.generic_visit(node) def visit_Assign(self, node: ast.Assign) -> None: if ( len(node.targets) == 1 and isinstance(node.targets[0], ast.Name) and node.targets[0].col_offset == 0 and node.targets[0].id == '__metaclass__' and isinstance(node.value, ast.Name) and node.value.id == 'type' ): self.metaclass_type_assignments.add(_ast_to_offset(node)) self.generic_visit(node) @staticmethod def _eq(test: ast.Compare, n: int) -> bool: return ( isinstance(test.ops[0], ast.Eq) and isinstance(test.comparators[0], ast.Num) and test.comparators[0].n == n ) @staticmethod def _compare_to_3( test: ast.Compare, op: Union[Type[ast.cmpop], Tuple[Type[ast.cmpop], ...]], ) -> bool: if not ( isinstance(test.ops[0], op) and isinstance(test.comparators[0], ast.Tuple) and len(test.comparators[0].elts) >= 1 and all(isinstance(n, ast.Num) for n in test.comparators[0].elts) ): return False # checked above but mypy needs help elts = cast('List[ast.Num]', test.comparators[0].elts) return elts[0].n == 3 and all(n.n == 0 for n in elts[1:]) def visit_If(self, node: ast.If) -> None: if ( # if six.PY2: self._is_six(node.test, ('PY2',)) or # if not six.PY3: ( isinstance(node.test, ast.UnaryOp) and isinstance(node.test.op, ast.Not) and self._is_six(node.test.operand, ('PY3',)) ) or # sys.version_info == 2 or < (3,) ( isinstance(node.test, ast.Compare) and self._is_version_info(node.test.left) and len(node.test.ops) == 1 and ( self._eq(node.test, 2) or self._compare_to_3(node.test, ast.Lt) ) ) ): if node.orelse and not isinstance(node.orelse[0], ast.If): self.if_py2_blocks_else.add(_ast_to_offset(node)) elif ( # if six.PY3: self._is_six(node.test, 'PY3') or # if not six.PY2: ( isinstance(node.test, ast.UnaryOp) and isinstance(node.test.op, ast.Not) and self._is_six(node.test.operand, ('PY2',)) ) or # sys.version_info == 3 or >= (3,) or > (3,) ( isinstance(node.test, ast.Compare) and self._is_version_info(node.test.left) and len(node.test.ops) == 1 and ( self._eq(node.test, 3) or self._compare_to_3(node.test, (ast.Gt, ast.GtE)) ) ) ): if node.orelse and not isinstance(node.orelse[0], ast.If): self.if_py3_blocks_else.add(_ast_to_offset(node)) elif not node.orelse: self.if_py3_blocks.add(_ast_to_offset(node)) self.generic_visit(node) def visit_For(self, node: ast.For) -> None: if ( not self._in_async_def and len(node.body) == 1 and isinstance(node.body[0], ast.Expr) and isinstance(node.body[0].value, ast.Yield) and node.body[0].value.value is not None and targets_same(node.target, node.body[0].value.value) and not node.orelse ): offset = _ast_to_offset(node) func_info = self._scope_stack[-1] func_info.yield_from_fors.add(offset) for target_node in ast.walk(node.target): if ( isinstance(target_node, ast.Name) and isinstance(target_node.ctx, ast.Store) ): func_info.yield_from_names[target_node.id].add(offset) # manually visit, but with target+body as a separate scope self.visit(node.iter) with self._scope(): self.visit(node.target) for stmt in node.body: self.visit(stmt) assert not node.orelse else: self.generic_visit(node) def generic_visit(self, node: ast.AST) -> None: self._previous_node = node super().generic_visit(node) def _fixup_dedent_tokens(tokens: List[Token]) -> None: """For whatever reason the DEDENT / UNIMPORTANT_WS tokens are misordered | if True: | if True: | pass | else: |^ ^- DEDENT |+----UNIMPORTANT_WS """ for i, token in enumerate(tokens): if token.name == UNIMPORTANT_WS and tokens[i + 1].name == 'DEDENT': tokens[i], tokens[i + 1] = tokens[i + 1], tokens[i] def _find_block_start(tokens: List[Token], i: int) -> int: depth = 0 while depth or tokens[i].src != ':': if tokens[i].src in OPENING: depth += 1 elif tokens[i].src in CLOSING: depth -= 1 i += 1 return i class Block(NamedTuple): start: int colon: int block: int end: int line: bool def _initial_indent(self, tokens: List[Token]) -> int: if tokens[self.start].src.isspace(): return len(tokens[self.start].src) else: return 0 def _minimum_indent(self, tokens: List[Token]) -> int: block_indent = None for i in range(self.block, self.end): if ( tokens[i - 1].name in ('NL', 'NEWLINE') and tokens[i].name in ('INDENT', UNIMPORTANT_WS) ): token_indent = len(tokens[i].src) if block_indent is None: block_indent = token_indent else: block_indent = min(block_indent, token_indent) assert block_indent is not None return block_indent def dedent(self, tokens: List[Token]) -> None: if self.line: return diff = self._minimum_indent(tokens) - self._initial_indent(tokens) for i in range(self.block, self.end): if ( tokens[i - 1].name in ('DEDENT', 'NL', 'NEWLINE') and tokens[i].name in ('INDENT', UNIMPORTANT_WS) ): tokens[i] = tokens[i]._replace(src=tokens[i].src[diff:]) def replace_condition(self, tokens: List[Token], new: List[Token]) -> None: tokens[self.start:self.colon] = new def _trim_end(self, tokens: List[Token]) -> 'Block': """the tokenizer reports the end of the block at the beginning of the next block """ i = last_token = self.end - 1 while tokens[i].name in NON_CODING_TOKENS | {'DEDENT', 'NEWLINE'}: # if we find an indented comment inside our block, keep it if ( tokens[i].name in {'NL', 'NEWLINE'} and tokens[i + 1].name == UNIMPORTANT_WS and len(tokens[i + 1].src) > self._initial_indent(tokens) ): break # otherwise we've found another line to remove elif tokens[i].name in {'NL', 'NEWLINE'}: last_token = i i -= 1 return self._replace(end=last_token + 1) @classmethod def find( cls, tokens: List[Token], i: int, trim_end: bool = False, ) -> 'Block': if i > 0 and tokens[i - 1].name in {'INDENT', UNIMPORTANT_WS}: i -= 1 start = i colon = _find_block_start(tokens, i) j = colon + 1 while ( tokens[j].name != 'NEWLINE' and tokens[j].name in NON_CODING_TOKENS ): j += 1 if tokens[j].name == 'NEWLINE': # multi line block block = j + 1 while tokens[j].name != 'INDENT': j += 1 level = 1 j += 1 while level: level += {'INDENT': 1, 'DEDENT': -1}.get(tokens[j].name, 0) j += 1 ret = cls(start, colon, block, j, line=False) if trim_end: return ret._trim_end(tokens) else: return ret else: # single line block block = j j = _find_end(tokens, j) return cls(start, colon, block, j, line=True) def _find_end(tokens: List[Token], i: int) -> int: while tokens[i].name not in {'NEWLINE', 'ENDMARKER'}: i += 1 # depending on the version of python, some will not emit # NEWLINE('') at the end of a file which does not end with a # newline (for example 3.6.5) if tokens[i].name == 'ENDMARKER': # pragma: no cover i -= 1 else: i += 1 return i def _find_if_else_block(tokens: List[Token], i: int) -> Tuple[Block, Block]: if_block = Block.find(tokens, i) i = if_block.end while tokens[i].src != 'else': i += 1 else_block = Block.find(tokens, i, trim_end=True) return if_block, else_block def _find_elif(tokens: List[Token], i: int) -> int: while tokens[i].src != 'elif': # pragma: no cover (only for <3.8.1) i -= 1 return i def _remove_decorator(tokens: List[Token], i: int) -> None: while tokens[i - 1].src != '@': i -= 1 if i > 1 and tokens[i - 2].name not in {'NEWLINE', 'NL'}: i -= 1 end = i + 1 while tokens[end].name != 'NEWLINE': end += 1 del tokens[i - 1:end + 1] def _remove_base_class(tokens: List[Token], i: int) -> None: # look forward and backward to find commas / parens brace_stack = [] j = i while tokens[j].src not in {',', ':'}: if tokens[j].src == ')': brace_stack.append(j) j += 1 right = j if tokens[right].src == ':': brace_stack.pop() else: # if there's a close-paren after a trailing comma j = right + 1 while tokens[j].name in NON_CODING_TOKENS: j += 1 if tokens[j].src == ')': while tokens[j].src != ':': j += 1 right = j if brace_stack: last_part = brace_stack[-1] else: last_part = i j = i while brace_stack: if tokens[j].src == '(': brace_stack.pop() j -= 1 while tokens[j].src not in {',', '('}: j -= 1 left = j # single base, remove the entire bases if tokens[left].src == '(' and tokens[right].src == ':': del tokens[left:right] # multiple bases, base is first elif tokens[left].src == '(' and tokens[right].src != ':': # if there's space / comment afterwards remove that too while tokens[right + 1].name in {UNIMPORTANT_WS, 'COMMENT'}: right += 1 del tokens[left + 1:right + 1] # multiple bases, base is not first else: del tokens[left:last_part + 1] def _parse_call_args( tokens: List[Token], i: int, ) -> Tuple[List[Tuple[int, int]], int]: args = [] stack = [i] i += 1 arg_start = i while stack: token = tokens[i] if len(stack) == 1 and token.src == ',': args.append((arg_start, i)) arg_start = i + 1 elif token.src in BRACES: stack.append(i) elif token.src == BRACES[tokens[stack[-1]].src]: stack.pop() # if we're at the end, append that argument if not stack and tokens_to_src(tokens[arg_start:i]).strip(): args.append((arg_start, i)) i += 1 return args, i def _get_tmpl(mapping: Dict[str, str], node: NameOrAttr) -> str: if isinstance(node, ast.Name): return mapping[node.id] else: return mapping[node.attr] def _arg_str(tokens: List[Token], start: int, end: int) -> str: return tokens_to_src(tokens[start:end]).strip() def _replace_call( tokens: List[Token], start: int, end: int, args: List[Tuple[int, int]], tmpl: str, *, parens: Sequence[int] = (), ) -> None: arg_strs = [_arg_str(tokens, *arg) for arg in args] for paren in parens: arg_strs[paren] = f'({arg_strs[paren]})' start_rest = args[0][1] + 1 while ( start_rest < end and tokens[start_rest].name in {'COMMENT', UNIMPORTANT_WS} ): start_rest += 1 rest = tokens_to_src(tokens[start_rest:end - 1]) src = tmpl.format(args=arg_strs, rest=rest) tokens[start:end] = [Token('CODE', src)] def _replace_yield(tokens: List[Token], i: int) -> None: in_token = _find_token(tokens, i, 'in') colon = _find_block_start(tokens, i) block = Block.find(tokens, i, trim_end=True) container = tokens_to_src(tokens[in_token + 1:colon]).strip() tokens[i:block.end] = [Token('CODE', f'yield from {container}\n')] def _fix_py3_plus( contents_text: str, min_version: MinVersion, keep_mock: bool = False, ) -> str: try: ast_obj = ast_parse(contents_text) except SyntaxError: return contents_text pep585_rewrite = ( min_version >= (3, 9) or _imports_future(contents_text, 'annotations') ) visitor = FindPy3Plus(min_version, keep_mock) visitor.visit(ast_obj) if not any(( visitor.bases_to_remove, visitor.encode_calls, visitor.if_py2_blocks_else, visitor.if_py3_blocks, visitor.if_py3_blocks_else, visitor.metaclass_type_assignments, visitor.native_literals, visitor.io_open_calls, visitor.open_mode_calls, visitor.mock_mock, visitor.mock_absolute_imports, visitor.mock_relative_imports, visitor.os_error_alias_calls, visitor.os_error_alias_simple, visitor.os_error_alias_excepts, visitor.no_arg_decorators, visitor.six_add_metaclass, visitor.six_b, visitor.six_calls, visitor.six_calls_int2byte, visitor.six_iter, visitor.six_raise_from, visitor.six_reraise, visitor.six_remove_decorators, visitor.six_simple, visitor.six_type_ctx, visitor.six_with_metaclass, visitor.super_calls, visitor.typing_builtin_renames, visitor.yield_from_fors, )): return contents_text try: tokens = src_to_tokens(contents_text) except tokenize.TokenError: # pragma: no cover (bpo-2180) return contents_text _fixup_dedent_tokens(tokens) def _replace(i: int, mapping: Dict[str, str], node: NameOrAttr) -> None: new_token = Token('CODE', _get_tmpl(mapping, node)) if isinstance(node, ast.Name): tokens[i] = new_token else: j = i while tokens[j].src != node.attr: # timid: if we see a parenthesis here, skip it if tokens[j].src == ')': return j += 1 tokens[i:j + 1] = [new_token] for i, token in reversed_enumerate(tokens): if not token.src: continue elif token.offset in visitor.bases_to_remove: _remove_base_class(tokens, i) elif token.offset in visitor.if_py3_blocks: if tokens[i].src == 'if': if_block = Block.find(tokens, i) if_block.dedent(tokens) del tokens[if_block.start:if_block.block] else: if_block = Block.find(tokens, _find_elif(tokens, i)) if_block.replace_condition(tokens, [Token('NAME', 'else')]) elif token.offset in visitor.if_py2_blocks_else: if tokens[i].src == 'if': if_block, else_block = _find_if_else_block(tokens, i) else_block.dedent(tokens) del tokens[if_block.start:else_block.block] else: j = _find_elif(tokens, i) if_block, else_block = _find_if_else_block(tokens, j) del tokens[if_block.start:else_block.start] elif token.offset in visitor.if_py3_blocks_else: if tokens[i].src == 'if': if_block, else_block = _find_if_else_block(tokens, i) if_block.dedent(tokens) del tokens[if_block.end:else_block.end] del tokens[if_block.start:if_block.block] else: j = _find_elif(tokens, i) if_block, else_block = _find_if_else_block(tokens, j) del tokens[if_block.end:else_block.end] if_block.replace_condition(tokens, [Token('NAME', 'else')]) elif token.offset in visitor.metaclass_type_assignments: j = _find_end(tokens, i) del tokens[i:j + 1] elif token.offset in visitor.native_literals: j = _find_open_paren(tokens, i) func_args, end = _parse_call_args(tokens, j) if any(tok.name == 'NL' for tok in tokens[i:end]): continue if func_args: _replace_call(tokens, i, end, func_args, '{args[0]}') else: tokens[i:end] = [token._replace(name='STRING', src="''")] elif token.offset in visitor.six_type_ctx: _replace(i, SIX_TYPE_CTX_ATTRS, visitor.six_type_ctx[token.offset]) elif token.offset in visitor.six_simple: _replace(i, SIX_SIMPLE_ATTRS, visitor.six_simple[token.offset]) elif token.offset in visitor.six_remove_decorators: _remove_decorator(tokens, i) elif token.offset in visitor.six_b: j = _find_open_paren(tokens, i) if ( tokens[j + 1].name == 'STRING' and _is_ascii(tokens[j + 1].src) and tokens[j + 2].src == ')' ): func_args, end = _parse_call_args(tokens, j) _replace_call(tokens, i, end, func_args, SIX_B_TMPL) elif token.offset in visitor.six_iter: j = _find_open_paren(tokens, i) func_args, end = _parse_call_args(tokens, j) call = visitor.six_iter[token.offset] assert isinstance(call.func, (ast.Name, ast.Attribute)) template = f'iter({_get_tmpl(SIX_CALLS, call.func)})' _replace_call(tokens, i, end, func_args, template) elif token.offset in visitor.six_calls: j = _find_open_paren(tokens, i) func_args, end = _parse_call_args(tokens, j) call = visitor.six_calls[token.offset] assert isinstance(call.func, (ast.Name, ast.Attribute)) template = _get_tmpl(SIX_CALLS, call.func) if isinstance(call.args[0], _EXPR_NEEDS_PARENS): _replace_call(tokens, i, end, func_args, template, parens=(0,)) else: _replace_call(tokens, i, end, func_args, template) elif token.offset in visitor.six_calls_int2byte: j = _find_open_paren(tokens, i) func_args, end = _parse_call_args(tokens, j) _replace_call(tokens, i, end, func_args, SIX_INT2BYTE_TMPL) elif token.offset in visitor.six_raise_from: j = _find_open_paren(tokens, i) func_args, end = _parse_call_args(tokens, j) _replace_call(tokens, i, end, func_args, RAISE_FROM_TMPL) elif token.offset in visitor.six_reraise: j = _find_open_paren(tokens, i) func_args, end = _parse_call_args(tokens, j) if len(func_args) == 1: tmpl = RERAISE_TMPL elif len(func_args) == 2: tmpl = RERAISE_2_TMPL else: tmpl = RERAISE_3_TMPL _replace_call(tokens, i, end, func_args, tmpl) elif token.offset in visitor.six_add_metaclass: j = _find_open_paren(tokens, i) func_args, end = _parse_call_args(tokens, j) metaclass = f'metaclass={_arg_str(tokens, *func_args[0])}' # insert `metaclass={args[0]}` into `class:` # search forward for the `class` token j = i + 1 while tokens[j].src != 'class': j += 1 class_token = j # then search forward for a `:` token, not inside a brace j = _find_block_start(tokens, j) last_paren = -1 for k in range(class_token, j): if tokens[k].src == ')': last_paren = k if last_paren == -1: tokens.insert(j, Token('CODE', f'({metaclass})')) else: insert = last_paren - 1 while tokens[insert].name in NON_CODING_TOKENS: insert -= 1 if tokens[insert].src == '(': # no bases src = metaclass elif tokens[insert].src != ',': src = f', {metaclass}' else: src = f' {metaclass},' tokens.insert(insert + 1, Token('CODE', src)) _remove_decorator(tokens, i) elif token.offset in visitor.six_with_metaclass: j = _find_open_paren(tokens, i) func_args, end = _parse_call_args(tokens, j) if len(func_args) == 1: tmpl = WITH_METACLASS_NO_BASES_TMPL elif len(func_args) == 2: base = _arg_str(tokens, *func_args[1]) if base == 'object': tmpl = WITH_METACLASS_NO_BASES_TMPL else: tmpl = WITH_METACLASS_BASES_TMPL else: tmpl = WITH_METACLASS_BASES_TMPL _replace_call(tokens, i, end, func_args, tmpl) elif pep585_rewrite and token.offset in visitor.typing_builtin_renames: node = visitor.typing_builtin_renames[token.offset] _replace(i, PEP585_BUILTINS, node) elif token.offset in visitor.super_calls: i = _find_open_paren(tokens, i) call = visitor.super_calls[token.offset] victims = _victims(tokens, i, call, gen=False) del tokens[victims.starts[0] + 1:victims.ends[-1]] elif token.offset in visitor.encode_calls: i = _find_open_paren(tokens, i + 1) call = visitor.encode_calls[token.offset] victims = _victims(tokens, i, call, gen=False) del tokens[victims.starts[0] + 1:victims.ends[-1]] elif token.offset in visitor.io_open_calls: j = _find_open_paren(tokens, i) tokens[i:j] = [token._replace(name='NAME', src='open')] elif token.offset in visitor.mock_mock: j = _find_token(tokens, i + 1, 'mock') del tokens[i + 1:j + 1] elif token.offset in visitor.mock_absolute_imports: j = _find_token(tokens, i, 'mock') if ( j + 2 < len(tokens) and tokens[j + 1].src == '.' and tokens[j + 2].src == 'mock' ): j += 2 src = 'from unittest import mock' tokens[i:j + 1] = [tokens[j]._replace(name='NAME', src=src)] elif token.offset in visitor.mock_relative_imports: j = _find_token(tokens, i, 'mock') if ( j + 2 < len(tokens) and tokens[j + 1].src == '.' and tokens[j + 2].src == 'mock' ): k = j + 2 else: k = j src = 'unittest.mock' tokens[j:k + 1] = [tokens[j]._replace(name='NAME', src=src)] elif token.offset in visitor.open_mode_calls: j = _find_open_paren(tokens, i) func_args, end = _parse_call_args(tokens, j) mode = tokens_to_src(tokens[slice(*func_args[1])]) mode_stripped = mode.strip().strip('"\'') if mode_stripped in U_MODE_REMOVE: del tokens[func_args[0][1]:func_args[1][1]] elif mode_stripped in U_MODE_REPLACE_R: new_mode = mode.replace('U', 'r') tokens[slice(*func_args[1])] = [Token('SRC', new_mode)] elif mode_stripped in U_MODE_REMOVE_U: new_mode = mode.replace('U', '') tokens[slice(*func_args[1])] = [Token('SRC', new_mode)] else: raise AssertionError(f'unreachable: {mode!r}') elif token.offset in visitor.os_error_alias_calls: j = _find_open_paren(tokens, i) tokens[i:j] = [token._replace(name='NAME', src='OSError')] elif token.offset in visitor.os_error_alias_simple: node = visitor.os_error_alias_simple[token.offset] _replace(i, collections.defaultdict(lambda: 'OSError'), node) elif token.offset in visitor.os_error_alias_excepts: line, utf8_byte_offset = token.line, token.utf8_byte_offset # find all the arg strs in the tuple except_index = i while tokens[except_index].src != 'except': except_index -= 1 start = _find_open_paren(tokens, except_index) func_args, end = _parse_call_args(tokens, start) # save the exceptions and remove the block arg_strs = [_arg_str(tokens, *arg) for arg in func_args] del tokens[start:end] # rewrite the block without dupes args = [] for arg in arg_strs: left, part, right = arg.partition('.') if ( left in visitor.OS_ERROR_ALIAS_MODULES and part == '.' and right == 'error' ): args.append('OSError') elif ( left in visitor.OS_ERROR_ALIASES and part == right == '' ): args.append('OSError') elif ( left == 'error' and part == right == '' and ( 'error' in visitor._from_imports['mmap'] or 'error' in visitor._from_imports['select'] or 'error' in visitor._from_imports['socket'] ) ): args.append('OSError') else: args.append(arg) unique_args = tuple(collections.OrderedDict.fromkeys(args)) if len(unique_args) > 1: joined = '({})'.format(', '.join(unique_args)) elif tokens[start - 1].name != 'UNIMPORTANT_WS': joined = ' {}'.format(unique_args[0]) else: joined = unique_args[0] new = Token('CODE', joined, line, utf8_byte_offset) tokens.insert(start, new) visitor.os_error_alias_excepts.discard(token.offset) elif token.offset in visitor.yield_from_fors: _replace_yield(tokens, i) elif ( min_version >= (3, 8) and token.offset in visitor.no_arg_decorators ): i = _find_open_paren(tokens, i) j = _find_token(tokens, i, ')') del tokens[i:j + 1] return tokens_to_src(tokens) def _simple_arg(arg: ast.expr) -> bool: return ( isinstance(arg, ast.Name) or (isinstance(arg, ast.Attribute) and _simple_arg(arg.value)) or ( isinstance(arg, ast.Call) and _simple_arg(arg.func) and not arg.args and not arg.keywords ) ) def _starargs(call: ast.Call) -> bool: return ( any(k.arg is None for k in call.keywords) or any(isinstance(a, ast.Starred) for a in call.args) ) def _format_params(call: ast.Call) -> Dict[str, str]: params = {} for i, arg in enumerate(call.args): params[str(i)] = _unparse(arg) for kwd in call.keywords: # kwd.arg can't be None here because we exclude starargs assert kwd.arg is not None params[kwd.arg] = _unparse(kwd.value) return params class FindPy36Plus(ast.NodeVisitor): def __init__(self) -> None: self.fstrings: Dict[Offset, ast.Call] = {} self.named_tuples: Dict[Offset, ast.Call] = {} self.dict_typed_dicts: Dict[Offset, ast.Call] = {} self.kw_typed_dicts: Dict[Offset, ast.Call] = {} self._from_imports: Dict[str, Set[str]] = collections.defaultdict(set) def visit_ImportFrom(self, node: ast.ImportFrom) -> None: if node.level == 0 and node.module in {'typing', 'typing_extensions'}: for name in node.names: if not name.asname: self._from_imports[node.module].add(name.name) self.generic_visit(node) def _is_attr(self, node: ast.AST, mods: Set[str], name: str) -> bool: return ( ( isinstance(node, ast.Name) and node.id == name and any(name in self._from_imports[mod] for mod in mods) ) or ( isinstance(node, ast.Attribute) and node.attr == name and isinstance(node.value, ast.Name) and node.value.id in mods ) ) def _parse(self, node: ast.Call) -> Optional[Tuple[DotFormatPart, ...]]: if not ( isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Str) and node.func.attr == 'format' and all(_simple_arg(arg) for arg in node.args) and all(_simple_arg(k.value) for k in node.keywords) and not _starargs(node) ): return None try: return parse_format(node.func.value.s) except ValueError: return None def visit_Call(self, node: ast.Call) -> None: parsed = self._parse(node) if parsed is not None: params = _format_params(node) seen: Set[str] = set() i = 0 for _, name, spec, _ in parsed: # timid: difficult to rewrite correctly if spec is not None and '{' in spec: break if name is not None: candidate, _, _ = name.partition('.') # timid: could make the f-string longer if candidate and candidate in seen: break # timid: bracketed elif '[' in name: break seen.add(candidate) key = candidate or str(i) # their .format() call is broken currently if key not in params: break if not candidate: i += 1 else: self.fstrings[_ast_to_offset(node)] = node self.generic_visit(node) def visit_Assign(self, node: ast.Assign) -> None: if ( # NT = ...("NT", ...) len(node.targets) == 1 and isinstance(node.targets[0], ast.Name) and isinstance(node.value, ast.Call) and len(node.value.args) >= 1 and isinstance(node.value.args[0], ast.Str) and node.targets[0].id == node.value.args[0].s and not _starargs(node.value) ): if ( self._is_attr( node.value.func, {'typing'}, 'NamedTuple', ) and len(node.value.args) == 2 and not node.value.keywords and isinstance(node.value.args[1], (ast.List, ast.Tuple)) and len(node.value.args[1].elts) > 0 and all( isinstance(tup, ast.Tuple) and len(tup.elts) == 2 and isinstance(tup.elts[0], ast.Str) and tup.elts[0].s.isidentifier() and tup.elts[0].s not in _KEYWORDS for tup in node.value.args[1].elts ) ): self.named_tuples[_ast_to_offset(node)] = node.value elif ( self._is_attr( node.value.func, {'typing', 'typing_extensions'}, 'TypedDict', ) and len(node.value.args) == 1 and len(node.value.keywords) > 0 ): self.kw_typed_dicts[_ast_to_offset(node)] = node.value elif ( self._is_attr( node.value.func, {'typing', 'typing_extensions'}, 'TypedDict', ) and len(node.value.args) == 2 and not node.value.keywords and isinstance(node.value.args[1], ast.Dict) and node.value.args[1].keys and all( isinstance(k, ast.Str) and k.s.isidentifier() and k.s not in _KEYWORDS for k in node.value.args[1].keys ) ): self.dict_typed_dicts[_ast_to_offset(node)] = node.value self.generic_visit(node) def _unparse(node: ast.expr) -> str: if isinstance(node, ast.Name): return node.id elif isinstance(node, ast.Attribute): return ''.join((_unparse(node.value), '.', node.attr)) elif isinstance(node, ast.Call): return '{}()'.format(_unparse(node.func)) elif isinstance(node, ast.Subscript): if sys.version_info >= (3, 9): # pragma: no cover (py39+) node_slice: ast.expr = node.slice elif isinstance(node.slice, ast.Index): # pragma: no cover (<py39) node_slice = node.slice.value else: raise AssertionError(f'expected Slice: {ast.dump(node)}') if isinstance(node_slice, ast.Tuple): if len(node_slice.elts) == 1: slice_s = f'{_unparse(node_slice.elts[0])},' else: slice_s = ', '.join(_unparse(elt) for elt in node_slice.elts) else: slice_s = _unparse(node_slice) return '{}[{}]'.format(_unparse(node.value), slice_s) elif isinstance(node, ast.Str): return repr(node.s) elif isinstance(node, ast.Ellipsis): return '...' elif isinstance(node, ast.List): return '[{}]'.format(', '.join(_unparse(elt) for elt in node.elts)) elif isinstance(node, ast.NameConstant): return repr(node.value) else: raise NotImplementedError(ast.dump(node)) def _to_fstring(src: str, call: ast.Call) -> str: params = _format_params(call) parts = [] i = 0 for s, name, spec, conv in parse_format('f' + src): if name is not None: k, dot, rest = name.partition('.') name = ''.join((params[k or str(i)], dot, rest)) if not k: # named and auto params can be in different orders i += 1 parts.append((s, name, spec, conv)) return unparse_parsed_string(parts) def _replace_typed_class( tokens: List[Token], i: int, call: ast.Call, types: Dict[str, ast.expr], ) -> None: if i > 0 and tokens[i - 1].name in {'INDENT', UNIMPORTANT_WS}: indent = f'{tokens[i - 1].src}{' ' * 4}' else: indent = ' ' * 4 # NT = NamedTuple("nt", [("a", int)]) # ^i ^end end = i + 1 while end < len(tokens) and tokens[end].name != 'NEWLINE': end += 1 attrs = '\n'.join(f'{indent}{k}: {_unparse(v)}' for k, v in types.items()) src = f'class {tokens[i].src}({_unparse(call.func)}):\n{attrs}' tokens[i:end] = [Token('CODE', src)] def _fix_py36_plus(contents_text: str) -> str: try: ast_obj = ast_parse(contents_text) except SyntaxError: return contents_text visitor = FindPy36Plus() visitor.visit(ast_obj) if not any(( visitor.fstrings, visitor.named_tuples, visitor.dict_typed_dicts, visitor.kw_typed_dicts, )): return contents_text try: tokens = src_to_tokens(contents_text) except tokenize.TokenError: # pragma: no cover (bpo-2180) return contents_text for i, token in reversed_enumerate(tokens): if token.offset in visitor.fstrings: node = visitor.fstrings[token.offset] # TODO: handle \N escape sequences if r'\N' in token.src: continue paren = i + 3 if tokens_to_src(tokens[i + 1:paren + 1]) != '.format(': continue # we don't actually care about arg position, so we pass `node` victims = _victims(tokens, paren, node, gen=False) end = victims.ends[-1] # if it spans more than one line, bail if tokens[end].line != token.line: continue tokens[i] = token._replace(src=_to_fstring(token.src, node)) del tokens[i + 1:end + 1] elif token.offset in visitor.named_tuples and token.name == 'NAME': call = visitor.named_tuples[token.offset] types: Dict[str, ast.expr] = { tup.elts[0].s: tup.elts[1] # type: ignore # (checked above) for tup in call.args[1].elts # type: ignore # (checked above) } _replace_typed_class(tokens, i, call, types) elif token.offset in visitor.kw_typed_dicts and token.name == 'NAME': call = visitor.kw_typed_dicts[token.offset] types = { arg.arg: arg.value # type: ignore # (checked above) for arg in call.keywords } _replace_typed_class(tokens, i, call, types) elif token.offset in visitor.dict_typed_dicts and token.name == 'NAME': call = visitor.dict_typed_dicts[token.offset] types = { k.s: v # type: ignore # (checked above) for k, v in zip( call.args[1].keys, # type: ignore # (checked above) call.args[1].values, # type: ignore # (checked above) ) } _replace_typed_class(tokens, i, call, types) return tokens_to_src(tokens) def _fix_file(filename: str, args: argparse.Namespace) -> int: if filename == '-': contents_bytes = sys.stdin.buffer.read() else: with open(filename, 'rb') as fb: contents_bytes = fb.read() try: contents_text_orig = contents_text = contents_bytes.decode() except UnicodeDecodeError: print(f'{filename} is non-utf-8 (not supported)') return 1 contents_text = _fix_py2_compatible(contents_text) contents_text = _fix_tokens(contents_text, min_version=args.min_version) if not args.keep_percent_format: contents_text = _fix_percent_format(contents_text) if args.min_version >= (3,): contents_text = _fix_py3_plus( contents_text, args.min_version, args.keep_mock, ) if args.min_version >= (3, 6): contents_text = _fix_py36_plus(contents_text) if filename == '-': print(contents_text, end='') elif contents_text != contents_text_orig: print(f'Rewriting {filename}', file=sys.stderr) with open(filename, 'w', encoding='UTF-8', newline='') as f: f.write(contents_text) if args.exit_zero_even_if_changed: return 0 else: return contents_text != contents_text_orig def main(argv: Optional[Sequence[str]] = None) -> int: parser = argparse.ArgumentParser() parser.add_argument('filenames', nargs='*') parser.add_argument('--exit-zero-even-if-changed', action='store_true') parser.add_argument('--keep-percent-format', action='store_true') parser.add_argument('--keep-mock', action='store_true') parser.add_argument( '--py3-plus', '--py3-only', action='store_const', dest='min_version', default=(2, 7), const=(3,), ) parser.add_argument( '--py36-plus', action='store_const', dest='min_version', const=(3, 6), ) parser.add_argument( '--py37-plus', action='store_const', dest='min_version', const=(3, 7), ) parser.add_argument( '--py38-plus', action='store_const', dest='min_version', const=(3, 8), ) parser.add_argument( '--py39-plus', action='store_const', dest='min_version', const=(3, 9), ) args = parser.parse_args(argv) ret = 0 for filename in args.filenames: ret |= _fix_file(filename, args) return ret if __name__ == '__main__': exit(main())
import argparse import ast import codecs import collections import contextlib import keyword import re import string import sys import tokenize import warnings from typing import Any from typing import cast from typing import Container from typing import Dict from typing import Generator from typing import Iterable from typing import List from typing import Match from typing import NamedTuple from typing import Optional from typing import Pattern from typing import Sequence from typing import Set from typing import Tuple from typing import Type from typing import Union from tokenize_rt import NON_CODING_TOKENS from tokenize_rt import Offset from tokenize_rt import parse_string_literal from tokenize_rt import reversed_enumerate from tokenize_rt import rfind_string_parts from tokenize_rt import src_to_tokens from tokenize_rt import Token from tokenize_rt import tokens_to_src from tokenize_rt import UNIMPORTANT_WS MinVersion = Tuple[int, ...] DotFormatPart = Tuple[str, Optional[str], Optional[str], Optional[str]] PercentFormatPart = Tuple[ Optional[str], Optional[str], Optional[str], Optional[str], str, ] PercentFormat = Tuple[str, Optional[PercentFormatPart]] ListCompOrGeneratorExp = Union[ast.ListComp, ast.GeneratorExp] ListOrTuple = Union[ast.List, ast.Tuple] NameOrAttr = Union[ast.Name, ast.Attribute] AnyFunctionDef = Union[ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda] SyncFunctionDef = Union[ast.FunctionDef, ast.Lambda] _stdlib_parse_format = string.Formatter().parse _KEYWORDS = frozenset(keyword.kwlist) _EXPR_NEEDS_PARENS: Tuple[Type[ast.expr], ...] = ( ast.Await, ast.BinOp, ast.BoolOp, ast.Compare, ast.GeneratorExp, ast.IfExp, ast.Lambda, ast.UnaryOp, ) if sys.version_info >= (3, 8): # pragma: no cover (py38+) _EXPR_NEEDS_PARENS += (ast.NamedExpr,) def parse_format(s: str) -> Tuple[DotFormatPart, ...]: """Makes the empty string not a special case. In the stdlib, there's loss of information (the type) on the empty string. """ parsed = tuple(_stdlib_parse_format(s)) if not parsed: return ((s, None, None, None),) else: return parsed def unparse_parsed_string(parsed: Sequence[DotFormatPart]) -> str: def _convert_tup(tup: DotFormatPart) -> str: ret, field_name, format_spec, conversion = tup ret = ret.replace('{', '{{') ret = ret.replace('}', '}}') if field_name is not None: ret += '{' + field_name if conversion: ret += '!' + conversion if format_spec: ret += ':' + format_spec ret += '}' return ret return ''.join(_convert_tup(tup) for tup in parsed) def _ast_to_offset(node: Union[ast.expr, ast.stmt]) -> Offset: return Offset(node.lineno, node.col_offset) def ast_parse(contents_text: str) -> ast.Module: # intentionally ignore warnings, we might be fixing warning-ridden syntax with warnings.catch_warnings(): warnings.simplefilter('ignore') return ast.parse(contents_text.encode()) def inty(s: str) -> bool: try: int(s) return True except (ValueError, TypeError): return False BRACES = {'(': ')', '[': ']', '{': '}'} OPENING, CLOSING = frozenset(BRACES), frozenset(BRACES.values()) SET_TRANSFORM = (ast.List, ast.ListComp, ast.GeneratorExp, ast.Tuple) def _is_wtf(func: str, tokens: List[Token], i: int) -> bool: return tokens[i].src != func or tokens[i + 1].src != '(' def _process_set_empty_literal(tokens: List[Token], start: int) -> None: if _is_wtf('set', tokens, start): return i = start + 2 brace_stack = ['('] while brace_stack: token = tokens[i].src if token == BRACES[brace_stack[-1]]: brace_stack.pop() elif token in BRACES: brace_stack.append(token) elif '\n' in token: # Contains a newline, could cause a SyntaxError, bail return i += 1 # Remove the inner tokens del tokens[start + 2:i - 1] def _search_until(tokens: List[Token], idx: int, arg: ast.expr) -> int: while ( idx < len(tokens) and not ( tokens[idx].line == arg.lineno and tokens[idx].utf8_byte_offset == arg.col_offset ) ): idx += 1 return idx if sys.version_info >= (3, 8): # pragma: no cover (py38+) # python 3.8 fixed the offsets of generators / tuples def _arg_token_index(tokens: List[Token], i: int, arg: ast.expr) -> int: idx = _search_until(tokens, i, arg) + 1 while idx < len(tokens) and tokens[idx].name in NON_CODING_TOKENS: idx += 1 return idx else: # pragma: no cover (<py38) def _arg_token_index(tokens: List[Token], i: int, arg: ast.expr) -> int: # lists containing non-tuples report the first element correctly if isinstance(arg, ast.List): # If the first element is a tuple, the ast lies to us about its col # offset. We must find the first `(` token after the start of the # list element. if isinstance(arg.elts[0], ast.Tuple): i = _search_until(tokens, i, arg) return _find_open_paren(tokens, i) else: return _search_until(tokens, i, arg.elts[0]) # others' start position points at their first child node already else: return _search_until(tokens, i, arg) class Victims(NamedTuple): starts: List[int] ends: List[int] first_comma_index: Optional[int] arg_index: int def _victims( tokens: List[Token], start: int, arg: ast.expr, gen: bool, ) -> Victims: starts = [start] start_depths = [1] ends: List[int] = [] first_comma_index = None arg_depth = None arg_index = _arg_token_index(tokens, start, arg) brace_stack = [tokens[start].src] i = start + 1 while brace_stack: token = tokens[i].src is_start_brace = token in BRACES is_end_brace = token == BRACES[brace_stack[-1]] if i == arg_index: arg_depth = len(brace_stack) if is_start_brace: brace_stack.append(token) # Remove all braces before the first element of the inner # comprehension's target. if is_start_brace and arg_depth is None: start_depths.append(len(brace_stack)) starts.append(i) if ( token == ',' and len(brace_stack) == arg_depth and first_comma_index is None ): first_comma_index = i if is_end_brace and len(brace_stack) in start_depths: if tokens[i - 2].src == ',' and tokens[i - 1].src == ' ': ends.extend((i - 2, i - 1, i)) elif tokens[i - 1].src == ',': ends.extend((i - 1, i)) else: ends.append(i) if len(brace_stack) > 1 and tokens[i + 1].src == ',': ends.append(i + 1) if is_end_brace: brace_stack.pop() i += 1 # May need to remove a trailing comma for a comprehension if gen: i -= 2 while tokens[i].name in NON_CODING_TOKENS: i -= 1 if tokens[i].src == ',': ends.append(i) return Victims(starts, sorted(set(ends)), first_comma_index, arg_index) def _find_token(tokens: List[Token], i: int, src: str) -> int: while tokens[i].src != src: i += 1 return i def _find_open_paren(tokens: List[Token], i: int) -> int: return _find_token(tokens, i, '(') def _is_on_a_line_by_self(tokens: List[Token], i: int) -> bool: return ( tokens[i - 2].name == 'NL' and tokens[i - 1].name == UNIMPORTANT_WS and tokens[i + 1].name == 'NL' ) def _remove_brace(tokens: List[Token], i: int) -> None: if _is_on_a_line_by_self(tokens, i): del tokens[i - 1:i + 2] else: del tokens[i] def _process_set_literal( tokens: List[Token], start: int, arg: ast.expr, ) -> None: if _is_wtf('set', tokens, start): return gen = isinstance(arg, ast.GeneratorExp) set_victims = _victims(tokens, start + 1, arg, gen=gen) del set_victims.starts[0] end_index = set_victims.ends.pop() tokens[end_index] = Token('OP', '}') for index in reversed(set_victims.starts + set_victims.ends): _remove_brace(tokens, index) tokens[start:start + 2] = [Token('OP', '{')] def _process_dict_comp( tokens: List[Token], start: int, arg: ListCompOrGeneratorExp, ) -> None: if _is_wtf('dict', tokens, start): return dict_victims = _victims(tokens, start + 1, arg, gen=True) elt_victims = _victims(tokens, dict_victims.arg_index, arg.elt, gen=True) del dict_victims.starts[0] end_index = dict_victims.ends.pop() tokens[end_index] = Token('OP', '}') for index in reversed(dict_victims.ends): _remove_brace(tokens, index) # See #6, Fix SyntaxError from rewriting dict((a, b)for a, b in y) if tokens[elt_victims.ends[-1] + 1].src == 'for': tokens.insert(elt_victims.ends[-1] + 1, Token(UNIMPORTANT_WS, ' ')) for index in reversed(elt_victims.ends): _remove_brace(tokens, index) assert elt_victims.first_comma_index is not None tokens[elt_victims.first_comma_index] = Token('OP', ':') for index in reversed(dict_victims.starts + elt_victims.starts): _remove_brace(tokens, index) tokens[start:start + 2] = [Token('OP', '{')] def _process_is_literal( tokens: List[Token], i: int, compare: Union[ast.Is, ast.IsNot], ) -> None: while tokens[i].src != 'is': i -= 1 if isinstance(compare, ast.Is): tokens[i] = tokens[i]._replace(src='==') else: tokens[i] = tokens[i]._replace(src='!=') # since we iterate backward, the dummy tokens keep the same length i += 1 while tokens[i].src != 'not': tokens[i] = Token('DUMMY', '') i += 1 tokens[i] = Token('DUMMY', '') LITERAL_TYPES = (ast.Str, ast.Num, ast.Bytes) class Py2CompatibleVisitor(ast.NodeVisitor): def __init__(self) -> None: self.dicts: Dict[Offset, ListCompOrGeneratorExp] = {} self.sets: Dict[Offset, ast.expr] = {} self.set_empty_literals: Dict[Offset, ListOrTuple] = {} self.is_literal: Dict[Offset, Union[ast.Is, ast.IsNot]] = {} def visit_Call(self, node: ast.Call) -> None: if ( isinstance(node.func, ast.Name) and node.func.id == 'set' and len(node.args) == 1 and not node.keywords and isinstance(node.args[0], SET_TRANSFORM) ): arg, = node.args key = _ast_to_offset(node.func) if isinstance(arg, (ast.List, ast.Tuple)) and not arg.elts: self.set_empty_literals[key] = arg else: self.sets[key] = arg elif ( isinstance(node.func, ast.Name) and node.func.id == 'dict' and len(node.args) == 1 and not node.keywords and isinstance(node.args[0], (ast.ListComp, ast.GeneratorExp)) and isinstance(node.args[0].elt, (ast.Tuple, ast.List)) and len(node.args[0].elt.elts) == 2 ): self.dicts[_ast_to_offset(node.func)] = node.args[0] self.generic_visit(node) def visit_Compare(self, node: ast.Compare) -> None: left = node.left for op, right in zip(node.ops, node.comparators): if ( isinstance(op, (ast.Is, ast.IsNot)) and ( isinstance(left, LITERAL_TYPES) or isinstance(right, LITERAL_TYPES) ) ): self.is_literal[_ast_to_offset(right)] = op left = right self.generic_visit(node) def _fix_py2_compatible(contents_text: str) -> str: try: ast_obj = ast_parse(contents_text) except SyntaxError: return contents_text visitor = Py2CompatibleVisitor() visitor.visit(ast_obj) if not any(( visitor.dicts, visitor.sets, visitor.set_empty_literals, visitor.is_literal, )): return contents_text try: tokens = src_to_tokens(contents_text) except tokenize.TokenError: # pragma: no cover (bpo-2180) return contents_text for i, token in reversed_enumerate(tokens): if token.offset in visitor.dicts: _process_dict_comp(tokens, i, visitor.dicts[token.offset]) elif token.offset in visitor.set_empty_literals: _process_set_empty_literal(tokens, i) elif token.offset in visitor.sets: _process_set_literal(tokens, i, visitor.sets[token.offset]) elif token.offset in visitor.is_literal: _process_is_literal(tokens, i, visitor.is_literal[token.offset]) return tokens_to_src(tokens) def _imports_future(contents_text: str, future_name: str) -> bool: try: ast_obj = ast_parse(contents_text) except SyntaxError: return False for node in ast_obj.body: # Docstring if isinstance(node, ast.Expr) and isinstance(node.value, ast.Str): continue elif isinstance(node, ast.ImportFrom): if ( node.level == 0 and node.module == '__future__' and any(name.name == future_name for name in node.names) ): return True elif node.module == '__future__': continue else: return False else: return False return False # https://docs.python.org/3/reference/lexical_analysis.html ESCAPE_STARTS = frozenset(( '\n', '\r', '\\', "'", '"', 'a', 'b', 'f', 'n', 'r', 't', 'v', '0', '1', '2', '3', '4', '5', '6', '7', # octal escapes 'x', # hex escapes )) ESCAPE_RE = re.compile(r'\\.', re.DOTALL) NAMED_ESCAPE_NAME = re.compile(r'\{[^}]+\}') def _fix_escape_sequences(token: Token) -> Token: prefix, rest = parse_string_literal(token.src) actual_prefix = prefix.lower() if 'r' in actual_prefix or '\\' not in rest: return token is_bytestring = 'b' in actual_prefix def _is_valid_escape(match: Match[str]) -> bool: c = match.group()[1] return ( c in ESCAPE_STARTS or (not is_bytestring and c in 'uU') or ( not is_bytestring and c == 'N' and bool(NAMED_ESCAPE_NAME.match(rest, match.end())) ) ) has_valid_escapes = False has_invalid_escapes = False for match in ESCAPE_RE.finditer(rest): if _is_valid_escape(match): has_valid_escapes = True else: has_invalid_escapes = True def cb(match: Match[str]) -> str: matched = match.group() if _is_valid_escape(match): return matched else: return fr'\{matched}' if has_invalid_escapes and (has_valid_escapes or 'u' in actual_prefix): return token._replace(src=prefix + ESCAPE_RE.sub(cb, rest)) elif has_invalid_escapes and not has_valid_escapes: return token._replace(src=prefix + 'r' + rest) else: return token def _remove_u_prefix(token: Token) -> Token: prefix, rest = parse_string_literal(token.src) if 'u' not in prefix.lower(): return token else: new_prefix = prefix.replace('u', '').replace('U', '') return token._replace(src=new_prefix + rest) def _fix_ur_literals(token: Token) -> Token: prefix, rest = parse_string_literal(token.src) if prefix.lower() != 'ur': return token else: def cb(match: Match[str]) -> str: escape = match.group() if escape[1].lower() == 'u': return escape else: return '\\' + match.group() rest = ESCAPE_RE.sub(cb, rest) prefix = prefix.replace('r', '').replace('R', '') return token._replace(src=prefix + rest) def _fix_long(src: str) -> str: return src.rstrip('lL') def _fix_octal(s: str) -> str: if not s.startswith('0') or not s.isdigit() or s == len(s) * '0': return s elif len(s) == 2: return s[1:] else: return '0o' + s[1:] def _fix_extraneous_parens(tokens: List[Token], i: int) -> None: # search forward for another non-coding token i += 1 while tokens[i].name in NON_CODING_TOKENS: i += 1 # if we did not find another brace, return immediately if tokens[i].src != '(': return start = i depth = 1 while depth: i += 1 # found comma or yield at depth 1: this is a tuple / coroutine if depth == 1 and tokens[i].src in {',', 'yield'}: return elif tokens[i].src in OPENING: depth += 1 elif tokens[i].src in CLOSING: depth -= 1 end = i # empty tuple if all(t.name in NON_CODING_TOKENS for t in tokens[start + 1:i]): return # search forward for the next non-coding token i += 1 while tokens[i].name in NON_CODING_TOKENS: i += 1 if tokens[i].src == ')': _remove_brace(tokens, end) _remove_brace(tokens, start) def _remove_fmt(tup: DotFormatPart) -> DotFormatPart: if tup[1] is None: return tup else: return (tup[0], '', tup[2], tup[3]) def _fix_format_literal(tokens: List[Token], end: int) -> None: parts = rfind_string_parts(tokens, end) parsed_parts = [] last_int = -1 for i in parts: # f'foo {0}'.format(...) would get turned into a SyntaxError prefix, _ = parse_string_literal(tokens[i].src) if 'f' in prefix.lower(): return try: parsed = parse_format(tokens[i].src) except ValueError: # the format literal was malformed, skip it return # The last segment will always be the end of the string and not a # format, slice avoids the `None` format key for _, fmtkey, spec, _ in parsed[:-1]: if ( fmtkey is not None and inty(fmtkey) and int(fmtkey) == last_int + 1 and spec is not None and '{' not in spec ): last_int += 1 else: return parsed_parts.append(tuple(_remove_fmt(tup) for tup in parsed)) for i, parsed in zip(parts, parsed_parts): tokens[i] = tokens[i]._replace(src=unparse_parsed_string(parsed)) def _fix_encode_to_binary(tokens: List[Token], i: int) -> None: # .encode() if ( i + 2 < len(tokens) and tokens[i + 1].src == '(' and tokens[i + 2].src == ')' ): victims = slice(i - 1, i + 3) latin1_ok = False # .encode('encoding') elif ( i + 3 < len(tokens) and tokens[i + 1].src == '(' and tokens[i + 2].name == 'STRING' and tokens[i + 3].src == ')' ): victims = slice(i - 1, i + 4) prefix, rest = parse_string_literal(tokens[i + 2].src) if 'f' in prefix.lower(): return encoding = ast.literal_eval(prefix + rest) if _is_codec(encoding, 'ascii') or _is_codec(encoding, 'utf-8'): latin1_ok = False elif _is_codec(encoding, 'iso8859-1'): latin1_ok = True else: return else: return parts = rfind_string_parts(tokens, i - 2) if not parts: return for part in parts: prefix, rest = parse_string_literal(tokens[part].src) escapes = set(ESCAPE_RE.findall(rest)) if ( not _is_ascii(rest) or '\\u' in escapes or '\\U' in escapes or '\\N' in escapes or ('\\x' in escapes and not latin1_ok) or 'f' in prefix.lower() ): return for part in parts: prefix, rest = parse_string_literal(tokens[part].src) prefix = 'b' + prefix.replace('u', '').replace('U', '') tokens[part] = tokens[part]._replace(src=prefix + rest) del tokens[victims] def _build_import_removals() -> Dict[MinVersion, Dict[str, Tuple[str, ...]]]: ret = {} future: Tuple[Tuple[MinVersion, Tuple[str, ...]], ...] = ( ((2, 7), ('nested_scopes', 'generators', 'with_statement')), ( (3,), ( 'absolute_import', 'division', 'print_function', 'unicode_literals', ), ), ((3, 6), ()), ((3, 7), ('generator_stop',)), ((3, 8), ()), ) prev: Tuple[str, ...] = () for min_version, names in future: prev += names ret[min_version] = {'__future__': prev} # see reorder_python_imports for k, v in ret.items(): if k >= (3,): v.update({ 'builtins': ( 'ascii', 'bytes', 'chr', 'dict', 'filter', 'hex', 'input', 'int', 'list', 'map', 'max', 'min', 'next', 'object', 'oct', 'open', 'pow', 'range', 'round', 'str', 'super', 'zip', '*', ), 'io': ('open',), 'six': ('callable', 'next'), 'six.moves': ('filter', 'input', 'map', 'range', 'zip'), }) return ret IMPORT_REMOVALS = _build_import_removals() def _fix_import_removals( tokens: List[Token], start: int, min_version: MinVersion, ) -> None: i = start + 1 name_parts = [] while tokens[i].src != 'import': if tokens[i].name in {'NAME', 'OP'}: name_parts.append(tokens[i].src) i += 1 modname = ''.join(name_parts) if modname not in IMPORT_REMOVALS[min_version]: return found: List[Optional[int]] = [] i += 1 while tokens[i].name not in {'NEWLINE', 'ENDMARKER'}: if tokens[i].name == 'NAME' or tokens[i].src == '*': # don't touch aliases if ( found and found[-1] is not None and tokens[found[-1]].src == 'as' ): found[-2:] = [None] else: found.append(i) i += 1 # depending on the version of python, some will not emit NEWLINE('') at the # end of a file which does not end with a newline (for example 3.6.5) if tokens[i].name == 'ENDMARKER': # pragma: no cover i -= 1 remove_names = IMPORT_REMOVALS[min_version][modname] to_remove = [ x for x in found if x is not None and tokens[x].src in remove_names ] if len(to_remove) == len(found): del tokens[start:i + 1] else: for idx in reversed(to_remove): if found[0] == idx: # look forward until next name and del j = idx + 1 while tokens[j].name != 'NAME': j += 1 del tokens[idx:j] else: # look backward for comma and del j = idx while tokens[j].src != ',': j -= 1 del tokens[j:idx + 1] def _fix_tokens(contents_text: str, min_version: MinVersion) -> str: remove_u = ( min_version >= (3,) or _imports_future(contents_text, 'unicode_literals') ) try: tokens = src_to_tokens(contents_text) except tokenize.TokenError: return contents_text for i, token in reversed_enumerate(tokens): if token.name == 'NUMBER': tokens[i] = token._replace(src=_fix_long(_fix_octal(token.src))) elif token.name == 'STRING': tokens[i] = _fix_ur_literals(tokens[i]) if remove_u: tokens[i] = _remove_u_prefix(tokens[i]) tokens[i] = _fix_escape_sequences(tokens[i]) elif token.src == '(': _fix_extraneous_parens(tokens, i) elif token.src == 'format' and i > 0 and tokens[i - 1].src == '.': _fix_format_literal(tokens, i - 2) elif token.src == 'encode' and i > 0 and tokens[i - 1].src == '.': _fix_encode_to_binary(tokens, i) elif ( min_version >= (3,) and token.utf8_byte_offset == 0 and token.line < 3 and token.name == 'COMMENT' and tokenize.cookie_re.match(token.src) ): del tokens[i] assert tokens[i].name == 'NL', tokens[i].name del tokens[i] elif token.src == 'from' and token.utf8_byte_offset == 0: _fix_import_removals(tokens, i, min_version) return tokens_to_src(tokens).lstrip() MAPPING_KEY_RE = re.compile(r'\(([^()]*)\)') CONVERSION_FLAG_RE = re.compile('[#0+ -]*') WIDTH_RE = re.compile(r'(?:\*|\d*)') PRECISION_RE = re.compile(r'(?:\.(?:\*|\d*))?') LENGTH_RE = re.compile('[hlL]?') def _must_match(regex: Pattern[str], string: str, pos: int) -> Match[str]: match = regex.match(string, pos) assert match is not None return match def parse_percent_format(s: str) -> Tuple[PercentFormat, ...]: def _parse_inner() -> Generator[PercentFormat, None, None]: string_start = 0 string_end = 0 in_fmt = False i = 0 while i < len(s): if not in_fmt: try: i = s.index('%', i) except ValueError: # no more % fields! yield s[string_start:], None return else: string_end = i i += 1 in_fmt = True else: key_match = MAPPING_KEY_RE.match(s, i) if key_match: key: Optional[str] = key_match.group(1) i = key_match.end() else: key = None conversion_flag_match = _must_match(CONVERSION_FLAG_RE, s, i) conversion_flag = conversion_flag_match.group() or None i = conversion_flag_match.end() width_match = _must_match(WIDTH_RE, s, i) width = width_match.group() or None i = width_match.end() precision_match = _must_match(PRECISION_RE, s, i) precision = precision_match.group() or None i = precision_match.end() # length modifier is ignored i = _must_match(LENGTH_RE, s, i).end() try: conversion = s[i] except IndexError: raise ValueError('end-of-string while parsing format') i += 1 fmt = (key, conversion_flag, width, precision, conversion) yield s[string_start:string_end], fmt in_fmt = False string_start = i if in_fmt: raise ValueError('end-of-string while parsing format') return tuple(_parse_inner()) class FindPercentFormats(ast.NodeVisitor): def __init__(self) -> None: self.found: Dict[Offset, ast.BinOp] = {} def visit_BinOp(self, node: ast.BinOp) -> None: if isinstance(node.op, ast.Mod) and isinstance(node.left, ast.Str): try: parsed = parse_percent_format(node.left.s) except ValueError: pass else: for _, fmt in parsed: if not fmt: continue key, conversion_flag, width, precision, conversion = fmt # timid: these require out-of-order parameter consumption if width == '*' or precision == '.*': break # these conversions require modification of parameters if conversion in {'d', 'i', 'u', 'c'}: break # timid: py2: %#o formats different from {:#o} (--py3?) if '#' in (conversion_flag or '') and conversion == 'o': break # no equivalent in format if key == '': break # timid: py2: conversion is subject to modifiers (--py3?) nontrivial_fmt = any((conversion_flag, width, precision)) if conversion == '%' and nontrivial_fmt: break # no equivalent in format if conversion in {'a', 'r'} and nontrivial_fmt: break # all dict substitutions must be named if isinstance(node.right, ast.Dict) and not key: break else: self.found[_ast_to_offset(node)] = node self.generic_visit(node) def _simplify_conversion_flag(flag: str) -> str: parts: List[str] = [] for c in flag: if c in parts: continue c = c.replace('-', '<') parts.append(c) if c == '<' and '0' in parts: parts.remove('0') elif c == '+' and ' ' in parts: parts.remove(' ') return ''.join(parts) def _percent_to_format(s: str) -> str: def _handle_part(part: PercentFormat) -> str: s, fmt = part s = s.replace('{', '{{').replace('}', '}}') if fmt is None: return s else: key, conversion_flag, width, precision, conversion = fmt if conversion == '%': return s + '%' parts = [s, '{'] if width and conversion == 's' and not conversion_flag: conversion_flag = '>' if conversion == 's': conversion = '' if key: parts.append(key) if conversion in {'r', 'a'}: converter = f'!{conversion}' conversion = '' else: converter = '' if any((conversion_flag, width, precision, conversion)): parts.append(':') if conversion_flag: parts.append(_simplify_conversion_flag(conversion_flag)) parts.extend(x for x in (width, precision, conversion) if x) parts.extend(converter) parts.append('}') return ''.join(parts) return ''.join(_handle_part(part) for part in parse_percent_format(s)) def _is_ascii(s: str) -> bool: if sys.version_info >= (3, 7): # pragma: no cover (py37+) return s.isascii() else: # pragma: no cover (<py37) return all(c in string.printable for c in s) def _fix_percent_format_tuple( tokens: List[Token], start: int, node: ast.BinOp, ) -> None: # TODO: this is overly timid paren = start + 4 if tokens_to_src(tokens[start + 1:paren + 1]) != ' % (': return victims = _victims(tokens, paren, node.right, gen=False) victims.ends.pop() for index in reversed(victims.starts + victims.ends): _remove_brace(tokens, index) newsrc = _percent_to_format(tokens[start].src) tokens[start] = tokens[start]._replace(src=newsrc) tokens[start + 1:paren] = [Token('Format', '.format'), Token('OP', '(')] def _fix_percent_format_dict( tokens: List[Token], start: int, node: ast.BinOp, ) -> None: seen_keys: Set[str] = set() keys = {} # the caller has enforced this assert isinstance(node.right, ast.Dict) for k in node.right.keys: # not a string key if not isinstance(k, ast.Str): return # duplicate key elif k.s in seen_keys: return # not an identifier elif not k.s.isidentifier(): return # a keyword elif k.s in _KEYWORDS: return seen_keys.add(k.s) keys[_ast_to_offset(k)] = k # TODO: this is overly timid brace = start + 4 if tokens_to_src(tokens[start + 1:brace + 1]) != ' % {': return victims = _victims(tokens, brace, node.right, gen=False) brace_end = victims.ends[-1] key_indices = [] for i, token in enumerate(tokens[brace:brace_end], brace): key = keys.pop(token.offset, None) if key is None: continue # we found the key, but the string didn't match (implicit join?) elif ast.literal_eval(token.src) != key.s: return # the map uses some strange syntax that's not `'key': value` elif tokens_to_src(tokens[i + 1:i + 3]) != ': ': return else: key_indices.append((i, key.s)) assert not keys, keys tokens[brace_end] = tokens[brace_end]._replace(src=')') for (key_index, s) in reversed(key_indices): tokens[key_index:key_index + 3] = [Token('CODE', f'{s}=')] newsrc = _percent_to_format(tokens[start].src) tokens[start] = tokens[start]._replace(src=newsrc) tokens[start + 1:brace + 1] = [Token('CODE', '.format'), Token('OP', '(')] def _fix_percent_format(contents_text: str) -> str: try: ast_obj = ast_parse(contents_text) except SyntaxError: return contents_text visitor = FindPercentFormats() visitor.visit(ast_obj) if not visitor.found: return contents_text try: tokens = src_to_tokens(contents_text) except tokenize.TokenError: # pragma: no cover (bpo-2180) return contents_text for i, token in reversed_enumerate(tokens): node = visitor.found.get(token.offset) if node is None: continue # TODO: handle \N escape sequences if r'\N' in token.src: continue if isinstance(node.right, ast.Tuple): _fix_percent_format_tuple(tokens, i, node) elif isinstance(node.right, ast.Dict): _fix_percent_format_dict(tokens, i, node) return tokens_to_src(tokens) SIX_SIMPLE_ATTRS = { 'text_type': 'str', 'binary_type': 'bytes', 'class_types': '(type,)', 'string_types': '(str,)', 'integer_types': '(int,)', 'unichr': 'chr', 'iterbytes': 'iter', 'print_': 'print', 'exec_': 'exec', 'advance_iterator': 'next', 'next': 'next', 'callable': 'callable', } SIX_TYPE_CTX_ATTRS = { 'class_types': 'type', 'string_types': 'str', 'integer_types': 'int', } SIX_CALLS = { 'u': '{args[0]}', 'byte2int': '{args[0]}[0]', 'indexbytes': '{args[0]}[{rest}]', 'iteritems': '{args[0]}.items()', 'iterkeys': '{args[0]}.keys()', 'itervalues': '{args[0]}.values()', 'viewitems': '{args[0]}.items()', 'viewkeys': '{args[0]}.keys()', 'viewvalues': '{args[0]}.values()', 'create_unbound_method': '{args[0]}', 'get_unbound_function': '{args[0]}', 'get_method_function': '{args[0]}.__func__', 'get_method_self': '{args[0]}.__self__', 'get_function_closure': '{args[0]}.__closure__', 'get_function_code': '{args[0]}.__code__', 'get_function_defaults': '{args[0]}.__defaults__', 'get_function_globals': '{args[0]}.__globals__', 'assertCountEqual': '{args[0]}.assertCountEqual({rest})', 'assertRaisesRegex': '{args[0]}.assertRaisesRegex({rest})', 'assertRegex': '{args[0]}.assertRegex({rest})', } SIX_INT2BYTE_TMPL = 'bytes(({args[0]},))' SIX_B_TMPL = 'b{args[0]}' WITH_METACLASS_NO_BASES_TMPL = 'metaclass={args[0]}' WITH_METACLASS_BASES_TMPL = '{rest}, metaclass={args[0]}' RAISE_FROM_TMPL = 'raise {args[0]} from {rest}' RERAISE_TMPL = 'raise' RERAISE_2_TMPL = 'raise {args[1]}.with_traceback(None)' RERAISE_3_TMPL = 'raise {args[1]}.with_traceback({args[2]})' SIX_NATIVE_STR = frozenset(('ensure_str', 'ensure_text', 'text_type')) U_MODE_REMOVE = frozenset(('U', 'Ur', 'rU', 'r', 'rt', 'tr')) U_MODE_REPLACE_R = frozenset(('Ub', 'bU')) U_MODE_REMOVE_U = frozenset(('rUb', 'Urb', 'rbU', 'Ubr', 'bUr', 'brU')) U_MODE_REPLACE = U_MODE_REPLACE_R | U_MODE_REMOVE_U PEP585_BUILTINS = { k: k.lower() for k in ('Dict', 'FrozenSet', 'List', 'Set', 'Tuple', 'Type') } def _all_isinstance( vals: Iterable[Any], tp: Union[Type[Any], Tuple[Type[Any], ...]], ) -> bool: return all(isinstance(v, tp) for v in vals) def fields_same(n1: ast.AST, n2: ast.AST) -> bool: for (a1, v1), (a2, v2) in zip(ast.iter_fields(n1), ast.iter_fields(n2)): # ignore ast attributes, they'll be covered by walk if a1 != a2: return False elif _all_isinstance((v1, v2), ast.AST): continue elif _all_isinstance((v1, v2), (list, tuple)): if len(v1) != len(v2): return False # ignore sequences which are all-ast, they'll be covered by walk elif _all_isinstance(v1, ast.AST) and _all_isinstance(v2, ast.AST): continue elif v1 != v2: return False elif v1 != v2: return False return True def targets_same(target: ast.AST, yield_value: ast.AST) -> bool: for t1, t2 in zip(ast.walk(target), ast.walk(yield_value)): # ignore `ast.Load` / `ast.Store` if _all_isinstance((t1, t2), ast.expr_context): continue elif type(t1) != type(t2): return False elif not fields_same(t1, t2): return False else: return True def _is_codec(encoding: str, name: str) -> bool: try: return codecs.lookup(encoding).name == name except LookupError: return False class FindPy3Plus(ast.NodeVisitor): OS_ERROR_ALIASES = frozenset(( 'EnvironmentError', 'IOError', 'WindowsError', )) OS_ERROR_ALIAS_MODULES = frozenset(( 'mmap', 'select', 'socket', )) FROM_IMPORTED_MODULES = OS_ERROR_ALIAS_MODULES.union(( 'functools', 'six', 'typing', )) MOCK_MODULES = frozenset(('mock', 'mock.mock')) class ClassInfo: def __init__(self, name: str) -> None: self.name = name self.def_depth = 0 self.first_arg_name = '' class Scope: def __init__(self) -> None: self.reads: Set[str] = set() self.writes: Set[str] = set() self.yield_from_fors: Set[Offset] = set() self.yield_from_names: Dict[str, Set[Offset]] self.yield_from_names = collections.defaultdict(set) def __init__(self, version: Tuple[int, ...], keep_mock: bool) -> None: self._version = version self._find_mock = not keep_mock self.bases_to_remove: Set[Offset] = set() self.encode_calls: Dict[Offset, ast.Call] = {} self._exc_info_imported = False self._version_info_imported = False self.if_py3_blocks: Set[Offset] = set() self.if_py2_blocks_else: Set[Offset] = set() self.if_py3_blocks_else: Set[Offset] = set() self.metaclass_type_assignments: Set[Offset] = set() self.native_literals: Set[Offset] = set() self._from_imports: Dict[str, Set[str]] = collections.defaultdict(set) self.io_open_calls: Set[Offset] = set() self.mock_mock: Set[Offset] = set() self.mock_absolute_imports: Set[Offset] = set() self.mock_relative_imports: Set[Offset] = set() self.open_mode_calls: Set[Offset] = set() self.os_error_alias_calls: Set[Offset] = set() self.os_error_alias_simple: Dict[Offset, NameOrAttr] = {} self.os_error_alias_excepts: Set[Offset] = set() self.six_add_metaclass: Set[Offset] = set() self.six_b: Set[Offset] = set() self.six_calls: Dict[Offset, ast.Call] = {} self.six_calls_int2byte: Set[Offset] = set() self.six_iter: Dict[Offset, ast.Call] = {} self._previous_node: Optional[ast.AST] = None self.six_raise_from: Set[Offset] = set() self.six_reraise: Set[Offset] = set() self.six_remove_decorators: Set[Offset] = set() self.six_simple: Dict[Offset, NameOrAttr] = {} self.six_type_ctx: Dict[Offset, NameOrAttr] = {} self.six_with_metaclass: Set[Offset] = set() self._in_type_annotation = False self.typing_builtin_renames: Dict[Offset, NameOrAttr] = {} self._class_info_stack: List[FindPy3Plus.ClassInfo] = [] self._in_comp = 0 self.super_calls: Dict[Offset, ast.Call] = {} self._in_async_def = False self._scope_stack: List[FindPy3Plus.Scope] = [] self.yield_from_fors: Set[Offset] = set() self.no_arg_decorators: Set[Offset] = set() def _is_six(self, node: ast.expr, names: Container[str]) -> bool: return ( isinstance(node, ast.Name) and node.id in names and node.id in self._from_imports['six'] ) or ( isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id == 'six' and node.attr in names ) def _is_star_sys_exc_info(self, node: ast.Call) -> bool: return ( len(node.args) == 1 and isinstance(node.args[0], ast.Starred) and isinstance(node.args[0].value, ast.Call) and self._is_exc_info(node.args[0].value.func) ) def _is_lru_cache(self, node: ast.expr) -> bool: return ( isinstance(node, ast.Name) and node.id == 'lru_cache' and node.id in self._from_imports['functools'] ) or ( isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id == 'functools' and node.attr == 'lru_cache' ) def _is_mock_mock(self, node: ast.expr) -> bool: return ( isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id == 'mock' and node.attr == 'mock' ) def _is_io_open(self, node: ast.expr) -> bool: return ( isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id == 'io' and node.attr == 'open' ) def _is_os_error_alias(self, node: Optional[ast.expr]) -> bool: return ( isinstance(node, ast.Name) and node.id in self.OS_ERROR_ALIASES ) or ( isinstance(node, ast.Name) and node.id == 'error' and ( node.id in self._from_imports['mmap'] or node.id in self._from_imports['select'] or node.id in self._from_imports['socket'] ) ) or ( isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id in self.OS_ERROR_ALIAS_MODULES and node.attr == 'error' ) def _is_exc_info(self, node: ast.expr) -> bool: return ( isinstance(node, ast.Name) and node.id == 'exc_info' and self._exc_info_imported ) or ( isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id == 'sys' and node.attr == 'exc_info' ) def _is_version_info(self, node: ast.expr) -> bool: return ( isinstance(node, ast.Name) and node.id == 'version_info' and self._version_info_imported ) or ( isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id == 'sys' and node.attr == 'version_info' ) def visit_ImportFrom(self, node: ast.ImportFrom) -> None: if not node.level: if node.module in self.FROM_IMPORTED_MODULES: for name in node.names: if not name.asname: self._from_imports[node.module].add(name.name) elif self._find_mock and node.module in self.MOCK_MODULES: self.mock_relative_imports.add(_ast_to_offset(node)) elif node.module == 'sys' and any( name.name == 'exc_info' and not name.asname for name in node.names ): self._exc_info_imported = True elif node.module == 'sys' and any( name.name == 'version_info' and not name.asname for name in node.names ): self._version_info_imported = True self.generic_visit(node) def visit_Import(self, node: ast.Import) -> None: if ( self._find_mock and len(node.names) == 1 and node.names[0].name in self.MOCK_MODULES ): self.mock_absolute_imports.add(_ast_to_offset(node)) self.generic_visit(node) def visit_ClassDef(self, node: ast.ClassDef) -> None: for decorator in node.decorator_list: if self._is_six(decorator, ('python_2_unicode_compatible',)): self.six_remove_decorators.add(_ast_to_offset(decorator)) elif ( isinstance(decorator, ast.Call) and self._is_six(decorator.func, ('add_metaclass',)) and not _starargs(decorator) ): self.six_add_metaclass.add(_ast_to_offset(decorator)) for base in node.bases: if isinstance(base, ast.Name) and base.id == 'object': self.bases_to_remove.add(_ast_to_offset(base)) elif self._is_six(base, ('Iterator',)): self.bases_to_remove.add(_ast_to_offset(base)) if ( len(node.bases) == 1 and isinstance(node.bases[0], ast.Call) and self._is_six(node.bases[0].func, ('with_metaclass',)) and not _starargs(node.bases[0]) ): self.six_with_metaclass.add(_ast_to_offset(node.bases[0])) self._class_info_stack.append(FindPy3Plus.ClassInfo(node.name)) self.generic_visit(node) self._class_info_stack.pop() @contextlib.contextmanager def _track_def_depth( self, node: AnyFunctionDef, ) -> Generator[None, None, None]: class_info = self._class_info_stack[-1] class_info.def_depth += 1 if class_info.def_depth == 1 and node.args.args: class_info.first_arg_name = node.args.args[0].arg try: yield finally: class_info.def_depth -= 1 @contextlib.contextmanager def _scope(self) -> Generator[None, None, None]: self._scope_stack.append(FindPy3Plus.Scope()) try: yield finally: info = self._scope_stack.pop() # discard any that were referenced outside of the loop for name in info.reads: offsets = info.yield_from_names[name] info.yield_from_fors.difference_update(offsets) self.yield_from_fors.update(info.yield_from_fors) if self._scope_stack: cell_reads = info.reads - info.writes self._scope_stack[-1].reads.update(cell_reads) def _visit_annotation(self, node: ast.AST) -> None: orig, self._in_type_annotation = self._in_type_annotation, True self.generic_visit(node) self._in_type_annotation = orig def _visit_func(self, node: AnyFunctionDef) -> None: with contextlib.ExitStack() as ctx, self._scope(): if self._class_info_stack: ctx.enter_context(self._track_def_depth(node)) if not isinstance(node, ast.Lambda) and node.returns is not None: self._visit_annotation(node.returns) self.generic_visit(node) def _visit_sync_func(self, node: SyncFunctionDef) -> None: self._in_async_def, orig = False, self._in_async_def self._visit_func(node) self._in_async_def = orig visit_FunctionDef = visit_Lambda = _visit_sync_func def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None: self._in_async_def, orig = True, self._in_async_def self._visit_func(node) self._in_async_def = orig def visit_arg(self, node: ast.arg) -> None: if node.annotation is not None: self._visit_annotation(node.annotation) self.generic_visit(node) def visit_AnnAssign(self, node: ast.AnnAssign) -> None: self._visit_annotation(node.annotation) self.generic_visit(node) def _visit_comp(self, node: ast.expr) -> None: self._in_comp += 1 with self._scope(): self.generic_visit(node) self._in_comp -= 1 visit_ListComp = visit_SetComp = _visit_comp visit_DictComp = visit_GeneratorExp = _visit_comp def visit_Attribute(self, node: ast.Attribute) -> None: if self._is_six(node, SIX_SIMPLE_ATTRS): self.six_simple[_ast_to_offset(node)] = node elif self._find_mock and self._is_mock_mock(node): self.mock_mock.add(_ast_to_offset(node)) elif ( ( self._version >= (3, 9) or self._in_type_annotation ) and isinstance(node.value, ast.Name) and node.value.id == 'typing' and node.attr in PEP585_BUILTINS ): self.typing_builtin_renames[_ast_to_offset(node)] = node self.generic_visit(node) def visit_Name(self, node: ast.Name) -> None: if self._is_six(node, SIX_SIMPLE_ATTRS): self.six_simple[_ast_to_offset(node)] = node elif ( ( self._version >= (3, 9) or self._in_type_annotation ) and node.id in PEP585_BUILTINS and node.id in self._from_imports['typing'] ): self.typing_builtin_renames[_ast_to_offset(node)] = node if self._scope_stack: if isinstance(node.ctx, ast.Load): self._scope_stack[-1].reads.add(node.id) elif isinstance(node.ctx, (ast.Store, ast.Del)): self._scope_stack[-1].writes.add(node.id) else: raise AssertionError(node) self.generic_visit(node) def visit_Try(self, node: ast.Try) -> None: for handler in node.handlers: htype = handler.type if self._is_os_error_alias(htype): assert isinstance(htype, (ast.Name, ast.Attribute)) self.os_error_alias_simple[_ast_to_offset(htype)] = htype elif ( isinstance(htype, ast.Tuple) and any( self._is_os_error_alias(elt) for elt in htype.elts ) ): self.os_error_alias_excepts.add(_ast_to_offset(htype)) self.generic_visit(node) def visit_Raise(self, node: ast.Raise) -> None: exc = node.exc if exc is not None and self._is_os_error_alias(exc): assert isinstance(exc, (ast.Name, ast.Attribute)) self.os_error_alias_simple[_ast_to_offset(exc)] = exc elif ( isinstance(exc, ast.Call) and self._is_os_error_alias(exc.func) ): self.os_error_alias_calls.add(_ast_to_offset(exc)) self.generic_visit(node) def visit_Call(self, node: ast.Call) -> None: if ( isinstance(node.func, ast.Name) and node.func.id in {'isinstance', 'issubclass'} and len(node.args) == 2 and self._is_six(node.args[1], SIX_TYPE_CTX_ATTRS) ): arg = node.args[1] # _is_six() enforces this assert isinstance(arg, (ast.Name, ast.Attribute)) self.six_type_ctx[_ast_to_offset(node.args[1])] = arg elif self._is_six(node.func, ('b', 'ensure_binary')): self.six_b.add(_ast_to_offset(node)) elif ( self._is_six(node.func, SIX_CALLS) and node.args and not _starargs(node) ): self.six_calls[_ast_to_offset(node)] = node elif ( self._is_six(node.func, ('int2byte',)) and node.args and not _starargs(node) ): self.six_calls_int2byte.add(_ast_to_offset(node)) elif ( isinstance(node.func, ast.Name) and node.func.id == 'next' and not _starargs(node) and len(node.args) == 1 and isinstance(node.args[0], ast.Call) and self._is_six( node.args[0].func, ('iteritems', 'iterkeys', 'itervalues'), ) and not _starargs(node.args[0]) ): self.six_iter[_ast_to_offset(node.args[0])] = node.args[0] elif ( isinstance(self._previous_node, ast.Expr) and self._is_six(node.func, ('raise_from',)) and not _starargs(node) ): self.six_raise_from.add(_ast_to_offset(node)) elif ( isinstance(self._previous_node, ast.Expr) and self._is_six(node.func, ('reraise',)) and (not _starargs(node) or self._is_star_sys_exc_info(node)) ): self.six_reraise.add(_ast_to_offset(node)) elif ( not self._in_comp and self._class_info_stack and self._class_info_stack[-1].def_depth == 1 and isinstance(node.func, ast.Name) and node.func.id == 'super' and len(node.args) == 2 and isinstance(node.args[0], ast.Name) and isinstance(node.args[1], ast.Name) and node.args[0].id == self._class_info_stack[-1].name and node.args[1].id == self._class_info_stack[-1].first_arg_name ): self.super_calls[_ast_to_offset(node)] = node elif ( ( self._is_six(node.func, SIX_NATIVE_STR) or isinstance(node.func, ast.Name) and node.func.id == 'str' ) and not node.keywords and not _starargs(node) and ( len(node.args) == 0 or ( len(node.args) == 1 and isinstance(node.args[0], ast.Str) ) ) ): self.native_literals.add(_ast_to_offset(node)) elif ( isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Str) and node.func.attr == 'encode' and not _starargs(node) and len(node.args) == 1 and isinstance(node.args[0], ast.Str) and _is_codec(node.args[0].s, 'utf-8') ): self.encode_calls[_ast_to_offset(node)] = node elif self._is_io_open(node.func): self.io_open_calls.add(_ast_to_offset(node)) elif ( isinstance(node.func, ast.Name) and node.func.id == 'open' and not _starargs(node) and len(node.args) >= 2 and isinstance(node.args[1], ast.Str) and ( node.args[1].s in U_MODE_REPLACE or (len(node.args) == 2 and node.args[1].s in U_MODE_REMOVE) ) ): self.open_mode_calls.add(_ast_to_offset(node)) elif ( not node.args and not node.keywords and self._is_lru_cache(node.func) ): self.no_arg_decorators.add(_ast_to_offset(node)) self.generic_visit(node) def visit_Assign(self, node: ast.Assign) -> None: if ( len(node.targets) == 1 and isinstance(node.targets[0], ast.Name) and node.targets[0].col_offset == 0 and node.targets[0].id == '__metaclass__' and isinstance(node.value, ast.Name) and node.value.id == 'type' ): self.metaclass_type_assignments.add(_ast_to_offset(node)) self.generic_visit(node) @staticmethod def _eq(test: ast.Compare, n: int) -> bool: return ( isinstance(test.ops[0], ast.Eq) and isinstance(test.comparators[0], ast.Num) and test.comparators[0].n == n ) @staticmethod def _compare_to_3( test: ast.Compare, op: Union[Type[ast.cmpop], Tuple[Type[ast.cmpop], ...]], ) -> bool: if not ( isinstance(test.ops[0], op) and isinstance(test.comparators[0], ast.Tuple) and len(test.comparators[0].elts) >= 1 and all(isinstance(n, ast.Num) for n in test.comparators[0].elts) ): return False # checked above but mypy needs help elts = cast('List[ast.Num]', test.comparators[0].elts) return elts[0].n == 3 and all(n.n == 0 for n in elts[1:]) def visit_If(self, node: ast.If) -> None: if ( # if six.PY2: self._is_six(node.test, ('PY2',)) or # if not six.PY3: ( isinstance(node.test, ast.UnaryOp) and isinstance(node.test.op, ast.Not) and self._is_six(node.test.operand, ('PY3',)) ) or # sys.version_info == 2 or < (3,) ( isinstance(node.test, ast.Compare) and self._is_version_info(node.test.left) and len(node.test.ops) == 1 and ( self._eq(node.test, 2) or self._compare_to_3(node.test, ast.Lt) ) ) ): if node.orelse and not isinstance(node.orelse[0], ast.If): self.if_py2_blocks_else.add(_ast_to_offset(node)) elif ( # if six.PY3: self._is_six(node.test, 'PY3') or # if not six.PY2: ( isinstance(node.test, ast.UnaryOp) and isinstance(node.test.op, ast.Not) and self._is_six(node.test.operand, ('PY2',)) ) or # sys.version_info == 3 or >= (3,) or > (3,) ( isinstance(node.test, ast.Compare) and self._is_version_info(node.test.left) and len(node.test.ops) == 1 and ( self._eq(node.test, 3) or self._compare_to_3(node.test, (ast.Gt, ast.GtE)) ) ) ): if node.orelse and not isinstance(node.orelse[0], ast.If): self.if_py3_blocks_else.add(_ast_to_offset(node)) elif not node.orelse: self.if_py3_blocks.add(_ast_to_offset(node)) self.generic_visit(node) def visit_For(self, node: ast.For) -> None: if ( not self._in_async_def and len(node.body) == 1 and isinstance(node.body[0], ast.Expr) and isinstance(node.body[0].value, ast.Yield) and node.body[0].value.value is not None and targets_same(node.target, node.body[0].value.value) and not node.orelse ): offset = _ast_to_offset(node) func_info = self._scope_stack[-1] func_info.yield_from_fors.add(offset) for target_node in ast.walk(node.target): if ( isinstance(target_node, ast.Name) and isinstance(target_node.ctx, ast.Store) ): func_info.yield_from_names[target_node.id].add(offset) # manually visit, but with target+body as a separate scope self.visit(node.iter) with self._scope(): self.visit(node.target) for stmt in node.body: self.visit(stmt) assert not node.orelse else: self.generic_visit(node) def generic_visit(self, node: ast.AST) -> None: self._previous_node = node super().generic_visit(node) def _fixup_dedent_tokens(tokens: List[Token]) -> None: """For whatever reason the DEDENT / UNIMPORTANT_WS tokens are misordered | if True: | if True: | pass | else: |^ ^- DEDENT |+----UNIMPORTANT_WS """ for i, token in enumerate(tokens): if token.name == UNIMPORTANT_WS and tokens[i + 1].name == 'DEDENT': tokens[i], tokens[i + 1] = tokens[i + 1], tokens[i] def _find_block_start(tokens: List[Token], i: int) -> int: depth = 0 while depth or tokens[i].src != ':': if tokens[i].src in OPENING: depth += 1 elif tokens[i].src in CLOSING: depth -= 1 i += 1 return i class Block(NamedTuple): start: int colon: int block: int end: int line: bool def _initial_indent(self, tokens: List[Token]) -> int: if tokens[self.start].src.isspace(): return len(tokens[self.start].src) else: return 0 def _minimum_indent(self, tokens: List[Token]) -> int: block_indent = None for i in range(self.block, self.end): if ( tokens[i - 1].name in ('NL', 'NEWLINE') and tokens[i].name in ('INDENT', UNIMPORTANT_WS) ): token_indent = len(tokens[i].src) if block_indent is None: block_indent = token_indent else: block_indent = min(block_indent, token_indent) assert block_indent is not None return block_indent def dedent(self, tokens: List[Token]) -> None: if self.line: return diff = self._minimum_indent(tokens) - self._initial_indent(tokens) for i in range(self.block, self.end): if ( tokens[i - 1].name in ('DEDENT', 'NL', 'NEWLINE') and tokens[i].name in ('INDENT', UNIMPORTANT_WS) ): tokens[i] = tokens[i]._replace(src=tokens[i].src[diff:]) def replace_condition(self, tokens: List[Token], new: List[Token]) -> None: tokens[self.start:self.colon] = new def _trim_end(self, tokens: List[Token]) -> 'Block': """the tokenizer reports the end of the block at the beginning of the next block """ i = last_token = self.end - 1 while tokens[i].name in NON_CODING_TOKENS | {'DEDENT', 'NEWLINE'}: # if we find an indented comment inside our block, keep it if ( tokens[i].name in {'NL', 'NEWLINE'} and tokens[i + 1].name == UNIMPORTANT_WS and len(tokens[i + 1].src) > self._initial_indent(tokens) ): break # otherwise we've found another line to remove elif tokens[i].name in {'NL', 'NEWLINE'}: last_token = i i -= 1 return self._replace(end=last_token + 1) @classmethod def find( cls, tokens: List[Token], i: int, trim_end: bool = False, ) -> 'Block': if i > 0 and tokens[i - 1].name in {'INDENT', UNIMPORTANT_WS}: i -= 1 start = i colon = _find_block_start(tokens, i) j = colon + 1 while ( tokens[j].name != 'NEWLINE' and tokens[j].name in NON_CODING_TOKENS ): j += 1 if tokens[j].name == 'NEWLINE': # multi line block block = j + 1 while tokens[j].name != 'INDENT': j += 1 level = 1 j += 1 while level: level += {'INDENT': 1, 'DEDENT': -1}.get(tokens[j].name, 0) j += 1 ret = cls(start, colon, block, j, line=False) if trim_end: return ret._trim_end(tokens) else: return ret else: # single line block block = j j = _find_end(tokens, j) return cls(start, colon, block, j, line=True) def _find_end(tokens: List[Token], i: int) -> int: while tokens[i].name not in {'NEWLINE', 'ENDMARKER'}: i += 1 # depending on the version of python, some will not emit # NEWLINE('') at the end of a file which does not end with a # newline (for example 3.6.5) if tokens[i].name == 'ENDMARKER': # pragma: no cover i -= 1 else: i += 1 return i def _find_if_else_block(tokens: List[Token], i: int) -> Tuple[Block, Block]: if_block = Block.find(tokens, i) i = if_block.end while tokens[i].src != 'else': i += 1 else_block = Block.find(tokens, i, trim_end=True) return if_block, else_block def _find_elif(tokens: List[Token], i: int) -> int: while tokens[i].src != 'elif': # pragma: no cover (only for <3.8.1) i -= 1 return i def _remove_decorator(tokens: List[Token], i: int) -> None: while tokens[i - 1].src != '@': i -= 1 if i > 1 and tokens[i - 2].name not in {'NEWLINE', 'NL'}: i -= 1 end = i + 1 while tokens[end].name != 'NEWLINE': end += 1 del tokens[i - 1:end + 1] def _remove_base_class(tokens: List[Token], i: int) -> None: # look forward and backward to find commas / parens brace_stack = [] j = i while tokens[j].src not in {',', ':'}: if tokens[j].src == ')': brace_stack.append(j) j += 1 right = j if tokens[right].src == ':': brace_stack.pop() else: # if there's a close-paren after a trailing comma j = right + 1 while tokens[j].name in NON_CODING_TOKENS: j += 1 if tokens[j].src == ')': while tokens[j].src != ':': j += 1 right = j if brace_stack: last_part = brace_stack[-1] else: last_part = i j = i while brace_stack: if tokens[j].src == '(': brace_stack.pop() j -= 1 while tokens[j].src not in {',', '('}: j -= 1 left = j # single base, remove the entire bases if tokens[left].src == '(' and tokens[right].src == ':': del tokens[left:right] # multiple bases, base is first elif tokens[left].src == '(' and tokens[right].src != ':': # if there's space / comment afterwards remove that too while tokens[right + 1].name in {UNIMPORTANT_WS, 'COMMENT'}: right += 1 del tokens[left + 1:right + 1] # multiple bases, base is not first else: del tokens[left:last_part + 1] def _parse_call_args( tokens: List[Token], i: int, ) -> Tuple[List[Tuple[int, int]], int]: args = [] stack = [i] i += 1 arg_start = i while stack: token = tokens[i] if len(stack) == 1 and token.src == ',': args.append((arg_start, i)) arg_start = i + 1 elif token.src in BRACES: stack.append(i) elif token.src == BRACES[tokens[stack[-1]].src]: stack.pop() # if we're at the end, append that argument if not stack and tokens_to_src(tokens[arg_start:i]).strip(): args.append((arg_start, i)) i += 1 return args, i def _get_tmpl(mapping: Dict[str, str], node: NameOrAttr) -> str: if isinstance(node, ast.Name): return mapping[node.id] else: return mapping[node.attr] def _arg_str(tokens: List[Token], start: int, end: int) -> str: return tokens_to_src(tokens[start:end]).strip() def _replace_call( tokens: List[Token], start: int, end: int, args: List[Tuple[int, int]], tmpl: str, *, parens: Sequence[int] = (), ) -> None: arg_strs = [_arg_str(tokens, *arg) for arg in args] for paren in parens: arg_strs[paren] = f'({arg_strs[paren]})' start_rest = args[0][1] + 1 while ( start_rest < end and tokens[start_rest].name in {'COMMENT', UNIMPORTANT_WS} ): start_rest += 1 rest = tokens_to_src(tokens[start_rest:end - 1]) src = tmpl.format(args=arg_strs, rest=rest) tokens[start:end] = [Token('CODE', src)] def _replace_yield(tokens: List[Token], i: int) -> None: in_token = _find_token(tokens, i, 'in') colon = _find_block_start(tokens, i) block = Block.find(tokens, i, trim_end=True) container = tokens_to_src(tokens[in_token + 1:colon]).strip() tokens[i:block.end] = [Token('CODE', f'yield from {container}\n')] def _fix_py3_plus( contents_text: str, min_version: MinVersion, keep_mock: bool = False, ) -> str: try: ast_obj = ast_parse(contents_text) except SyntaxError: return contents_text pep585_rewrite = ( min_version >= (3, 9) or _imports_future(contents_text, 'annotations') ) visitor = FindPy3Plus(min_version, keep_mock) visitor.visit(ast_obj) if not any(( visitor.bases_to_remove, visitor.encode_calls, visitor.if_py2_blocks_else, visitor.if_py3_blocks, visitor.if_py3_blocks_else, visitor.metaclass_type_assignments, visitor.native_literals, visitor.io_open_calls, visitor.open_mode_calls, visitor.mock_mock, visitor.mock_absolute_imports, visitor.mock_relative_imports, visitor.os_error_alias_calls, visitor.os_error_alias_simple, visitor.os_error_alias_excepts, visitor.no_arg_decorators, visitor.six_add_metaclass, visitor.six_b, visitor.six_calls, visitor.six_calls_int2byte, visitor.six_iter, visitor.six_raise_from, visitor.six_reraise, visitor.six_remove_decorators, visitor.six_simple, visitor.six_type_ctx, visitor.six_with_metaclass, visitor.super_calls, visitor.typing_builtin_renames, visitor.yield_from_fors, )): return contents_text try: tokens = src_to_tokens(contents_text) except tokenize.TokenError: # pragma: no cover (bpo-2180) return contents_text _fixup_dedent_tokens(tokens) def _replace(i: int, mapping: Dict[str, str], node: NameOrAttr) -> None: new_token = Token('CODE', _get_tmpl(mapping, node)) if isinstance(node, ast.Name): tokens[i] = new_token else: j = i while tokens[j].src != node.attr: # timid: if we see a parenthesis here, skip it if tokens[j].src == ')': return j += 1 tokens[i:j + 1] = [new_token] for i, token in reversed_enumerate(tokens): if not token.src: continue elif token.offset in visitor.bases_to_remove: _remove_base_class(tokens, i) elif token.offset in visitor.if_py3_blocks: if tokens[i].src == 'if': if_block = Block.find(tokens, i) if_block.dedent(tokens) del tokens[if_block.start:if_block.block] else: if_block = Block.find(tokens, _find_elif(tokens, i)) if_block.replace_condition(tokens, [Token('NAME', 'else')]) elif token.offset in visitor.if_py2_blocks_else: if tokens[i].src == 'if': if_block, else_block = _find_if_else_block(tokens, i) else_block.dedent(tokens) del tokens[if_block.start:else_block.block] else: j = _find_elif(tokens, i) if_block, else_block = _find_if_else_block(tokens, j) del tokens[if_block.start:else_block.start] elif token.offset in visitor.if_py3_blocks_else: if tokens[i].src == 'if': if_block, else_block = _find_if_else_block(tokens, i) if_block.dedent(tokens) del tokens[if_block.end:else_block.end] del tokens[if_block.start:if_block.block] else: j = _find_elif(tokens, i) if_block, else_block = _find_if_else_block(tokens, j) del tokens[if_block.end:else_block.end] if_block.replace_condition(tokens, [Token('NAME', 'else')]) elif token.offset in visitor.metaclass_type_assignments: j = _find_end(tokens, i) del tokens[i:j + 1] elif token.offset in visitor.native_literals: j = _find_open_paren(tokens, i) func_args, end = _parse_call_args(tokens, j) if any(tok.name == 'NL' for tok in tokens[i:end]): continue if func_args: _replace_call(tokens, i, end, func_args, '{args[0]}') else: tokens[i:end] = [token._replace(name='STRING', src="''")] elif token.offset in visitor.six_type_ctx: _replace(i, SIX_TYPE_CTX_ATTRS, visitor.six_type_ctx[token.offset]) elif token.offset in visitor.six_simple: _replace(i, SIX_SIMPLE_ATTRS, visitor.six_simple[token.offset]) elif token.offset in visitor.six_remove_decorators: _remove_decorator(tokens, i) elif token.offset in visitor.six_b: j = _find_open_paren(tokens, i) if ( tokens[j + 1].name == 'STRING' and _is_ascii(tokens[j + 1].src) and tokens[j + 2].src == ')' ): func_args, end = _parse_call_args(tokens, j) _replace_call(tokens, i, end, func_args, SIX_B_TMPL) elif token.offset in visitor.six_iter: j = _find_open_paren(tokens, i) func_args, end = _parse_call_args(tokens, j) call = visitor.six_iter[token.offset] assert isinstance(call.func, (ast.Name, ast.Attribute)) template = f'iter({_get_tmpl(SIX_CALLS, call.func)})' _replace_call(tokens, i, end, func_args, template) elif token.offset in visitor.six_calls: j = _find_open_paren(tokens, i) func_args, end = _parse_call_args(tokens, j) call = visitor.six_calls[token.offset] assert isinstance(call.func, (ast.Name, ast.Attribute)) template = _get_tmpl(SIX_CALLS, call.func) if isinstance(call.args[0], _EXPR_NEEDS_PARENS): _replace_call(tokens, i, end, func_args, template, parens=(0,)) else: _replace_call(tokens, i, end, func_args, template) elif token.offset in visitor.six_calls_int2byte: j = _find_open_paren(tokens, i) func_args, end = _parse_call_args(tokens, j) _replace_call(tokens, i, end, func_args, SIX_INT2BYTE_TMPL) elif token.offset in visitor.six_raise_from: j = _find_open_paren(tokens, i) func_args, end = _parse_call_args(tokens, j) _replace_call(tokens, i, end, func_args, RAISE_FROM_TMPL) elif token.offset in visitor.six_reraise: j = _find_open_paren(tokens, i) func_args, end = _parse_call_args(tokens, j) if len(func_args) == 1: tmpl = RERAISE_TMPL elif len(func_args) == 2: tmpl = RERAISE_2_TMPL else: tmpl = RERAISE_3_TMPL _replace_call(tokens, i, end, func_args, tmpl) elif token.offset in visitor.six_add_metaclass: j = _find_open_paren(tokens, i) func_args, end = _parse_call_args(tokens, j) metaclass = f'metaclass={_arg_str(tokens, *func_args[0])}' # insert `metaclass={args[0]}` into `class:` # search forward for the `class` token j = i + 1 while tokens[j].src != 'class': j += 1 class_token = j # then search forward for a `:` token, not inside a brace j = _find_block_start(tokens, j) last_paren = -1 for k in range(class_token, j): if tokens[k].src == ')': last_paren = k if last_paren == -1: tokens.insert(j, Token('CODE', f'({metaclass})')) else: insert = last_paren - 1 while tokens[insert].name in NON_CODING_TOKENS: insert -= 1 if tokens[insert].src == '(': # no bases src = metaclass elif tokens[insert].src != ',': src = f', {metaclass}' else: src = f' {metaclass},' tokens.insert(insert + 1, Token('CODE', src)) _remove_decorator(tokens, i) elif token.offset in visitor.six_with_metaclass: j = _find_open_paren(tokens, i) func_args, end = _parse_call_args(tokens, j) if len(func_args) == 1: tmpl = WITH_METACLASS_NO_BASES_TMPL elif len(func_args) == 2: base = _arg_str(tokens, *func_args[1]) if base == 'object': tmpl = WITH_METACLASS_NO_BASES_TMPL else: tmpl = WITH_METACLASS_BASES_TMPL else: tmpl = WITH_METACLASS_BASES_TMPL _replace_call(tokens, i, end, func_args, tmpl) elif pep585_rewrite and token.offset in visitor.typing_builtin_renames: node = visitor.typing_builtin_renames[token.offset] _replace(i, PEP585_BUILTINS, node) elif token.offset in visitor.super_calls: i = _find_open_paren(tokens, i) call = visitor.super_calls[token.offset] victims = _victims(tokens, i, call, gen=False) del tokens[victims.starts[0] + 1:victims.ends[-1]] elif token.offset in visitor.encode_calls: i = _find_open_paren(tokens, i + 1) call = visitor.encode_calls[token.offset] victims = _victims(tokens, i, call, gen=False) del tokens[victims.starts[0] + 1:victims.ends[-1]] elif token.offset in visitor.io_open_calls: j = _find_open_paren(tokens, i) tokens[i:j] = [token._replace(name='NAME', src='open')] elif token.offset in visitor.mock_mock: j = _find_token(tokens, i + 1, 'mock') del tokens[i + 1:j + 1] elif token.offset in visitor.mock_absolute_imports: j = _find_token(tokens, i, 'mock') if ( j + 2 < len(tokens) and tokens[j + 1].src == '.' and tokens[j + 2].src == 'mock' ): j += 2 src = 'from unittest import mock' tokens[i:j + 1] = [tokens[j]._replace(name='NAME', src=src)] elif token.offset in visitor.mock_relative_imports: j = _find_token(tokens, i, 'mock') if ( j + 2 < len(tokens) and tokens[j + 1].src == '.' and tokens[j + 2].src == 'mock' ): k = j + 2 else: k = j src = 'unittest.mock' tokens[j:k + 1] = [tokens[j]._replace(name='NAME', src=src)] elif token.offset in visitor.open_mode_calls: j = _find_open_paren(tokens, i) func_args, end = _parse_call_args(tokens, j) mode = tokens_to_src(tokens[slice(*func_args[1])]) mode_stripped = mode.strip().strip('"\'') if mode_stripped in U_MODE_REMOVE: del tokens[func_args[0][1]:func_args[1][1]] elif mode_stripped in U_MODE_REPLACE_R: new_mode = mode.replace('U', 'r') tokens[slice(*func_args[1])] = [Token('SRC', new_mode)] elif mode_stripped in U_MODE_REMOVE_U: new_mode = mode.replace('U', '') tokens[slice(*func_args[1])] = [Token('SRC', new_mode)] else: raise AssertionError(f'unreachable: {mode!r}') elif token.offset in visitor.os_error_alias_calls: j = _find_open_paren(tokens, i) tokens[i:j] = [token._replace(name='NAME', src='OSError')] elif token.offset in visitor.os_error_alias_simple: node = visitor.os_error_alias_simple[token.offset] _replace(i, collections.defaultdict(lambda: 'OSError'), node) elif token.offset in visitor.os_error_alias_excepts: line, utf8_byte_offset = token.line, token.utf8_byte_offset # find all the arg strs in the tuple except_index = i while tokens[except_index].src != 'except': except_index -= 1 start = _find_open_paren(tokens, except_index) func_args, end = _parse_call_args(tokens, start) # save the exceptions and remove the block arg_strs = [_arg_str(tokens, *arg) for arg in func_args] del tokens[start:end] # rewrite the block without dupes args = [] for arg in arg_strs: left, part, right = arg.partition('.') if ( left in visitor.OS_ERROR_ALIAS_MODULES and part == '.' and right == 'error' ): args.append('OSError') elif ( left in visitor.OS_ERROR_ALIASES and part == right == '' ): args.append('OSError') elif ( left == 'error' and part == right == '' and ( 'error' in visitor._from_imports['mmap'] or 'error' in visitor._from_imports['select'] or 'error' in visitor._from_imports['socket'] ) ): args.append('OSError') else: args.append(arg) unique_args = tuple(collections.OrderedDict.fromkeys(args)) if len(unique_args) > 1: joined = '({})'.format(', '.join(unique_args)) elif tokens[start - 1].name != 'UNIMPORTANT_WS': joined = ' {}'.format(unique_args[0]) else: joined = unique_args[0] new = Token('CODE', joined, line, utf8_byte_offset) tokens.insert(start, new) visitor.os_error_alias_excepts.discard(token.offset) elif token.offset in visitor.yield_from_fors: _replace_yield(tokens, i) elif ( min_version >= (3, 8) and token.offset in visitor.no_arg_decorators ): i = _find_open_paren(tokens, i) j = _find_token(tokens, i, ')') del tokens[i:j + 1] return tokens_to_src(tokens) def _simple_arg(arg: ast.expr) -> bool: return ( isinstance(arg, ast.Name) or (isinstance(arg, ast.Attribute) and _simple_arg(arg.value)) or ( isinstance(arg, ast.Call) and _simple_arg(arg.func) and not arg.args and not arg.keywords ) ) def _starargs(call: ast.Call) -> bool: return ( any(k.arg is None for k in call.keywords) or any(isinstance(a, ast.Starred) for a in call.args) ) def _format_params(call: ast.Call) -> Dict[str, str]: params = {} for i, arg in enumerate(call.args): params[str(i)] = _unparse(arg) for kwd in call.keywords: # kwd.arg can't be None here because we exclude starargs assert kwd.arg is not None params[kwd.arg] = _unparse(kwd.value) return params class FindPy36Plus(ast.NodeVisitor): def __init__(self) -> None: self.fstrings: Dict[Offset, ast.Call] = {} self.named_tuples: Dict[Offset, ast.Call] = {} self.dict_typed_dicts: Dict[Offset, ast.Call] = {} self.kw_typed_dicts: Dict[Offset, ast.Call] = {} self._from_imports: Dict[str, Set[str]] = collections.defaultdict(set) def visit_ImportFrom(self, node: ast.ImportFrom) -> None: if node.level == 0 and node.module in {'typing', 'typing_extensions'}: for name in node.names: if not name.asname: self._from_imports[node.module].add(name.name) self.generic_visit(node) def _is_attr(self, node: ast.AST, mods: Set[str], name: str) -> bool: return ( ( isinstance(node, ast.Name) and node.id == name and any(name in self._from_imports[mod] for mod in mods) ) or ( isinstance(node, ast.Attribute) and node.attr == name and isinstance(node.value, ast.Name) and node.value.id in mods ) ) def _parse(self, node: ast.Call) -> Optional[Tuple[DotFormatPart, ...]]: if not ( isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Str) and node.func.attr == 'format' and all(_simple_arg(arg) for arg in node.args) and all(_simple_arg(k.value) for k in node.keywords) and not _starargs(node) ): return None try: return parse_format(node.func.value.s) except ValueError: return None def visit_Call(self, node: ast.Call) -> None: parsed = self._parse(node) if parsed is not None: params = _format_params(node) seen: Set[str] = set() i = 0 for _, name, spec, _ in parsed: # timid: difficult to rewrite correctly if spec is not None and '{' in spec: break if name is not None: candidate, _, _ = name.partition('.') # timid: could make the f-string longer if candidate and candidate in seen: break # timid: bracketed elif '[' in name: break seen.add(candidate) key = candidate or str(i) # their .format() call is broken currently if key not in params: break if not candidate: i += 1 else: self.fstrings[_ast_to_offset(node)] = node self.generic_visit(node) def visit_Assign(self, node: ast.Assign) -> None: if ( # NT = ...("NT", ...) len(node.targets) == 1 and isinstance(node.targets[0], ast.Name) and isinstance(node.value, ast.Call) and len(node.value.args) >= 1 and isinstance(node.value.args[0], ast.Str) and node.targets[0].id == node.value.args[0].s and not _starargs(node.value) ): if ( self._is_attr( node.value.func, {'typing'}, 'NamedTuple', ) and len(node.value.args) == 2 and not node.value.keywords and isinstance(node.value.args[1], (ast.List, ast.Tuple)) and len(node.value.args[1].elts) > 0 and all( isinstance(tup, ast.Tuple) and len(tup.elts) == 2 and isinstance(tup.elts[0], ast.Str) and tup.elts[0].s.isidentifier() and tup.elts[0].s not in _KEYWORDS for tup in node.value.args[1].elts ) ): self.named_tuples[_ast_to_offset(node)] = node.value elif ( self._is_attr( node.value.func, {'typing', 'typing_extensions'}, 'TypedDict', ) and len(node.value.args) == 1 and len(node.value.keywords) > 0 ): self.kw_typed_dicts[_ast_to_offset(node)] = node.value elif ( self._is_attr( node.value.func, {'typing', 'typing_extensions'}, 'TypedDict', ) and len(node.value.args) == 2 and not node.value.keywords and isinstance(node.value.args[1], ast.Dict) and node.value.args[1].keys and all( isinstance(k, ast.Str) and k.s.isidentifier() and k.s not in _KEYWORDS for k in node.value.args[1].keys ) ): self.dict_typed_dicts[_ast_to_offset(node)] = node.value self.generic_visit(node) def _unparse(node: ast.expr) -> str: if isinstance(node, ast.Name): return node.id elif isinstance(node, ast.Attribute): return ''.join((_unparse(node.value), '.', node.attr)) elif isinstance(node, ast.Call): return '{}()'.format(_unparse(node.func)) elif isinstance(node, ast.Subscript): if sys.version_info >= (3, 9): # pragma: no cover (py39+) node_slice: ast.expr = node.slice elif isinstance(node.slice, ast.Index): # pragma: no cover (<py39) node_slice = node.slice.value else: raise AssertionError(f'expected Slice: {ast.dump(node)}') if isinstance(node_slice, ast.Tuple): if len(node_slice.elts) == 1: slice_s = f'{_unparse(node_slice.elts[0])},' else: slice_s = ', '.join(_unparse(elt) for elt in node_slice.elts) else: slice_s = _unparse(node_slice) return '{}[{}]'.format(_unparse(node.value), slice_s) elif isinstance(node, ast.Str): return repr(node.s) elif isinstance(node, ast.Ellipsis): return '...' elif isinstance(node, ast.List): return '[{}]'.format(', '.join(_unparse(elt) for elt in node.elts)) elif isinstance(node, ast.NameConstant): return repr(node.value) else: raise NotImplementedError(ast.dump(node)) def _to_fstring(src: str, call: ast.Call) -> str: params = _format_params(call) parts = [] i = 0 for s, name, spec, conv in parse_format('f' + src): if name is not None: k, dot, rest = name.partition('.') name = ''.join((params[k or str(i)], dot, rest)) if not k: # named and auto params can be in different orders i += 1 parts.append((s, name, spec, conv)) return unparse_parsed_string(parts) def _replace_typed_class( tokens: List[Token], i: int, call: ast.Call, types: Dict[str, ast.expr], ) -> None: if i > 0 and tokens[i - 1].name in {'INDENT', UNIMPORTANT_WS}: indent = f'{tokens[i - 1].src}{" " * 4}' else: indent = ' ' * 4 # NT = NamedTuple("nt", [("a", int)]) # ^i ^end end = i + 1 while end < len(tokens) and tokens[end].name != 'NEWLINE': end += 1 attrs = '\n'.join(f'{indent}{k}: {_unparse(v)}' for k, v in types.items()) src = f'class {tokens[i].src}({_unparse(call.func)}):\n{attrs}' tokens[i:end] = [Token('CODE', src)] def _fix_py36_plus(contents_text: str) -> str: try: ast_obj = ast_parse(contents_text) except SyntaxError: return contents_text visitor = FindPy36Plus() visitor.visit(ast_obj) if not any(( visitor.fstrings, visitor.named_tuples, visitor.dict_typed_dicts, visitor.kw_typed_dicts, )): return contents_text try: tokens = src_to_tokens(contents_text) except tokenize.TokenError: # pragma: no cover (bpo-2180) return contents_text for i, token in reversed_enumerate(tokens): if token.offset in visitor.fstrings: node = visitor.fstrings[token.offset] # TODO: handle \N escape sequences if r'\N' in token.src: continue paren = i + 3 if tokens_to_src(tokens[i + 1:paren + 1]) != '.format(': continue # we don't actually care about arg position, so we pass `node` victims = _victims(tokens, paren, node, gen=False) end = victims.ends[-1] # if it spans more than one line, bail if tokens[end].line != token.line: continue tokens[i] = token._replace(src=_to_fstring(token.src, node)) del tokens[i + 1:end + 1] elif token.offset in visitor.named_tuples and token.name == 'NAME': call = visitor.named_tuples[token.offset] types: Dict[str, ast.expr] = { tup.elts[0].s: tup.elts[1] # type: ignore # (checked above) for tup in call.args[1].elts # type: ignore # (checked above) } _replace_typed_class(tokens, i, call, types) elif token.offset in visitor.kw_typed_dicts and token.name == 'NAME': call = visitor.kw_typed_dicts[token.offset] types = { arg.arg: arg.value # type: ignore # (checked above) for arg in call.keywords } _replace_typed_class(tokens, i, call, types) elif token.offset in visitor.dict_typed_dicts and token.name == 'NAME': call = visitor.dict_typed_dicts[token.offset] types = { k.s: v # type: ignore # (checked above) for k, v in zip( call.args[1].keys, # type: ignore # (checked above) call.args[1].values, # type: ignore # (checked above) ) } _replace_typed_class(tokens, i, call, types) return tokens_to_src(tokens) def _fix_file(filename: str, args: argparse.Namespace) -> int: if filename == '-': contents_bytes = sys.stdin.buffer.read() else: with open(filename, 'rb') as fb: contents_bytes = fb.read() try: contents_text_orig = contents_text = contents_bytes.decode() except UnicodeDecodeError: print(f'{filename} is non-utf-8 (not supported)') return 1 contents_text = _fix_py2_compatible(contents_text) contents_text = _fix_tokens(contents_text, min_version=args.min_version) if not args.keep_percent_format: contents_text = _fix_percent_format(contents_text) if args.min_version >= (3,): contents_text = _fix_py3_plus( contents_text, args.min_version, args.keep_mock, ) if args.min_version >= (3, 6): contents_text = _fix_py36_plus(contents_text) if filename == '-': print(contents_text, end='') elif contents_text != contents_text_orig: print(f'Rewriting {filename}', file=sys.stderr) with open(filename, 'w', encoding='UTF-8', newline='') as f: f.write(contents_text) if args.exit_zero_even_if_changed: return 0 else: return contents_text != contents_text_orig def main(argv: Optional[Sequence[str]] = None) -> int: parser = argparse.ArgumentParser() parser.add_argument('filenames', nargs='*') parser.add_argument('--exit-zero-even-if-changed', action='store_true') parser.add_argument('--keep-percent-format', action='store_true') parser.add_argument('--keep-mock', action='store_true') parser.add_argument( '--py3-plus', '--py3-only', action='store_const', dest='min_version', default=(2, 7), const=(3,), ) parser.add_argument( '--py36-plus', action='store_const', dest='min_version', const=(3, 6), ) parser.add_argument( '--py37-plus', action='store_const', dest='min_version', const=(3, 7), ) parser.add_argument( '--py38-plus', action='store_const', dest='min_version', const=(3, 8), ) parser.add_argument( '--py39-plus', action='store_const', dest='min_version', const=(3, 9), ) args = parser.parse_args(argv) ret = 0 for filename in args.filenames: ret |= _fix_file(filename, args) return ret if __name__ == '__main__': exit(main())
import argparse import ast from datetime import datetime import json import matplotlib.pyplot as plt import numpy as np import os import time from typing import Optional, Dict, Union, List from warnings import warn from experiment.experiment_utils import get_args_string import snc from snc.agents.hedgehog.hh_agents.big_step_hedgehog_agent import BigStepHedgehogAgent from snc.agents.hedgehog.hh_agents.pure_feedback_mip_hedgehog_agent \ import PureFeedbackMIPHedgehogAgent from snc.agents.hedgehog.hh_agents.pure_feedback_stationary_hedgehog_agent \ import PureFeedbackStationaryHedgehogAgent import snc.agents.hedgehog.minimal_draining_time as mdt import snc.environments.scenarios as scenarios import snc.simulation.snc_simulator as ps from snc.simulation.store_data.json_logging import set_up_json_logging import snc.simulation.store_data.reporter as rep from snc.simulation.utils import load_agents import snc.simulation.utils.validation_utils as validation_utils from snc.utils.snc_tools import is_routing_network set_up_json_logging() def run_policy(policy_simulator: ps.SncSimulator, num_simulation_steps: int, server_mode: bool, is_hedgehog: bool, save_location: str, job_gen_seed: Optional[int] = None): """ Run a policy simulator, with a reporter, saving the result in given location. :param policy_simulator: the policy simulator object. :param num_simulation_steps: the number of steps the simulation runs. :param server_mode: when experiment runs locally, this flag controls whether to show live plots and wait for input before closing them at the end of the simulation. :param is_hedgehog: whether the policy simulator object is hedgehog specifically. :param save_location: what to name the data when it is saved in logs directory. :param job_gen_seed: Job generator random seed. :return: Run results - a dictionary including data on cost, state and action processes. """ env = policy_simulator.env initial_state = env.state time_interval = env.job_generator.sim_time_interval min_draining_time = mdt.compute_minimal_draining_time_from_env_cvxpy(initial_state, env) print(f"Minimal draining time: {min_draining_time}\n" f"Minimal draining simulation steps: {min_draining_time * time_interval}") plot_freq = 100 is_routing = is_routing_network(env) handlers = validation_utils.get_handlers(server_mode, num_simulation_steps, plot_freq, time_interval, is_hedgehog, is_routing) reporter = rep.Reporter(handlers=handlers) return policy_simulator.run(num_simulation_steps, reporter, save_location, job_gen_seed) def run_validation(arguments: argparse.Namespace) -> Dict[str, str]: """ Run the validation on a particular scenario. :param arguments: Namespace of experiment parameters. """ assert arguments.env_param_overrides['job_gen_seed'] is not None assert arguments.seed is not None # Note that if job_gen_seed was not in env_param_overrides, then at this point we will have: # arguments.env_param_overrides['job_gen_seed'] == arguments.seed. job_gen_seed = arguments.env_param_overrides['job_gen_seed'] global_seed = arguments.seed + 100 agent_seed = arguments.seed + 200 mpc_seed = arguments.seed + 300 np.random.seed(global_seed) print(f"job_gen_seed {job_gen_seed}") print(f"global_seed {global_seed}") print(f"agent_seed {agent_seed}") print(f"mpc_seed {mpc_seed}") save_locations = dict() # Get Scenario _, env = scenarios.load_scenario( arguments.env_name, job_gen_seed, arguments.env_param_overrides) # Initialise an agent counter to ensure that the right checkpoint is loaded for each agent. rl_agent_count = 0 for agent_name in arguments.agents: env.reset_with_random_state(job_gen_seed) agent_args = {} name_alias = agent_name # Set name of folder storing results to agent_name by default. if agent_name in load_agents.HEDGEHOG_AGENTS: if arguments.hedgehog_param_overrides is None: arguments.hedgehog_param_overrides = dict() agent_args['hh_overrides'] = arguments.hedgehog_param_overrides agent_args['discount_factor'] = arguments.discount_factor agent_args['debug_info'] = arguments.debug_info agent_args['agent_seed'] = agent_seed agent_args['mpc_seed'] = mpc_seed # Replace directory name if name passed as an agent parameter. name_alias = arguments.hedgehog_param_overrides.get('name', agent_name) elif agent_name == 'distribution_with_rebalancing_heuristic': agent_args['safety_stocks'] = 20 * np.ones(env.state.shape) elif agent_name in ['reinforce', 'ppo']: agent_args['discount_factor'] = arguments.discount_factor if arguments.rl_agent_params: # Update agent_args accordingly. if rl_agent_count < len(arguments.rl_agent_params): if 'discount_factor' in arguments.rl_agent_params[rl_agent_count]: warn('WARNING: Overriding provided discount factor with agent specific ' 'discount factor for {agent_name} agent') agent_args.update(arguments.rl_agent_params[rl_agent_count]) else: if agent_name == "ppo": raise ValueError("When running a PPO agent you must provide agent parameters.") else: warn("REINFORCE agent being run default agent parameters.") agent_args['rl_checkpoint'] = arguments.rl_checkpoints[rl_agent_count] rl_agent_count += 1 elif agent_name == 'maxweight' or agent_name == 'scheduling_maxweight': if arguments.maxweight_param_overrides is None: arguments.maxweight_param_overrides = dict() agent_args['overrides'] = arguments.maxweight_param_overrides agent_args['agent_seed'] = agent_seed agent_args['mpc_seed'] = mpc_seed # Replace directory name if name passed as an agent parameter. name_alias = arguments.maxweight_param_overrides.get('name', agent_name) else: agent_args['agent_seed'] = agent_seed agent = load_agents.get_agent(agent_name, env, **agent_args) sim = ps.SncSimulator(env, agent, **arguments.__dict__) print(f'\nSimulating {agent.name}...') validation_utils.print_agent_params(agent) is_hedgehog = isinstance(agent, (BigStepHedgehogAgent, PureFeedbackStationaryHedgehogAgent, PureFeedbackMIPHedgehogAgent)) save_location = f'{arguments.logdir}/{name_alias}' run_policy(sim, arguments.num_steps, arguments.server_mode, is_hedgehog, save_location, job_gen_seed) if is_hedgehog: assert isinstance(agent, (BigStepHedgehogAgent, PureFeedbackStationaryHedgehogAgent, PureFeedbackMIPHedgehogAgent)) validation_utils.print_workload_to_physical_resources_indexes(agent.workload_tuple.nu) save_locations[agent.name] = save_location print(f'Data stored at: {save_location}.') print(f'Finished simulating {agent.name}.\n') print(f"job_gen_seed: {arguments.env_param_overrides.get("job_gen_seed")}") print("End of simulation!") if not arguments.server_mode: plt.ioff() plt.show() return save_locations def parse_args() -> argparse.Namespace: """Processes command line arguments and collects them in the named tuple returned·""" params = argparse.ArgumentParser(description="Experiment Arguments.") params.add_argument("--env_name", type=str, default="simple_reentrant_line", help="Name of environment to run on." "Must be in the list of implemented scenarios.") params.add_argument("--agents", type=str, default='all', help='whitespace separated list of agents to run.' 'Also accepts special case of "all" which runs all known agents.') params.add_argument("-ns", "--num_steps", type=int, default=2500, help="Number of simulation steps.") params.add_argument("-ep", "--env_param_overrides", type=str, default='{}', help="JSON formatted dictionary of environment parameter overrides. " "May be a string or a path to a JSON file.") params.add_argument("--rl_agent_params", type=str, default=None, help="JSON formatted list of dictionaries of agent parameters. " "One dictionary per RL agent to be run. " "If a single RL agent is run this may be a single dictionary or" "JSON file.") params.add_argument("-hhp", "--hedgehog_param_overrides", type=str, default='{}', help="JSON formatted dictionary of Hedgehog parameter overrides. " "May be a string or a path to a JSON file.") params.add_argument("-mwp", "--maxweight_param_overrides", type=str, default='{}', help="JSON formatted dictionary of MaxWeight parameter overrides. " "May be a string or a path to a JSON file.") params.add_argument("-df", "--discount_factor", type=float, default=0.999999, help="Discount factor applied to future rewards.") params.add_argument("--logdir", type=str, default=os.path.join( os.path.dirname(snc.__file__), 'logs')) params.add_argument("--rl_checkpoints", type=str, default=None, help="A list of paths to a directories where the TensorFlow model weights " "are saved. These should be ordered in a corresponding order to the " "agents in the agents list. If using --agents all then REINFORCE " "precedes PPO.") params.add_argument("--seed", type=int, default=42, help="Random seed.") params.add_argument("--server_mode", action="store_true", help="Neither show live plots nor ask for input before closing them at the " "end of the simulation. If simulation runs in art, this parameter is " "set to True independent on this argument.") params.add_argument("--debug_info", action="store_true", help="Print debug information while running.") # Collect the parameters in a namespace. parsed_params = params.parse_args() parsed_params = process_parsed_args(parsed_params) return parsed_params def process_parsed_args(parsed_params: argparse.Namespace) -> argparse.Namespace: assert parsed_params.env_name in scenarios.SCENARIO_CONSTRUCTORS, \ "Scenario passed does not exist." if parsed_params.rl_checkpoints: # Cast the string to a list. parsed_params.rl_checkpoints = ast.literal_eval(parsed_params.rl_checkpoints) for ckpt in parsed_params.rl_checkpoints: assert os.path.exists(ckpt), \ f'RL parameter folder {ckpt} not found.' if parsed_params.agents.lower() == 'all': # Only include RL agents if model weights supplied. with_rl_agent = bool(parsed_params.rl_checkpoints) if with_rl_agent: assert len(parsed_params.rl_checkpoints) == load_agents.NUM_RL_AGENTS, \ "The number of agent checkpoints provided does not match the number of RL agents." else: warn("No reinforcement learning agents will be run as no load checkpoints provided.") parsed_params.agents = load_agents.get_all_agent_names(parsed_params.env_name, with_rl_agent) else: parsed_params.agents = [a.strip() for a in parsed_params.agents.split()] # Set the logging folder from the load automatically. now = datetime.now() time_stamp_for_logs = datetime.strftime(now, "%y_%m_%d_%H%M%S.%f") parsed_params.logdir = os.path.join(parsed_params.logdir, time_stamp_for_logs) # We want to make sure that the seed is not None if parsed_params.seed is None: parsed_params.seed = int(time.time()) if parsed_params.env_param_overrides: parsed_params.env_param_overrides = process_environment_parameters( parsed_params.env_param_overrides, parsed_params.seed) if parsed_params.rl_agent_params: rl_agent_params = process_agent_parameters(parsed_params.rl_agent_params) parsed_params.rl_agent_params = post_process_rl_agent_params(rl_agent_params, parsed_params.agents) if parsed_params.hedgehog_param_overrides: hh_agent_params = process_agent_parameters(parsed_params.hedgehog_param_overrides) parsed_params.hedgehog_param_overrides = cast_overrides_to_numpy_arrays(hh_agent_params) if parsed_params.maxweight_param_overrides: mw_agent_params = process_agent_parameters(parsed_params.maxweight_param_overrides) parsed_params.maxweight_param_overrides = cast_overrides_to_numpy_arrays(mw_agent_params) if not os.path.isdir(parsed_params.logdir): os.makedirs(parsed_params.logdir) with open(os.path.join(parsed_params.logdir, 'validation_params.txt'), 'w') as param_file: param_file.write(get_args_string(parsed_params)) return parsed_params def process_environment_parameters(env_param_overrides: str, seed: int) \ -> Dict[str, Union[float, List, np.ndarray]]: """ Returns updated environment parameter from a JSON file or a string of a dictionary. :param env_param_overrides: The namespace to be updated. :param seed: General random number generator seed. :return: env_param_overrides: Dictionary containing updated environment np.ndarray. """ # Support environment parameters passed as a path to a JSON file or as a string of a dictionary. if os.path.exists(env_param_overrides): with open(env_param_overrides, 'r') as json_file: env_param_overrides_json = json.load(json_file) else: env_param_overrides_json = json.loads(env_param_overrides) # We are always going to use the seed set here and not the one in environment parameters if 'job_gen_seed' in env_param_overrides_json: assert env_param_overrides_json["job_gen_seed"] is not None if env_param_overrides_json["job_gen_seed"] != seed: warn("Seed for environment job generator differs from general random seed ") else: env_param_overrides_json['job_gen_seed'] = seed env_param_overrides_updated = cast_overrides_to_numpy_arrays(env_param_overrides_json) return env_param_overrides_updated def cast_overrides_to_numpy_arrays(param_overrides: Dict[str, Union[float, List]]) \ -> Dict[str, Union[float, List, np.ndarray]]: """ All list type objects will be cast to numpy arrays before passing. This is needed for the current implementation of ControlledRandomWalk environments. :param param_overrides: Dictionary of parameters. :return: new_param_overrides: Dictionary similar to param_overrides, but with list values replaced with numpy arrays. """ new_param_overrides: Dict[str, Union[float, List, np.ndarray]] = dict() for p in param_overrides: if isinstance(param_overrides[p], list): new_param_overrides[p] = np.array(param_overrides[p]) else: new_param_overrides[p] = param_overrides[p] return new_param_overrides def process_agent_parameters(agent_params: str) -> Dict[str, Union[float, List]]: """ Process agents params. Note that this function purposely mutates params causing side effects. :param agent_params: Agent parameters to be processed passed as a file path, or as a dictionary, or as a list of dictionaries. :return: agent_params: """ # Load agent parameters considering several cases. # If simply a file path is provided. if os.path.exists(agent_params): with open(agent_params, 'r') as json_file: agent_params_data = json.load(json_file) else: # If a dictionary or list of dictionaries and/or file paths is provided first attain the # list. try: agent_params_data = ast.literal_eval(agent_params) except SyntaxError: raise ValueError('Argument is invalid. Possibly file doesnt exist. Value passed was ' f'{agent_params}') # Handle the case of a list for multiple (or even a single) agents. if isinstance(agent_params_data, list): for i, entry in enumerate(agent_params_data): if not isinstance(entry, dict): assert isinstance(entry, str) and os.path.exists(entry), \ "JSON file for agent parameters not found." with open(entry, 'r') as json_file: agent_params_data[i] = json.load(json_file) else: assert isinstance(entry, dict), "If not passing a JSON file of agent " \ "parameters you must pass a dictionary " \ "(JSON string)." else: # Users may pass a single dictionary of agent parameters when running a single RL agent. assert isinstance(agent_params_data, dict), "If not passing a JSON file of agent " \ "parameters you must pass a dictionary " \ "(JSON string)." return agent_params_data def post_process_rl_agent_params(agent_params: Union[Dict, List[Dict]], agent_names: List[str]) \ -> List[Dict[str, Union[float, List]]]: """ If we have parsed parameters for multiple RL agents, this function checks that the list of parameters has as many items as the list of RL agents (currently only checks for 'ppo' and 'reinforce' names). Otherwise, if we have parsed parameters for a single RL agent, it wraps the parameters with a list. :param agent_params: Dictionary or list of dictionaries with the parsed parameters for the RL agents. :param agent_names: List of parsed names of agents. :return: List of dictionaries with the parsed parameters for all the RL agents, even if there is only one. """ if isinstance(agent_params, list): assert len(agent_params) == agent_names.count('ppo') \ + agent_names.count('reinforce'), "The number of agent parameter sets provided " \ "for RL agents does not match the number of RL " \ "agents to run." else: assert agent_names.count('ppo') + agent_names.count('reinforce') == 1, \ "Users may only pass a dictionary of RL agent parameters when there a single RL " \ "agent is being validated." agent_params = [agent_params] return agent_params if __name__ == '__main__': # Simply get the arguments and run main. args = parse_args() run_validation(args)
import argparse import ast from datetime import datetime import json import matplotlib.pyplot as plt import numpy as np import os import time from typing import Optional, Dict, Union, List from warnings import warn from experiment.experiment_utils import get_args_string import snc from snc.agents.hedgehog.hh_agents.big_step_hedgehog_agent import BigStepHedgehogAgent from snc.agents.hedgehog.hh_agents.pure_feedback_mip_hedgehog_agent \ import PureFeedbackMIPHedgehogAgent from snc.agents.hedgehog.hh_agents.pure_feedback_stationary_hedgehog_agent \ import PureFeedbackStationaryHedgehogAgent import snc.agents.hedgehog.minimal_draining_time as mdt import snc.environments.scenarios as scenarios import snc.simulation.snc_simulator as ps from snc.simulation.store_data.json_logging import set_up_json_logging import snc.simulation.store_data.reporter as rep from snc.simulation.utils import load_agents import snc.simulation.utils.validation_utils as validation_utils from snc.utils.snc_tools import is_routing_network set_up_json_logging() def run_policy(policy_simulator: ps.SncSimulator, num_simulation_steps: int, server_mode: bool, is_hedgehog: bool, save_location: str, job_gen_seed: Optional[int] = None): """ Run a policy simulator, with a reporter, saving the result in given location. :param policy_simulator: the policy simulator object. :param num_simulation_steps: the number of steps the simulation runs. :param server_mode: when experiment runs locally, this flag controls whether to show live plots and wait for input before closing them at the end of the simulation. :param is_hedgehog: whether the policy simulator object is hedgehog specifically. :param save_location: what to name the data when it is saved in logs directory. :param job_gen_seed: Job generator random seed. :return: Run results - a dictionary including data on cost, state and action processes. """ env = policy_simulator.env initial_state = env.state time_interval = env.job_generator.sim_time_interval min_draining_time = mdt.compute_minimal_draining_time_from_env_cvxpy(initial_state, env) print(f"Minimal draining time: {min_draining_time}\n" f"Minimal draining simulation steps: {min_draining_time * time_interval}") plot_freq = 100 is_routing = is_routing_network(env) handlers = validation_utils.get_handlers(server_mode, num_simulation_steps, plot_freq, time_interval, is_hedgehog, is_routing) reporter = rep.Reporter(handlers=handlers) return policy_simulator.run(num_simulation_steps, reporter, save_location, job_gen_seed) def run_validation(arguments: argparse.Namespace) -> Dict[str, str]: """ Run the validation on a particular scenario. :param arguments: Namespace of experiment parameters. """ assert arguments.env_param_overrides['job_gen_seed'] is not None assert arguments.seed is not None # Note that if job_gen_seed was not in env_param_overrides, then at this point we will have: # arguments.env_param_overrides['job_gen_seed'] == arguments.seed. job_gen_seed = arguments.env_param_overrides['job_gen_seed'] global_seed = arguments.seed + 100 agent_seed = arguments.seed + 200 mpc_seed = arguments.seed + 300 np.random.seed(global_seed) print(f"job_gen_seed {job_gen_seed}") print(f"global_seed {global_seed}") print(f"agent_seed {agent_seed}") print(f"mpc_seed {mpc_seed}") save_locations = dict() # Get Scenario _, env = scenarios.load_scenario( arguments.env_name, job_gen_seed, arguments.env_param_overrides) # Initialise an agent counter to ensure that the right checkpoint is loaded for each agent. rl_agent_count = 0 for agent_name in arguments.agents: env.reset_with_random_state(job_gen_seed) agent_args = {} name_alias = agent_name # Set name of folder storing results to agent_name by default. if agent_name in load_agents.HEDGEHOG_AGENTS: if arguments.hedgehog_param_overrides is None: arguments.hedgehog_param_overrides = dict() agent_args['hh_overrides'] = arguments.hedgehog_param_overrides agent_args['discount_factor'] = arguments.discount_factor agent_args['debug_info'] = arguments.debug_info agent_args['agent_seed'] = agent_seed agent_args['mpc_seed'] = mpc_seed # Replace directory name if name passed as an agent parameter. name_alias = arguments.hedgehog_param_overrides.get('name', agent_name) elif agent_name == 'distribution_with_rebalancing_heuristic': agent_args['safety_stocks'] = 20 * np.ones(env.state.shape) elif agent_name in ['reinforce', 'ppo']: agent_args['discount_factor'] = arguments.discount_factor if arguments.rl_agent_params: # Update agent_args accordingly. if rl_agent_count < len(arguments.rl_agent_params): if 'discount_factor' in arguments.rl_agent_params[rl_agent_count]: warn('WARNING: Overriding provided discount factor with agent specific ' 'discount factor for {agent_name} agent') agent_args.update(arguments.rl_agent_params[rl_agent_count]) else: if agent_name == "ppo": raise ValueError("When running a PPO agent you must provide agent parameters.") else: warn("REINFORCE agent being run default agent parameters.") agent_args['rl_checkpoint'] = arguments.rl_checkpoints[rl_agent_count] rl_agent_count += 1 elif agent_name == 'maxweight' or agent_name == 'scheduling_maxweight': if arguments.maxweight_param_overrides is None: arguments.maxweight_param_overrides = dict() agent_args['overrides'] = arguments.maxweight_param_overrides agent_args['agent_seed'] = agent_seed agent_args['mpc_seed'] = mpc_seed # Replace directory name if name passed as an agent parameter. name_alias = arguments.maxweight_param_overrides.get('name', agent_name) else: agent_args['agent_seed'] = agent_seed agent = load_agents.get_agent(agent_name, env, **agent_args) sim = ps.SncSimulator(env, agent, **arguments.__dict__) print(f'\nSimulating {agent.name}...') validation_utils.print_agent_params(agent) is_hedgehog = isinstance(agent, (BigStepHedgehogAgent, PureFeedbackStationaryHedgehogAgent, PureFeedbackMIPHedgehogAgent)) save_location = f'{arguments.logdir}/{name_alias}' run_policy(sim, arguments.num_steps, arguments.server_mode, is_hedgehog, save_location, job_gen_seed) if is_hedgehog: assert isinstance(agent, (BigStepHedgehogAgent, PureFeedbackStationaryHedgehogAgent, PureFeedbackMIPHedgehogAgent)) validation_utils.print_workload_to_physical_resources_indexes(agent.workload_tuple.nu) save_locations[agent.name] = save_location print(f'Data stored at: {save_location}.') print(f'Finished simulating {agent.name}.\n') print(f"job_gen_seed: {arguments.env_param_overrides.get('job_gen_seed')}") print("End of simulation!") if not arguments.server_mode: plt.ioff() plt.show() return save_locations def parse_args() -> argparse.Namespace: """Processes command line arguments and collects them in the named tuple returned·""" params = argparse.ArgumentParser(description="Experiment Arguments.") params.add_argument("--env_name", type=str, default="simple_reentrant_line", help="Name of environment to run on." "Must be in the list of implemented scenarios.") params.add_argument("--agents", type=str, default='all', help='whitespace separated list of agents to run.' 'Also accepts special case of "all" which runs all known agents.') params.add_argument("-ns", "--num_steps", type=int, default=2500, help="Number of simulation steps.") params.add_argument("-ep", "--env_param_overrides", type=str, default='{}', help="JSON formatted dictionary of environment parameter overrides. " "May be a string or a path to a JSON file.") params.add_argument("--rl_agent_params", type=str, default=None, help="JSON formatted list of dictionaries of agent parameters. " "One dictionary per RL agent to be run. " "If a single RL agent is run this may be a single dictionary or" "JSON file.") params.add_argument("-hhp", "--hedgehog_param_overrides", type=str, default='{}', help="JSON formatted dictionary of Hedgehog parameter overrides. " "May be a string or a path to a JSON file.") params.add_argument("-mwp", "--maxweight_param_overrides", type=str, default='{}', help="JSON formatted dictionary of MaxWeight parameter overrides. " "May be a string or a path to a JSON file.") params.add_argument("-df", "--discount_factor", type=float, default=0.999999, help="Discount factor applied to future rewards.") params.add_argument("--logdir", type=str, default=os.path.join( os.path.dirname(snc.__file__), 'logs')) params.add_argument("--rl_checkpoints", type=str, default=None, help="A list of paths to a directories where the TensorFlow model weights " "are saved. These should be ordered in a corresponding order to the " "agents in the agents list. If using --agents all then REINFORCE " "precedes PPO.") params.add_argument("--seed", type=int, default=42, help="Random seed.") params.add_argument("--server_mode", action="store_true", help="Neither show live plots nor ask for input before closing them at the " "end of the simulation. If simulation runs in art, this parameter is " "set to True independent on this argument.") params.add_argument("--debug_info", action="store_true", help="Print debug information while running.") # Collect the parameters in a namespace. parsed_params = params.parse_args() parsed_params = process_parsed_args(parsed_params) return parsed_params def process_parsed_args(parsed_params: argparse.Namespace) -> argparse.Namespace: assert parsed_params.env_name in scenarios.SCENARIO_CONSTRUCTORS, \ "Scenario passed does not exist." if parsed_params.rl_checkpoints: # Cast the string to a list. parsed_params.rl_checkpoints = ast.literal_eval(parsed_params.rl_checkpoints) for ckpt in parsed_params.rl_checkpoints: assert os.path.exists(ckpt), \ f'RL parameter folder {ckpt} not found.' if parsed_params.agents.lower() == 'all': # Only include RL agents if model weights supplied. with_rl_agent = bool(parsed_params.rl_checkpoints) if with_rl_agent: assert len(parsed_params.rl_checkpoints) == load_agents.NUM_RL_AGENTS, \ "The number of agent checkpoints provided does not match the number of RL agents." else: warn("No reinforcement learning agents will be run as no load checkpoints provided.") parsed_params.agents = load_agents.get_all_agent_names(parsed_params.env_name, with_rl_agent) else: parsed_params.agents = [a.strip() for a in parsed_params.agents.split()] # Set the logging folder from the load automatically. now = datetime.now() time_stamp_for_logs = datetime.strftime(now, "%y_%m_%d_%H%M%S.%f") parsed_params.logdir = os.path.join(parsed_params.logdir, time_stamp_for_logs) # We want to make sure that the seed is not None if parsed_params.seed is None: parsed_params.seed = int(time.time()) if parsed_params.env_param_overrides: parsed_params.env_param_overrides = process_environment_parameters( parsed_params.env_param_overrides, parsed_params.seed) if parsed_params.rl_agent_params: rl_agent_params = process_agent_parameters(parsed_params.rl_agent_params) parsed_params.rl_agent_params = post_process_rl_agent_params(rl_agent_params, parsed_params.agents) if parsed_params.hedgehog_param_overrides: hh_agent_params = process_agent_parameters(parsed_params.hedgehog_param_overrides) parsed_params.hedgehog_param_overrides = cast_overrides_to_numpy_arrays(hh_agent_params) if parsed_params.maxweight_param_overrides: mw_agent_params = process_agent_parameters(parsed_params.maxweight_param_overrides) parsed_params.maxweight_param_overrides = cast_overrides_to_numpy_arrays(mw_agent_params) if not os.path.isdir(parsed_params.logdir): os.makedirs(parsed_params.logdir) with open(os.path.join(parsed_params.logdir, 'validation_params.txt'), 'w') as param_file: param_file.write(get_args_string(parsed_params)) return parsed_params def process_environment_parameters(env_param_overrides: str, seed: int) \ -> Dict[str, Union[float, List, np.ndarray]]: """ Returns updated environment parameter from a JSON file or a string of a dictionary. :param env_param_overrides: The namespace to be updated. :param seed: General random number generator seed. :return: env_param_overrides: Dictionary containing updated environment np.ndarray. """ # Support environment parameters passed as a path to a JSON file or as a string of a dictionary. if os.path.exists(env_param_overrides): with open(env_param_overrides, 'r') as json_file: env_param_overrides_json = json.load(json_file) else: env_param_overrides_json = json.loads(env_param_overrides) # We are always going to use the seed set here and not the one in environment parameters if 'job_gen_seed' in env_param_overrides_json: assert env_param_overrides_json["job_gen_seed"] is not None if env_param_overrides_json["job_gen_seed"] != seed: warn("Seed for environment job generator differs from general random seed ") else: env_param_overrides_json['job_gen_seed'] = seed env_param_overrides_updated = cast_overrides_to_numpy_arrays(env_param_overrides_json) return env_param_overrides_updated def cast_overrides_to_numpy_arrays(param_overrides: Dict[str, Union[float, List]]) \ -> Dict[str, Union[float, List, np.ndarray]]: """ All list type objects will be cast to numpy arrays before passing. This is needed for the current implementation of ControlledRandomWalk environments. :param param_overrides: Dictionary of parameters. :return: new_param_overrides: Dictionary similar to param_overrides, but with list values replaced with numpy arrays. """ new_param_overrides: Dict[str, Union[float, List, np.ndarray]] = dict() for p in param_overrides: if isinstance(param_overrides[p], list): new_param_overrides[p] = np.array(param_overrides[p]) else: new_param_overrides[p] = param_overrides[p] return new_param_overrides def process_agent_parameters(agent_params: str) -> Dict[str, Union[float, List]]: """ Process agents params. Note that this function purposely mutates params causing side effects. :param agent_params: Agent parameters to be processed passed as a file path, or as a dictionary, or as a list of dictionaries. :return: agent_params: """ # Load agent parameters considering several cases. # If simply a file path is provided. if os.path.exists(agent_params): with open(agent_params, 'r') as json_file: agent_params_data = json.load(json_file) else: # If a dictionary or list of dictionaries and/or file paths is provided first attain the # list. try: agent_params_data = ast.literal_eval(agent_params) except SyntaxError: raise ValueError('Argument is invalid. Possibly file doesnt exist. Value passed was ' f'{agent_params}') # Handle the case of a list for multiple (or even a single) agents. if isinstance(agent_params_data, list): for i, entry in enumerate(agent_params_data): if not isinstance(entry, dict): assert isinstance(entry, str) and os.path.exists(entry), \ "JSON file for agent parameters not found." with open(entry, 'r') as json_file: agent_params_data[i] = json.load(json_file) else: assert isinstance(entry, dict), "If not passing a JSON file of agent " \ "parameters you must pass a dictionary " \ "(JSON string)." else: # Users may pass a single dictionary of agent parameters when running a single RL agent. assert isinstance(agent_params_data, dict), "If not passing a JSON file of agent " \ "parameters you must pass a dictionary " \ "(JSON string)." return agent_params_data def post_process_rl_agent_params(agent_params: Union[Dict, List[Dict]], agent_names: List[str]) \ -> List[Dict[str, Union[float, List]]]: """ If we have parsed parameters for multiple RL agents, this function checks that the list of parameters has as many items as the list of RL agents (currently only checks for 'ppo' and 'reinforce' names). Otherwise, if we have parsed parameters for a single RL agent, it wraps the parameters with a list. :param agent_params: Dictionary or list of dictionaries with the parsed parameters for the RL agents. :param agent_names: List of parsed names of agents. :return: List of dictionaries with the parsed parameters for all the RL agents, even if there is only one. """ if isinstance(agent_params, list): assert len(agent_params) == agent_names.count('ppo') \ + agent_names.count('reinforce'), "The number of agent parameter sets provided " \ "for RL agents does not match the number of RL " \ "agents to run." else: assert agent_names.count('ppo') + agent_names.count('reinforce') == 1, \ "Users may only pass a dictionary of RL agent parameters when there a single RL " \ "agent is being validated." agent_params = [agent_params] return agent_params if __name__ == '__main__': # Simply get the arguments and run main. args = parse_args() run_validation(args)
import logging import re import typing from abc import ABC, abstractmethod from collections import Counter, defaultdict from functools import lru_cache from operator import itemgetter from pathlib import Path from typing import Callable, Dict, List, Optional, Union, cast import torch from deprecated import deprecated from torch.utils.data import Dataset from torch.utils.data.dataset import ConcatDataset, Subset import flair from flair.file_utils import Tqdm log = logging.getLogger("flair") def _iter_dataset(dataset: Optional[Dataset]) -> typing.Iterable: if dataset is None: return [] from flair.datasets import DataLoader return map(lambda x: x[0], DataLoader(dataset, batch_size=1, num_workers=0)) def _len_dataset(dataset: Optional[Dataset]) -> int: if dataset is None: return 0 from flair.datasets import DataLoader loader = DataLoader(dataset, batch_size=1, num_workers=0) return len(loader) class Dictionary: """ This class holds a dictionary that maps strings to IDs, used to generate one-hot encodings of strings. """ def __init__(self, add_unk=True): # init dictionaries self.item2idx: Dict[bytes, int] = {} self.idx2item: List[bytes] = [] self.add_unk = add_unk self.multi_label = False self.span_labels = False # in order to deal with unknown tokens, add <unk> if add_unk: self.add_item("<unk>") def remove_item(self, item: str): bytes_item = item.encode("utf-8") if bytes_item in self.item2idx: self.idx2item.remove(bytes_item) del self.item2idx[bytes_item] def add_item(self, item: str) -> int: """ add string - if already in dictionary returns its ID. if not in dictionary, it will get a new ID. :param item: a string for which to assign an id. :return: ID of string """ bytes_item = item.encode("utf-8") if bytes_item not in self.item2idx: self.idx2item.append(bytes_item) self.item2idx[bytes_item] = len(self.idx2item) - 1 return self.item2idx[bytes_item] def get_idx_for_item(self, item: str) -> int: """ returns the ID of the string, otherwise 0 :param item: string for which ID is requested :return: ID of string, otherwise 0 """ item_encoded = item.encode("utf-8") if item_encoded in self.item2idx.keys(): return self.item2idx[item_encoded] elif self.add_unk: return 0 else: log.error(f"The string '{item}' is not in dictionary! Dictionary contains only: {self.get_items()}") log.error( "You can create a Dictionary that handles unknown items with an <unk>-key by setting add_unk = True in the construction." ) raise IndexError def get_idx_for_items(self, items: List[str]) -> List[int]: """ returns the IDs for each item of the list of string, otherwise 0 if not found :param items: List of string for which IDs are requested :return: List of ID of strings """ if not hasattr(self, "item2idx_not_encoded"): d = dict([(key.decode("UTF-8"), value) for key, value in self.item2idx.items()]) self.item2idx_not_encoded = defaultdict(int, d) if not items: return [] results = itemgetter(*items)(self.item2idx_not_encoded) if isinstance(results, int): return [results] return list(results) def get_items(self) -> List[str]: items = [] for item in self.idx2item: items.append(item.decode("UTF-8")) return items def __len__(self) -> int: return len(self.idx2item) def get_item_for_index(self, idx): return self.idx2item[idx].decode("UTF-8") def set_start_stop_tags(self): self.add_item("<START>") self.add_item("<STOP>") def start_stop_tags_are_set(self): if {"<START>".encode(), "<STOP>".encode()}.issubset(self.item2idx.keys()): return True else: return False def save(self, savefile): import pickle with open(savefile, "wb") as f: mappings = {"idx2item": self.idx2item, "item2idx": self.item2idx} pickle.dump(mappings, f) def __setstate__(self, d): self.__dict__ = d # set 'add_unk' if the dictionary was created with a version of Flair older than 0.9 if "add_unk" not in self.__dict__.keys(): self.__dict__["add_unk"] = True if b"<unk>" in self.__dict__["idx2item"] else False @classmethod def load_from_file(cls, filename: Union[str, Path]): import pickle f = open(filename, "rb") mappings = pickle.load(f, encoding="latin1") idx2item = mappings["idx2item"] item2idx = mappings["item2idx"] f.close() # set 'add_unk' depending on whether <unk> is a key add_unk = True if b"<unk>" in idx2item else False dictionary: Dictionary = Dictionary(add_unk=add_unk) dictionary.item2idx = item2idx dictionary.idx2item = idx2item return dictionary @classmethod def load(cls, name: str): from flair.file_utils import cached_path hu_path: str = "https://flair.informatik.hu-berlin.de/resources/characters" if name == "chars" or name == "common-chars": char_dict = cached_path(f"{hu_path}/common_characters", cache_dir="datasets") return Dictionary.load_from_file(char_dict) if name == "chars-large" or name == "common-chars-large": char_dict = cached_path(f"{hu_path}/common_characters_large", cache_dir="datasets") return Dictionary.load_from_file(char_dict) if name == "chars-xl" or name == "common-chars-xl": char_dict = cached_path(f"{hu_path}/common_characters_xl", cache_dir="datasets") return Dictionary.load_from_file(char_dict) if name == "chars-lemmatizer" or name == "common-chars-lemmatizer": char_dict = cached_path(f"{hu_path}/common_characters_lemmatizer", cache_dir="datasets") return Dictionary.load_from_file(char_dict) return Dictionary.load_from_file(name) def __eq__(self, o: object) -> bool: if not isinstance(o, Dictionary): return False return self.item2idx == o.item2idx and self.idx2item == o.idx2item and self.add_unk == o.add_unk def __str__(self): tags = ", ".join(self.get_item_for_index(i) for i in range(min(len(self), 50))) return f"Dictionary with {len(self)} tags: {tags}" class Label: """ This class represents a label. Each label has a value and optionally a confidence score. The score needs to be between 0.0 and 1.0. Default value for the score is 1.0. """ def __init__(self, value: Optional[str], score: float = 1.0): self._value = value self._score = score super().__init__() def set_value(self, value: str, score: float = 1.0): self.value = value self.score = score def spawn(self, value: str, score: float = 1.0): return Label(value, score) @property def value(self): return self._value @value.setter def value(self, value): if not value and value != "": raise ValueError("Incorrect label value provided. Label value needs to be set.") else: self._value = value @property def score(self): return self._score @score.setter def score(self, score): self._score = score def to_dict(self): return {"value": self.value, "confidence": self.score} def __str__(self): return f"{self._value} ({round(self._score, 4)})" def __repr__(self): return f"{self._value} ({round(self._score, 4)})" def __eq__(self, other): return self.value == other.value and self.score == other.score @property def identifier(self): return "" class SpanLabel(Label): def __init__(self, span, value: Optional[str], score: float = 1.0): super().__init__(value, score) self.span = span def spawn(self, value: str, score: float = 1.0): return SpanLabel(self.span, value, score) def to_dict(self): return {"span": self.span, "value": self.value, "confidence": self.score} def __str__(self): return f"{self._value} [{self.span.id_text}] ({round(self._score, 4)})" def __repr__(self): return f"{self._value} [{self.span.id_text}] ({round(self._score, 4)})" def __hash__(self): return hash(self.__repr__()) def __len__(self): return len(self.span) def __eq__(self, other): return self.value == other.value and self.score == other.score and self.span.id_text == other.span.id_text @property def identifier(self): return f"{self.span.id_text}" class RelationLabel(Label): def __init__(self, head, tail, value: Optional[str], score: float = 1.0): super().__init__(value, score) self.head = head self.tail = tail def spawn(self, value: str, score: float = 1.0): return RelationLabel(self.head, self.tail, value, score) def __str__(self): return f"{self._value} [{self.head.id_text} -> {self.tail.id_text}] ({round(self._score, 4)})" def __repr__(self): return f"{self._value} from {self.head.id_text} -> {self.tail.id_text} ({round(self._score, 4)})" def __len__(self): return len(self.head) + len(self.tail) def __eq__(self, other): return ( self.value == other.value and self.score == other.score and self.head.id_text == other.head.id_text and self.tail.id_text == other.tail.id_text ) @property def identifier(self): return f"{self.head.id_text} -> {self.tail.id_text}" class EntityLinkingLabel(Label): def __init__(self, span, cui, concept_name, ontology = None, score: float = 1): super().__init__(cui, score) self.span = span self.ontology = ontology self.concept_name = concept_name def spawn(self, value: str, score: float = 1): return EntityLinkingLabel(self.span, value, self.ontology, self.concept_name, score) def __str__(self): return f"{self._value} {self.concept_name} [{self.span}] ({round(self._score, 4)})" def __repr__(self): return f"{self._value} {self.concept_name} [{self.span}] ({round(self._score, 4)})" def __len__(self): return len(self.span) def __eq__(self, other): return ( self.value == other.value and self.span.id_text == other.span.id_text and self.concept_name == other.concept_name and self.ontology == other.ontology and self.score == other.score ) @property def identifier(self): return f"{self.cui}" class DataPoint: """ This is the parent class of all data points in Flair (including Token, Sentence, Image, etc.). Each DataPoint must be embeddable (hence the abstract property embedding() and methods to() and clear_embeddings()). Also, each DataPoint may have Labels in several layers of annotation (hence the functions add_label(), get_labels() and the property 'label') """ def __init__(self): self.annotation_layers = {} self._embeddings: Dict[str, torch.Tensor] = {} @property @abstractmethod def embedding(self): pass def set_embedding(self, name: str, vector: torch.Tensor): self._embeddings[name] = vector def get_embedding(self, names: Optional[List[str]] = None) -> torch.Tensor: embeddings = self.get_each_embedding(names) if embeddings: return torch.cat(embeddings, dim=0) return torch.tensor([], device=flair.device) def get_each_embedding(self, embedding_names: Optional[List[str]] = None) -> List[torch.Tensor]: embeddings = [] for embed_name in sorted(self._embeddings.keys()): if embedding_names and embed_name not in embedding_names: continue embed = self._embeddings[embed_name].to(flair.device) embeddings.append(embed) return embeddings def to(self, device: str, pin_memory: bool = False): for name, vector in self._embeddings.items(): if str(vector.device) != str(device): if pin_memory: self._embeddings[name] = vector.to(device, non_blocking=True).pin_memory() else: self._embeddings[name] = vector.to(device, non_blocking=True) def clear_embeddings(self, embedding_names: List[str] = None): if embedding_names is None: self._embeddings = {} else: for name in embedding_names: if name in self._embeddings.keys(): del self._embeddings[name] def add_label(self, typename: str, value: str, score: float = 1.0): if typename not in self.annotation_layers: self.annotation_layers[typename] = [Label(value, score)] else: self.annotation_layers[typename].append(Label(value, score)) return self def add_complex_label(self, typename: str, label: Label): if typename in self.annotation_layers and label in self.annotation_layers[typename]: return self if typename not in self.annotation_layers: self.annotation_layers[typename] = [label] else: self.annotation_layers[typename].append(label) return self def set_label(self, typename: str, value: str, score: float = 1.0): self.annotation_layers[typename] = [Label(value, score)] return self def remove_labels(self, typename: str): if typename in self.annotation_layers.keys(): del self.annotation_layers[typename] def get_labels(self, typename: str = None): if typename is None: return self.labels return self.annotation_layers[typename] if typename in self.annotation_layers else [] @property def labels(self) -> List[Label]: all_labels = [] for key in self.annotation_layers.keys(): all_labels.extend(self.annotation_layers[key]) return all_labels DT = typing.TypeVar("DT", bound=DataPoint) DT2 = typing.TypeVar("DT2", bound=DataPoint) class Token(DataPoint): """ This class represents one word in a tokenized sentence. Each token may have any number of tags. It may also point to its head in a dependency tree. """ def __init__( self, text: str, idx: int = None, head_id: int = None, whitespace_after: bool = True, start_position: int = None, ): super().__init__() self.text: str = text self.idx: Optional[int] = idx self.head_id: Optional[int] = head_id self.whitespace_after: bool = whitespace_after self.start_pos = start_position self.end_pos = start_position + len(text) if start_position is not None else None self.sentence: Optional[Sentence] = None self._embeddings: Dict = {} self.tags_proba_dist: Dict[str, List[Label]] = {} def add_tag_label(self, tag_type: str, tag: Label): self.set_label(tag_type, tag.value, tag.score) def add_tags_proba_dist(self, tag_type: str, tags: List[Label]): self.tags_proba_dist[tag_type] = tags def add_tag(self, tag_type: str, tag_value: str, confidence=1.0): self.set_label(tag_type, tag_value, confidence) def get_tag(self, label_type, zero_tag_value=""): if len(self.get_labels(label_type)) == 0: return Label(zero_tag_value) return self.get_labels(label_type)[0] def get_tags_proba_dist(self, tag_type: str) -> List[Label]: if tag_type in self.tags_proba_dist: return self.tags_proba_dist[tag_type] return [] def get_head(self): return self.sentence.get_token(self.head_id) @property def start_position(self) -> Optional[int]: return self.start_pos @property def end_position(self) -> Optional[int]: return self.end_pos @property def embedding(self): return self.get_embedding() def __str__(self) -> str: return "Token: {} {}".format(self.idx, self.text) if self.idx is not None else "Token: {}".format(self.text) def __repr__(self) -> str: return "Token: {} {}".format(self.idx, self.text) if self.idx is not None else "Token: {}".format(self.text) class Span(DataPoint): """ This class represents one textual span consisting of Tokens. """ def __init__(self, tokens: List[Token]): super().__init__() self.tokens = tokens @property def start_pos(self) -> int: assert self.tokens[0].start_position is not None return self.tokens[0].start_position @property def end_pos(self) -> int: assert self.tokens[-1].end_position is not None return self.tokens[-1].end_position @property def text(self) -> str: return " ".join([t.text for t in self.tokens]) def to_original_text(self) -> str: pos = self.tokens[0].start_pos if pos is None: return " ".join([t.text for t in self.tokens]) str = "" for t in self.tokens: if t.start_pos is None: return " ".join([t.text for t in self.tokens]) while t.start_pos > pos: str += " " pos += 1 str += t.text pos += len(t.text) return str def to_plain_string(self): plain = "" for token in self.tokens: plain += token.text if token.whitespace_after: plain += " " return plain.rstrip() def __str__(self) -> str: ids = ",".join([str(t.idx) for t in self.tokens]) label_string = " ".join([str(label) for label in self.labels]) labels = f" [− Labels: {label_string}]" if self.labels else "" return 'Span [{}]: "{}"{}'.format(ids, self.text, labels) @property def id_text(self) -> str: return f"{" ".join([t.text for t in self.tokens])} ({",".join([str(t.idx) for t in self.tokens])})" def __repr__(self) -> str: ids = ",".join([str(t.idx) for t in self.tokens]) return ( '<{}-span ({}): "{}">'.format(self.tag, ids, self.text) if len(self.labels) > 0 else '<span ({}): "{}">'.format(ids, self.text) ) def __getitem__(self, idx: int) -> Token: return self.tokens[idx] def __iter__(self): return iter(self.tokens) def __len__(self) -> int: return len(self.tokens) @property def tag(self): return self.labels[0].value @property def score(self): return self.labels[0].score @property def position_string(self): return "-".join([str(token.idx) for token in self]) @property def embedding(self): return torch.empty() def to(self, device: str, pin_memory: bool = False): pass def clear_embeddings(self, embedding_names: List[str] = None): pass def add_tag(self, tag_type: str, tag_value: str, confidence=1.0): assert self.tokens[0].sentence is not None self.tokens[0].sentence.add_complex_label(tag_type, SpanLabel(self, value=tag_value, score=confidence)) class Tokenizer(ABC): r"""An abstract class representing a :class:`Tokenizer`. Tokenizers are used to represent algorithms and models to split plain text into individual tokens / words. All subclasses should overwrite :meth:`tokenize`, which splits the given plain text into tokens. Moreover, subclasses may overwrite :meth:`name`, returning a unique identifier representing the tokenizer's configuration. """ @abstractmethod def tokenize(self, text: str) -> List[Token]: raise NotImplementedError() @property def name(self) -> str: return self.__class__.__name__ class Sentence(DataPoint): """ A Sentence is a list of tokens and is used to represent a sentence or text fragment. """ def __init__( self, text: Union[str, List[str]] = [], use_tokenizer: Union[bool, Tokenizer, Callable] = True, language_code: str = None, start_position: int = None, ): """ Class to hold all meta related to a text (tokens, predictions, language code, ...) :param text: original string (sentence), or a list of string tokens (words) :param use_tokenizer: a custom tokenizer (default is :class:`SpaceTokenizer`) more advanced options are :class:`SegTokTokenizer` to use segtok or :class:`SpacyTokenizer` to use Spacy library if available). Check the implementations of abstract class Tokenizer or implement your own subclass (if you need it). If instead of providing a Tokenizer, this parameter is just set to True (deprecated), :class:`SegtokTokenizer` will be used. :param language_code: Language of the sentence :param start_position: Start char offset of the sentence in the superordinate document """ super().__init__() self.tokens: List[Token] = [] self.language_code: Optional[str] = language_code self.start_pos = start_position self.end_pos = start_position + len(text) if start_position is not None else None # the tokenizer used for this sentence if isinstance(use_tokenizer, Tokenizer): tokenizer = use_tokenizer elif callable(use_tokenizer): from flair.tokenization import TokenizerWrapper tokenizer = TokenizerWrapper(use_tokenizer) elif type(use_tokenizer) == bool: from flair.tokenization import SegtokTokenizer, SpaceTokenizer tokenizer = SegtokTokenizer() if use_tokenizer else SpaceTokenizer() else: raise AssertionError( "Unexpected type of parameter 'use_tokenizer'. " + "Parameter should be bool, Callable[[str], List[Token]] (deprecated), Tokenizer" ) # if text is passed, instantiate sentence with tokens (words) if isinstance(text, (list, tuple)): [self.add_token(self._restore_windows_1252_characters(token)) for token in text] else: text = self._restore_windows_1252_characters(text) [self.add_token(token) for token in tokenizer.tokenize(text)] # log a warning if the dataset is empty if text == "": log.warning("Warning: An empty Sentence was created! Are there empty strings in your dataset?") self.tokenized: Optional[str] = None # some sentences represent a document boundary (but most do not) self.is_document_boundary: bool = False # internal variables to denote position inside dataset self._previous_sentence: Optional[Sentence] = None self._next_sentence: Optional[Sentence] = None self._position_in_dataset: Optional[typing.Tuple[Dataset, int]] = None def get_token(self, token_id: int) -> Optional[Token]: for token in self.tokens: if token.idx == token_id: return token return None def add_token(self, token: Union[Token, str]): if type(token) is str: token = Token(token) token = cast(Token, token) token.text = token.text.replace("\u200c", "") token.text = token.text.replace("\u200b", "") token.text = token.text.replace("\ufe0f", "") token.text = token.text.replace("\ufeff", "") # data with zero-width characters cannot be handled if token.text == "": return self.tokens.append(token) # set token idx if not set token.sentence = self if token.idx is None: token.idx = len(self.tokens) def get_label_names(self): label_names = [] for label in self.labels: label_names.append(label.value) return label_names def _convert_span_labels(self, label_type: str, min_score=-1): current_span: List[Token] = [] tags: Dict[str, float] = defaultdict(lambda: 0.0) previous_tag_value: str = "O" for token in self: tag: Label = token.get_tag(label_type) tag_value = tag.value # non-set tags are OUT tags if tag_value == "" or tag_value == "O" or tag_value == "_": tag_value = "O-" # anything that is not a BIOES tag is a SINGLE tag if tag_value[0:2] not in ["B-", "I-", "O-", "E-", "S-"]: tag_value = "S-" + tag_value # anything that is not OUT is IN in_span = False if tag_value[0:2] not in ["O-"]: in_span = True # single and begin tags start a new span starts_new_span = False if tag_value[0:2] in ["B-", "S-"]: starts_new_span = True if previous_tag_value[0:2] in ["S-"] and previous_tag_value[2:] != tag_value[2:] and in_span: starts_new_span = True if (starts_new_span or not in_span) and len(current_span) > 0: scores = [t.get_labels(label_type)[0].score for t in current_span] span_score = sum(scores) / len(scores) if span_score > min_score: span = Span(current_span) value = sorted(tags.items(), key=lambda k_v: k_v[1], reverse=True)[0][0] self.add_complex_label( typename=label_type, label=SpanLabel(span=span, value=value, score=span_score), ) current_span = [] tags = defaultdict(lambda: 0.0) if in_span: current_span.append(token) weight = 1.1 if starts_new_span else 1.0 tags[tag_value[2:]] += weight # remember previous tag previous_tag_value = tag_value if len(current_span) > 0: scores = [t.get_labels(label_type)[0].score for t in current_span] span_score = sum(scores) / len(scores) if span_score > min_score: span = Span(current_span) value = sorted(tags.items(), key=lambda k_v: k_v[1], reverse=True)[0][0] self.add_complex_label( typename=label_type, label=SpanLabel(span=span, value=value, score=span_score), ) @property def embedding(self): return self.get_embedding() def to(self, device: str, pin_memory: bool = False): # move sentence embeddings to device super().to(device=device, pin_memory=pin_memory) # also move token embeddings to device for token in self: token.to(device, pin_memory) def clear_embeddings(self, embedding_names: List[str] = None): super().clear_embeddings(embedding_names) # clear token embeddings for token in self: token.clear_embeddings(embedding_names) @lru_cache(maxsize=1) # cache last context, as training repeats calls def left_context(self, context_length: int, respect_document_boundaries: bool = True): sentence = self left_context: List[str] = [] while True: sentence = sentence.previous_sentence() if sentence is None: break if respect_document_boundaries and sentence.is_document_boundary: break left_context = [t.text for t in sentence.tokens] + left_context if len(left_context) > context_length: left_context = left_context[-context_length:] break return left_context @lru_cache(maxsize=1) # cache last context, as training repeats calls def right_context(self, context_length: int, respect_document_boundaries: bool = True): sentence = self right_context: List[str] = [] while True: sentence = sentence.next_sentence() if sentence is None: break if respect_document_boundaries and sentence.is_document_boundary: break right_context += [t.text for t in sentence.tokens] if len(right_context) > context_length: right_context = right_context[:context_length] break return right_context def to_tagged_string(self, main_tag=None) -> str: list = [] for token in self.tokens: list.append(token.text) tags: List[str] = [] for label_type in token.annotation_layers.keys(): if main_tag is not None and main_tag != label_type: continue if token.get_labels(label_type)[0].value == "O": continue if token.get_labels(label_type)[0].value == "_": continue tags.append(token.get_labels(label_type)[0].value) all_tags = "<" + "/".join(tags) + ">" if all_tags != "<>": list.append(all_tags) return " ".join(list) def to_tokenized_string(self) -> str: if self.tokenized is None: self.tokenized = " ".join([t.text for t in self.tokens]) return self.tokenized def to_plain_string(self): plain = "" for token in self.tokens: plain += token.text if token.whitespace_after: plain += " " return plain.rstrip() def infer_space_after(self): """ Heuristics in case you wish to infer whitespace_after values for tokenized text. This is useful for some old NLP tasks (such as CoNLL-03 and CoNLL-2000) that provide only tokenized data with no info of original whitespacing. :return: """ last_token = None quote_count: int = 0 # infer whitespace after field for token in self.tokens: if token.text == '"': quote_count += 1 if quote_count % 2 != 0: token.whitespace_after = False elif last_token is not None: last_token.whitespace_after = False if last_token is not None: if token.text in [".", ":", ",", ";", ")", "n't", "!", "?"]: last_token.whitespace_after = False if token.text.startswith("'"): last_token.whitespace_after = False if token.text in ["("]: token.whitespace_after = False last_token = token return self def to_original_text(self) -> str: str = "" pos = 0 for t in self.tokens: if t.start_pos is None: return self.to_tokenized_string() while t.start_pos > pos: str += " " pos += 1 str += t.text pos += len(t.text) return str def to_dict(self, tag_type: str = None): labels = [] if tag_type: labels = [label.to_dict() for label in self.get_labels(tag_type)] return {"text": self.to_original_text(), tag_type: labels} if self.labels: labels = [label.to_dict() for label in self.labels] return {"text": self.to_original_text(), "all labels": labels} @typing.overload def __getitem__(self, idx: int) -> Token: ... @typing.overload def __getitem__(self, s: slice) -> Span: ... def __getitem__(self, subscript): if isinstance(subscript, slice): return Span(self.tokens[subscript]) else: return self.tokens[subscript] def __iter__(self): return iter(self.tokens) def __len__(self) -> int: return len(self.tokens) def __repr__(self): tagged_string = self.to_tagged_string() tokenized_string = self.to_tokenized_string() # add Sentence labels to output if they exist sentence_labels = f" − Sentence-Labels: {self.annotation_layers}" if self.annotation_layers != {} else "" # add Token labels to output if they exist token_labels = f' − Token-Labels: "{tagged_string}"' if tokenized_string != tagged_string else "" return f'Sentence: "{tokenized_string}" [− Tokens: {len(self)}{token_labels}{sentence_labels}]' def __copy__(self): s = Sentence() for token in self.tokens: nt = Token(token.text) for tag_type in token.tags: nt.add_label( tag_type, token.get_tag(tag_type).value, token.get_tag(tag_type).score, ) s.add_token(nt) return s def __str__(self) -> str: tagged_string = self.to_tagged_string() tokenized_string = self.to_tokenized_string() # add Sentence labels to output if they exist sentence_labels = f" − Sentence-Labels: {self.annotation_layers}" if self.annotation_layers != {} else "" # add Token labels to output if they exist token_labels = f' − Token-Labels: "{tagged_string}"' if tokenized_string != tagged_string else "" return f'Sentence: "{tokenized_string}" [− Tokens: {len(self)}{token_labels}{sentence_labels}]' def get_language_code(self) -> str: if self.language_code is None: import langdetect try: self.language_code = langdetect.detect(self.to_plain_string()) except Exception: self.language_code = "en" return self.language_code @staticmethod def _restore_windows_1252_characters(text: str) -> str: def to_windows_1252(match): try: return bytes([ord(match.group(0))]).decode("windows-1252") except UnicodeDecodeError: # No character at the corresponding code point: remove it return "" return re.sub(r"[\u0080-\u0099]", to_windows_1252, text) def next_sentence(self): """ Get the next sentence in the document (works only if context is set through dataloader or elsewhere) :return: next Sentence in document if set, otherwise None """ if self._next_sentence is not None: return self._next_sentence if self._position_in_dataset is not None: dataset = self._position_in_dataset[0] index = self._position_in_dataset[1] + 1 if index < len(dataset): return dataset[index] return None def previous_sentence(self): """ Get the previous sentence in the document (works only if context is set through dataloader or elsewhere) :return: previous Sentence in document if set, otherwise None """ if self._previous_sentence is not None: return self._previous_sentence if self._position_in_dataset is not None: dataset = self._position_in_dataset[0] index = self._position_in_dataset[1] - 1 if index >= 0: return dataset[index] return None def is_context_set(self) -> bool: """ Return True or False depending on whether context is set (for instance in dataloader or elsewhere) :return: True if context is set, else False """ return self._previous_sentence is not None or self._position_in_dataset is not None def get_labels(self, label_type: str = None): # if no label if specified, return all labels if label_type is None: return self.labels # if the label type exists in the Sentence, return it if label_type in self.annotation_layers: return self.annotation_layers[label_type] # otherwise check if the label exists on the token-level # in this case, create span-labels and return those if label_type in set().union(*(token.annotation_layers.keys() for token in self)): return [ SpanLabel(Span([token]), token.get_tag(label_type).value, token.get_tag(label_type).score) for token in self if label_type in token.annotation_layers ] # return empty list if none of the above return [] class DataPair(DataPoint, typing.Generic[DT, DT2]): def __init__(self, first: DT, second: DT2): super().__init__() self.first = first self.second = second def to(self, device: str, pin_memory: bool = False): self.first.to(device, pin_memory) self.second.to(device, pin_memory) def clear_embeddings(self, embedding_names: List[str] = None): self.first.clear_embeddings(embedding_names) self.second.clear_embeddings(embedding_names) @property def embedding(self): return torch.cat([self.first.embedding, self.second.embedding]) def __str__(self): return f"DataPair:\n − First {self.first}\n − Second {self.second}\n − Labels: {self.labels}" def to_plain_string(self): return f"DataPair: First {self.first} || Second {self.second}" def to_original_text(self): return f"{self.first.to_original_text()} || {self.second.to_original_text()}" def __len__(self): return len(self.first) + len(self.second) TextPair = DataPair[Sentence, Sentence] class Image(DataPoint): def __init__(self, data=None, imageURL=None): super().__init__() self.data = data self._embeddings: Dict = {} self.imageURL = imageURL @property def embedding(self): return self.get_embedding() def __str__(self): image_repr = self.data.size() if self.data else "" image_url = self.imageURL if self.imageURL else "" return f"Image: {image_repr} {image_url}" class FlairDataset(Dataset): @abstractmethod def is_in_memory(self) -> bool: pass class Corpus: def __init__( self, train: Dataset = None, dev: Dataset = None, test: Dataset = None, name: str = "corpus", sample_missing_splits: Union[bool, str] = True, ): # set name self.name: str = name # abort if no data is provided if not train and not dev and not test: raise RuntimeError("No data provided when initializing corpus object.") # sample test data from train if none is provided if test is None and sample_missing_splits and train and not sample_missing_splits == "only_dev": train_length = _len_dataset(train) test_size: int = round(train_length / 10) test, train = randomly_split_into_two_datasets(train, test_size) # sample dev data from train if none is provided if dev is None and sample_missing_splits and train and not sample_missing_splits == "only_test": train_length = _len_dataset(train) dev_size: int = round(train_length / 10) dev, train = randomly_split_into_two_datasets(train, dev_size) # set train dev and test data self._train: Optional[Dataset] = train self._test: Optional[Dataset] = test self._dev: Optional[Dataset] = dev @property def train(self) -> Optional[Dataset]: return self._train @property def dev(self) -> Optional[Dataset]: return self._dev @property def test(self) -> Optional[Dataset]: return self._test def downsample( self, percentage: float = 0.1, downsample_train=True, downsample_dev=True, downsample_test=True, ): if downsample_train and self._train is not None: self._train = self._downsample_to_proportion(self._train, percentage) if downsample_dev and self._dev is not None: self._dev = self._downsample_to_proportion(self._dev, percentage) if downsample_test and self._test is not None: self._test = self._downsample_to_proportion(self._test, percentage) return self def filter_empty_sentences(self): log.info("Filtering empty sentences") if self._train is not None: self._train = Corpus._filter_empty_sentences(self._train) if self._test is not None: self._test = Corpus._filter_empty_sentences(self._test) if self._dev is not None: self._dev = Corpus._filter_empty_sentences(self._dev) log.info(self) def filter_long_sentences(self, max_charlength: int): log.info("Filtering long sentences") if self._train is not None: self._train = Corpus._filter_long_sentences(self._train, max_charlength) if self._test is not None: self._test = Corpus._filter_long_sentences(self._test, max_charlength) if self._dev is not None: self._dev = Corpus._filter_long_sentences(self._dev, max_charlength) log.info(self) @staticmethod def _filter_long_sentences(dataset, max_charlength: int) -> Dataset: # find out empty sentence indices empty_sentence_indices = [] non_empty_sentence_indices = [] for index, sentence in Tqdm.tqdm(enumerate(_iter_dataset(dataset))): if len(sentence.to_plain_string()) > max_charlength: empty_sentence_indices.append(index) else: non_empty_sentence_indices.append(index) # create subset of non-empty sentence indices subset = Subset(dataset, non_empty_sentence_indices) return subset @staticmethod def _filter_empty_sentences(dataset) -> Dataset: # find out empty sentence indices empty_sentence_indices = [] non_empty_sentence_indices = [] for index, sentence in enumerate(_iter_dataset(dataset)): if len(sentence) == 0: empty_sentence_indices.append(index) else: non_empty_sentence_indices.append(index) # create subset of non-empty sentence indices subset = Subset(dataset, non_empty_sentence_indices) return subset def make_vocab_dictionary(self, max_tokens=-1, min_freq=1) -> Dictionary: """ Creates a dictionary of all tokens contained in the corpus. By defining `max_tokens` you can set the maximum number of tokens that should be contained in the dictionary. If there are more than `max_tokens` tokens in the corpus, the most frequent tokens are added first. If `min_freq` is set the a value greater than 1 only tokens occurring more than `min_freq` times are considered to be added to the dictionary. :param max_tokens: the maximum number of tokens that should be added to the dictionary (-1 = take all tokens) :param min_freq: a token needs to occur at least `min_freq` times to be added to the dictionary (-1 = there is no limitation) :return: dictionary of tokens """ tokens = self._get_most_common_tokens(max_tokens, min_freq) vocab_dictionary: Dictionary = Dictionary() for token in tokens: vocab_dictionary.add_item(token) return vocab_dictionary def _get_most_common_tokens(self, max_tokens, min_freq) -> List[str]: tokens_and_frequencies = Counter(self._get_all_tokens()) tokens: List[str] = [] for token, freq in tokens_and_frequencies.most_common(): if (min_freq != -1 and freq < min_freq) or (max_tokens != -1 and len(tokens) == max_tokens): break tokens.append(token) return tokens def _get_all_tokens(self) -> List[str]: assert self.train tokens = list(map((lambda s: s.tokens), _iter_dataset(self.train))) tokens = [token for sublist in tokens for token in sublist] return list(map((lambda t: t.text), tokens)) @staticmethod def _downsample_to_proportion(dataset: Dataset, proportion: float): sampled_size: int = round(_len_dataset(dataset) * proportion) splits = randomly_split_into_two_datasets(dataset, sampled_size) return splits[0] def obtain_statistics(self, label_type: str = None, pretty_print: bool = True) -> Union[dict, str]: """ Print statistics about the class distribution (only labels of sentences are taken into account) and sentence sizes. """ json_data = { "TRAIN": self._obtain_statistics_for(self.train, "TRAIN", label_type), "TEST": self._obtain_statistics_for(self.test, "TEST", label_type), "DEV": self._obtain_statistics_for(self.dev, "DEV", label_type), } if pretty_print: import json return json.dumps(json_data, indent=4) return json_data @staticmethod def _obtain_statistics_for(sentences, name, tag_type) -> dict: if len(sentences) == 0: return {} classes_to_count = Corpus._count_sentence_labels(sentences) tags_to_count = Corpus._count_token_labels(sentences, tag_type) tokens_per_sentence = Corpus._get_tokens_per_sentence(sentences) label_size_dict = {} for label, c in classes_to_count.items(): label_size_dict[label] = c tag_size_dict = {} for tag, c in tags_to_count.items(): tag_size_dict[tag] = c return { "dataset": name, "total_number_of_documents": len(sentences), "number_of_documents_per_class": label_size_dict, "number_of_tokens_per_tag": tag_size_dict, "number_of_tokens": { "total": sum(tokens_per_sentence), "min": min(tokens_per_sentence), "max": max(tokens_per_sentence), "avg": sum(tokens_per_sentence) / len(sentences), }, } @staticmethod def _get_tokens_per_sentence(sentences): return list(map(lambda x: len(x.tokens), sentences)) @staticmethod def _count_sentence_labels(sentences): label_count = defaultdict(lambda: 0) for sent in sentences: for label in sent.labels: label_count[label.value] += 1 return label_count @staticmethod def _count_token_labels(sentences, label_type): label_count = defaultdict(lambda: 0) for sent in sentences: for token in sent.tokens: if label_type in token.annotation_layers.keys(): label = token.get_tag(label_type) label_count[label.value] += 1 return label_count def __str__(self) -> str: return "Corpus: %d train + %d dev + %d test sentences" % ( _len_dataset(self.train) if self.train else 0, _len_dataset(self.dev) if self.dev else 0, _len_dataset(self.test) if self.test else 0, ) def make_label_dictionary(self, label_type: str, min_count: int = -1) -> Dictionary: """ Creates a dictionary of all labels assigned to the sentences in the corpus. :return: dictionary of labels """ label_dictionary: Dictionary = Dictionary(add_unk=True) label_dictionary.span_labels = False assert self.train datasets = [self.train] data: ConcatDataset = ConcatDataset(datasets) log.info("Computing label dictionary. Progress:") all_label_types: typing.Counter[str] = Counter() label_occurrence: typing.Counter[str] = Counter() all_sentence_labels: List[str] = [] for sentence in Tqdm.tqdm(_iter_dataset(data)): # check if sentence itself has labels labels = sentence.get_labels(label_type) all_label_types.update(sentence.annotation_layers.keys()) # go through all labels and increment count for label in labels: if label.value not in all_sentence_labels: label_occurrence[label.value] += 1 # check if there are any span labels if type(label) == SpanLabel and len(label.span) > 1: label_dictionary.span_labels = True if not label_dictionary.multi_label: if len(labels) > 1: label_dictionary.multi_label = True erfasst_count = 0 unked_count = 0 for label, count in label_occurrence.most_common(): if count >= min_count: label_dictionary.add_item(label) erfasst_count += count else: unked_count += count if len(label_dictionary.idx2item) == 0: log.error( f"Corpus contains only the labels: {", ".join([f"{label[0]} (#{label[1]})' for label in all_label_types.most_common()])}" ) log.error(f"You specified as label_type='{label_type}' which is not in this dataset!") raise Exception log.info( f"Corpus contains the labels: {", ".join([label[0] + f" (#{label[1]})' for label in all_label_types.most_common()])}" ) log.info(f"{erfasst_count} instances in dict, {unked_count} instances are UNK'ed") log.info(f"Most commonly observed '{label_type}'-labels are {label_occurrence.most_common(20)}") log.info(f"Created (for label '{label_type}') {label_dictionary}") return label_dictionary def get_label_distribution(self): class_to_count = defaultdict(lambda: 0) for sent in self.train: for label in sent.labels: class_to_count[label.value] += 1 return class_to_count def get_all_sentences(self) -> ConcatDataset: parts = [] if self.train: parts.append(self.train) if self.dev: parts.append(self.dev) if self.test: parts.append(self.test) return ConcatDataset(parts) @deprecated(version="0.8", reason="Use 'make_label_dictionary' instead.") def make_tag_dictionary(self, tag_type: str) -> Dictionary: # Make the tag dictionary tag_dictionary: Dictionary = Dictionary(add_unk=False) tag_dictionary.add_item("O") for sentence in _iter_dataset(self.get_all_sentences()): for token in sentence.tokens: tag_dictionary.add_item(token.get_tag(tag_type).value) tag_dictionary.add_item("<START>") tag_dictionary.add_item("<STOP>") return tag_dictionary class MultiCorpus(Corpus): def __init__(self, corpora: List[Corpus], name: str = "multicorpus", **corpusargs): self.corpora: List[Corpus] = corpora train_parts = [] dev_parts = [] test_parts = [] for corpus in self.corpora: if corpus.train: train_parts.append(corpus.train) if corpus.dev: dev_parts.append(corpus.dev) if corpus.test: test_parts.append(corpus.test) super(MultiCorpus, self).__init__( ConcatDataset(train_parts) if len(train_parts) > 0 else None, ConcatDataset(dev_parts) if len(dev_parts) > 0 else None, ConcatDataset(test_parts) if len(test_parts) > 0 else None, name=name, **corpusargs, ) def __str__(self): output = ( f"MultiCorpus: " f"{len(self.train) if self.train else 0} train + " f"{len(self.dev) if self.dev else 0} dev + " f"{len(self.test) if self.test else 0} test sentences\n - " ) output += "\n - ".join([f"{type(corpus).__name__} {str(corpus)} - {corpus.name}" for corpus in self.corpora]) return output def iob2(tags): """ Check that tags have a valid IOB format. Tags in IOB1 format are converted to IOB2. """ for i, tag in enumerate(tags): if tag.value == "O": continue split = tag.value.split("-") if len(split) != 2 or split[0] not in ["I", "B"]: return False if split[0] == "B": continue elif i == 0 or tags[i - 1].value == "O": # conversion IOB1 to IOB2 tags[i].value = "B" + tag.value[1:] elif tags[i - 1].value[1:] == tag.value[1:]: continue else: # conversion IOB1 to IOB2 tags[i].value = "B" + tag.value[1:] return True def iob_iobes(tags): """ IOB -> IOBES """ for i, tag in enumerate(tags): if tag.value == "O" or tag.value == "": tag.value = "O" continue t, label = tag.value.split("-", 1) if len(tags) == i + 1 or tags[i + 1].value == "O": next_same = False else: nt, next_label = tags[i + 1].value.split("-", 1) next_same = nt == "I" and next_label == label if t == "B": if not next_same: tag.value = tag.value.replace("B-", "S-") elif t == "I": if not next_same: tag.value = tag.value.replace("I-", "E-") else: raise Exception("Invalid IOB format!") def randomly_split_into_two_datasets(dataset, length_of_first): import random indices = [i for i in range(len(dataset))] random.shuffle(indices) first_dataset = indices[:length_of_first] second_dataset = indices[length_of_first:] first_dataset.sort() second_dataset.sort() return Subset(dataset, first_dataset), Subset(dataset, second_dataset)
import logging import re import typing from abc import ABC, abstractmethod from collections import Counter, defaultdict from functools import lru_cache from operator import itemgetter from pathlib import Path from typing import Callable, Dict, List, Optional, Union, cast import torch from deprecated import deprecated from torch.utils.data import Dataset from torch.utils.data.dataset import ConcatDataset, Subset import flair from flair.file_utils import Tqdm log = logging.getLogger("flair") def _iter_dataset(dataset: Optional[Dataset]) -> typing.Iterable: if dataset is None: return [] from flair.datasets import DataLoader return map(lambda x: x[0], DataLoader(dataset, batch_size=1, num_workers=0)) def _len_dataset(dataset: Optional[Dataset]) -> int: if dataset is None: return 0 from flair.datasets import DataLoader loader = DataLoader(dataset, batch_size=1, num_workers=0) return len(loader) class Dictionary: """ This class holds a dictionary that maps strings to IDs, used to generate one-hot encodings of strings. """ def __init__(self, add_unk=True): # init dictionaries self.item2idx: Dict[bytes, int] = {} self.idx2item: List[bytes] = [] self.add_unk = add_unk self.multi_label = False self.span_labels = False # in order to deal with unknown tokens, add <unk> if add_unk: self.add_item("<unk>") def remove_item(self, item: str): bytes_item = item.encode("utf-8") if bytes_item in self.item2idx: self.idx2item.remove(bytes_item) del self.item2idx[bytes_item] def add_item(self, item: str) -> int: """ add string - if already in dictionary returns its ID. if not in dictionary, it will get a new ID. :param item: a string for which to assign an id. :return: ID of string """ bytes_item = item.encode("utf-8") if bytes_item not in self.item2idx: self.idx2item.append(bytes_item) self.item2idx[bytes_item] = len(self.idx2item) - 1 return self.item2idx[bytes_item] def get_idx_for_item(self, item: str) -> int: """ returns the ID of the string, otherwise 0 :param item: string for which ID is requested :return: ID of string, otherwise 0 """ item_encoded = item.encode("utf-8") if item_encoded in self.item2idx.keys(): return self.item2idx[item_encoded] elif self.add_unk: return 0 else: log.error(f"The string '{item}' is not in dictionary! Dictionary contains only: {self.get_items()}") log.error( "You can create a Dictionary that handles unknown items with an <unk>-key by setting add_unk = True in the construction." ) raise IndexError def get_idx_for_items(self, items: List[str]) -> List[int]: """ returns the IDs for each item of the list of string, otherwise 0 if not found :param items: List of string for which IDs are requested :return: List of ID of strings """ if not hasattr(self, "item2idx_not_encoded"): d = dict([(key.decode("UTF-8"), value) for key, value in self.item2idx.items()]) self.item2idx_not_encoded = defaultdict(int, d) if not items: return [] results = itemgetter(*items)(self.item2idx_not_encoded) if isinstance(results, int): return [results] return list(results) def get_items(self) -> List[str]: items = [] for item in self.idx2item: items.append(item.decode("UTF-8")) return items def __len__(self) -> int: return len(self.idx2item) def get_item_for_index(self, idx): return self.idx2item[idx].decode("UTF-8") def set_start_stop_tags(self): self.add_item("<START>") self.add_item("<STOP>") def start_stop_tags_are_set(self): if {"<START>".encode(), "<STOP>".encode()}.issubset(self.item2idx.keys()): return True else: return False def save(self, savefile): import pickle with open(savefile, "wb") as f: mappings = {"idx2item": self.idx2item, "item2idx": self.item2idx} pickle.dump(mappings, f) def __setstate__(self, d): self.__dict__ = d # set 'add_unk' if the dictionary was created with a version of Flair older than 0.9 if "add_unk" not in self.__dict__.keys(): self.__dict__["add_unk"] = True if b"<unk>" in self.__dict__["idx2item"] else False @classmethod def load_from_file(cls, filename: Union[str, Path]): import pickle f = open(filename, "rb") mappings = pickle.load(f, encoding="latin1") idx2item = mappings["idx2item"] item2idx = mappings["item2idx"] f.close() # set 'add_unk' depending on whether <unk> is a key add_unk = True if b"<unk>" in idx2item else False dictionary: Dictionary = Dictionary(add_unk=add_unk) dictionary.item2idx = item2idx dictionary.idx2item = idx2item return dictionary @classmethod def load(cls, name: str): from flair.file_utils import cached_path hu_path: str = "https://flair.informatik.hu-berlin.de/resources/characters" if name == "chars" or name == "common-chars": char_dict = cached_path(f"{hu_path}/common_characters", cache_dir="datasets") return Dictionary.load_from_file(char_dict) if name == "chars-large" or name == "common-chars-large": char_dict = cached_path(f"{hu_path}/common_characters_large", cache_dir="datasets") return Dictionary.load_from_file(char_dict) if name == "chars-xl" or name == "common-chars-xl": char_dict = cached_path(f"{hu_path}/common_characters_xl", cache_dir="datasets") return Dictionary.load_from_file(char_dict) if name == "chars-lemmatizer" or name == "common-chars-lemmatizer": char_dict = cached_path(f"{hu_path}/common_characters_lemmatizer", cache_dir="datasets") return Dictionary.load_from_file(char_dict) return Dictionary.load_from_file(name) def __eq__(self, o: object) -> bool: if not isinstance(o, Dictionary): return False return self.item2idx == o.item2idx and self.idx2item == o.idx2item and self.add_unk == o.add_unk def __str__(self): tags = ", ".join(self.get_item_for_index(i) for i in range(min(len(self), 50))) return f"Dictionary with {len(self)} tags: {tags}" class Label: """ This class represents a label. Each label has a value and optionally a confidence score. The score needs to be between 0.0 and 1.0. Default value for the score is 1.0. """ def __init__(self, value: Optional[str], score: float = 1.0): self._value = value self._score = score super().__init__() def set_value(self, value: str, score: float = 1.0): self.value = value self.score = score def spawn(self, value: str, score: float = 1.0): return Label(value, score) @property def value(self): return self._value @value.setter def value(self, value): if not value and value != "": raise ValueError("Incorrect label value provided. Label value needs to be set.") else: self._value = value @property def score(self): return self._score @score.setter def score(self, score): self._score = score def to_dict(self): return {"value": self.value, "confidence": self.score} def __str__(self): return f"{self._value} ({round(self._score, 4)})" def __repr__(self): return f"{self._value} ({round(self._score, 4)})" def __eq__(self, other): return self.value == other.value and self.score == other.score @property def identifier(self): return "" class SpanLabel(Label): def __init__(self, span, value: Optional[str], score: float = 1.0): super().__init__(value, score) self.span = span def spawn(self, value: str, score: float = 1.0): return SpanLabel(self.span, value, score) def to_dict(self): return {"span": self.span, "value": self.value, "confidence": self.score} def __str__(self): return f"{self._value} [{self.span.id_text}] ({round(self._score, 4)})" def __repr__(self): return f"{self._value} [{self.span.id_text}] ({round(self._score, 4)})" def __hash__(self): return hash(self.__repr__()) def __len__(self): return len(self.span) def __eq__(self, other): return self.value == other.value and self.score == other.score and self.span.id_text == other.span.id_text @property def identifier(self): return f"{self.span.id_text}" class RelationLabel(Label): def __init__(self, head, tail, value: Optional[str], score: float = 1.0): super().__init__(value, score) self.head = head self.tail = tail def spawn(self, value: str, score: float = 1.0): return RelationLabel(self.head, self.tail, value, score) def __str__(self): return f"{self._value} [{self.head.id_text} -> {self.tail.id_text}] ({round(self._score, 4)})" def __repr__(self): return f"{self._value} from {self.head.id_text} -> {self.tail.id_text} ({round(self._score, 4)})" def __len__(self): return len(self.head) + len(self.tail) def __eq__(self, other): return ( self.value == other.value and self.score == other.score and self.head.id_text == other.head.id_text and self.tail.id_text == other.tail.id_text ) @property def identifier(self): return f"{self.head.id_text} -> {self.tail.id_text}" class EntityLinkingLabel(Label): def __init__(self, span, cui, concept_name, ontology = None, score: float = 1): super().__init__(cui, score) self.span = span self.ontology = ontology self.concept_name = concept_name def spawn(self, value: str, score: float = 1): return EntityLinkingLabel(self.span, value, self.ontology, self.concept_name, score) def __str__(self): return f"{self._value} {self.concept_name} [{self.span}] ({round(self._score, 4)})" def __repr__(self): return f"{self._value} {self.concept_name} [{self.span}] ({round(self._score, 4)})" def __len__(self): return len(self.span) def __eq__(self, other): return ( self.value == other.value and self.span.id_text == other.span.id_text and self.concept_name == other.concept_name and self.ontology == other.ontology and self.score == other.score ) @property def identifier(self): return f"{self.cui}" class DataPoint: """ This is the parent class of all data points in Flair (including Token, Sentence, Image, etc.). Each DataPoint must be embeddable (hence the abstract property embedding() and methods to() and clear_embeddings()). Also, each DataPoint may have Labels in several layers of annotation (hence the functions add_label(), get_labels() and the property 'label') """ def __init__(self): self.annotation_layers = {} self._embeddings: Dict[str, torch.Tensor] = {} @property @abstractmethod def embedding(self): pass def set_embedding(self, name: str, vector: torch.Tensor): self._embeddings[name] = vector def get_embedding(self, names: Optional[List[str]] = None) -> torch.Tensor: embeddings = self.get_each_embedding(names) if embeddings: return torch.cat(embeddings, dim=0) return torch.tensor([], device=flair.device) def get_each_embedding(self, embedding_names: Optional[List[str]] = None) -> List[torch.Tensor]: embeddings = [] for embed_name in sorted(self._embeddings.keys()): if embedding_names and embed_name not in embedding_names: continue embed = self._embeddings[embed_name].to(flair.device) embeddings.append(embed) return embeddings def to(self, device: str, pin_memory: bool = False): for name, vector in self._embeddings.items(): if str(vector.device) != str(device): if pin_memory: self._embeddings[name] = vector.to(device, non_blocking=True).pin_memory() else: self._embeddings[name] = vector.to(device, non_blocking=True) def clear_embeddings(self, embedding_names: List[str] = None): if embedding_names is None: self._embeddings = {} else: for name in embedding_names: if name in self._embeddings.keys(): del self._embeddings[name] def add_label(self, typename: str, value: str, score: float = 1.0): if typename not in self.annotation_layers: self.annotation_layers[typename] = [Label(value, score)] else: self.annotation_layers[typename].append(Label(value, score)) return self def add_complex_label(self, typename: str, label: Label): if typename in self.annotation_layers and label in self.annotation_layers[typename]: return self if typename not in self.annotation_layers: self.annotation_layers[typename] = [label] else: self.annotation_layers[typename].append(label) return self def set_label(self, typename: str, value: str, score: float = 1.0): self.annotation_layers[typename] = [Label(value, score)] return self def remove_labels(self, typename: str): if typename in self.annotation_layers.keys(): del self.annotation_layers[typename] def get_labels(self, typename: str = None): if typename is None: return self.labels return self.annotation_layers[typename] if typename in self.annotation_layers else [] @property def labels(self) -> List[Label]: all_labels = [] for key in self.annotation_layers.keys(): all_labels.extend(self.annotation_layers[key]) return all_labels DT = typing.TypeVar("DT", bound=DataPoint) DT2 = typing.TypeVar("DT2", bound=DataPoint) class Token(DataPoint): """ This class represents one word in a tokenized sentence. Each token may have any number of tags. It may also point to its head in a dependency tree. """ def __init__( self, text: str, idx: int = None, head_id: int = None, whitespace_after: bool = True, start_position: int = None, ): super().__init__() self.text: str = text self.idx: Optional[int] = idx self.head_id: Optional[int] = head_id self.whitespace_after: bool = whitespace_after self.start_pos = start_position self.end_pos = start_position + len(text) if start_position is not None else None self.sentence: Optional[Sentence] = None self._embeddings: Dict = {} self.tags_proba_dist: Dict[str, List[Label]] = {} def add_tag_label(self, tag_type: str, tag: Label): self.set_label(tag_type, tag.value, tag.score) def add_tags_proba_dist(self, tag_type: str, tags: List[Label]): self.tags_proba_dist[tag_type] = tags def add_tag(self, tag_type: str, tag_value: str, confidence=1.0): self.set_label(tag_type, tag_value, confidence) def get_tag(self, label_type, zero_tag_value=""): if len(self.get_labels(label_type)) == 0: return Label(zero_tag_value) return self.get_labels(label_type)[0] def get_tags_proba_dist(self, tag_type: str) -> List[Label]: if tag_type in self.tags_proba_dist: return self.tags_proba_dist[tag_type] return [] def get_head(self): return self.sentence.get_token(self.head_id) @property def start_position(self) -> Optional[int]: return self.start_pos @property def end_position(self) -> Optional[int]: return self.end_pos @property def embedding(self): return self.get_embedding() def __str__(self) -> str: return "Token: {} {}".format(self.idx, self.text) if self.idx is not None else "Token: {}".format(self.text) def __repr__(self) -> str: return "Token: {} {}".format(self.idx, self.text) if self.idx is not None else "Token: {}".format(self.text) class Span(DataPoint): """ This class represents one textual span consisting of Tokens. """ def __init__(self, tokens: List[Token]): super().__init__() self.tokens = tokens @property def start_pos(self) -> int: assert self.tokens[0].start_position is not None return self.tokens[0].start_position @property def end_pos(self) -> int: assert self.tokens[-1].end_position is not None return self.tokens[-1].end_position @property def text(self) -> str: return " ".join([t.text for t in self.tokens]) def to_original_text(self) -> str: pos = self.tokens[0].start_pos if pos is None: return " ".join([t.text for t in self.tokens]) str = "" for t in self.tokens: if t.start_pos is None: return " ".join([t.text for t in self.tokens]) while t.start_pos > pos: str += " " pos += 1 str += t.text pos += len(t.text) return str def to_plain_string(self): plain = "" for token in self.tokens: plain += token.text if token.whitespace_after: plain += " " return plain.rstrip() def __str__(self) -> str: ids = ",".join([str(t.idx) for t in self.tokens]) label_string = " ".join([str(label) for label in self.labels]) labels = f" [− Labels: {label_string}]" if self.labels else "" return 'Span [{}]: "{}"{}'.format(ids, self.text, labels) @property def id_text(self) -> str: return f"{' '.join([t.text for t in self.tokens])} ({','.join([str(t.idx) for t in self.tokens])})" def __repr__(self) -> str: ids = ",".join([str(t.idx) for t in self.tokens]) return ( '<{}-span ({}): "{}">'.format(self.tag, ids, self.text) if len(self.labels) > 0 else '<span ({}): "{}">'.format(ids, self.text) ) def __getitem__(self, idx: int) -> Token: return self.tokens[idx] def __iter__(self): return iter(self.tokens) def __len__(self) -> int: return len(self.tokens) @property def tag(self): return self.labels[0].value @property def score(self): return self.labels[0].score @property def position_string(self): return "-".join([str(token.idx) for token in self]) @property def embedding(self): return torch.empty() def to(self, device: str, pin_memory: bool = False): pass def clear_embeddings(self, embedding_names: List[str] = None): pass def add_tag(self, tag_type: str, tag_value: str, confidence=1.0): assert self.tokens[0].sentence is not None self.tokens[0].sentence.add_complex_label(tag_type, SpanLabel(self, value=tag_value, score=confidence)) class Tokenizer(ABC): r"""An abstract class representing a :class:`Tokenizer`. Tokenizers are used to represent algorithms and models to split plain text into individual tokens / words. All subclasses should overwrite :meth:`tokenize`, which splits the given plain text into tokens. Moreover, subclasses may overwrite :meth:`name`, returning a unique identifier representing the tokenizer's configuration. """ @abstractmethod def tokenize(self, text: str) -> List[Token]: raise NotImplementedError() @property def name(self) -> str: return self.__class__.__name__ class Sentence(DataPoint): """ A Sentence is a list of tokens and is used to represent a sentence or text fragment. """ def __init__( self, text: Union[str, List[str]] = [], use_tokenizer: Union[bool, Tokenizer, Callable] = True, language_code: str = None, start_position: int = None, ): """ Class to hold all meta related to a text (tokens, predictions, language code, ...) :param text: original string (sentence), or a list of string tokens (words) :param use_tokenizer: a custom tokenizer (default is :class:`SpaceTokenizer`) more advanced options are :class:`SegTokTokenizer` to use segtok or :class:`SpacyTokenizer` to use Spacy library if available). Check the implementations of abstract class Tokenizer or implement your own subclass (if you need it). If instead of providing a Tokenizer, this parameter is just set to True (deprecated), :class:`SegtokTokenizer` will be used. :param language_code: Language of the sentence :param start_position: Start char offset of the sentence in the superordinate document """ super().__init__() self.tokens: List[Token] = [] self.language_code: Optional[str] = language_code self.start_pos = start_position self.end_pos = start_position + len(text) if start_position is not None else None # the tokenizer used for this sentence if isinstance(use_tokenizer, Tokenizer): tokenizer = use_tokenizer elif callable(use_tokenizer): from flair.tokenization import TokenizerWrapper tokenizer = TokenizerWrapper(use_tokenizer) elif type(use_tokenizer) == bool: from flair.tokenization import SegtokTokenizer, SpaceTokenizer tokenizer = SegtokTokenizer() if use_tokenizer else SpaceTokenizer() else: raise AssertionError( "Unexpected type of parameter 'use_tokenizer'. " + "Parameter should be bool, Callable[[str], List[Token]] (deprecated), Tokenizer" ) # if text is passed, instantiate sentence with tokens (words) if isinstance(text, (list, tuple)): [self.add_token(self._restore_windows_1252_characters(token)) for token in text] else: text = self._restore_windows_1252_characters(text) [self.add_token(token) for token in tokenizer.tokenize(text)] # log a warning if the dataset is empty if text == "": log.warning("Warning: An empty Sentence was created! Are there empty strings in your dataset?") self.tokenized: Optional[str] = None # some sentences represent a document boundary (but most do not) self.is_document_boundary: bool = False # internal variables to denote position inside dataset self._previous_sentence: Optional[Sentence] = None self._next_sentence: Optional[Sentence] = None self._position_in_dataset: Optional[typing.Tuple[Dataset, int]] = None def get_token(self, token_id: int) -> Optional[Token]: for token in self.tokens: if token.idx == token_id: return token return None def add_token(self, token: Union[Token, str]): if type(token) is str: token = Token(token) token = cast(Token, token) token.text = token.text.replace("\u200c", "") token.text = token.text.replace("\u200b", "") token.text = token.text.replace("\ufe0f", "") token.text = token.text.replace("\ufeff", "") # data with zero-width characters cannot be handled if token.text == "": return self.tokens.append(token) # set token idx if not set token.sentence = self if token.idx is None: token.idx = len(self.tokens) def get_label_names(self): label_names = [] for label in self.labels: label_names.append(label.value) return label_names def _convert_span_labels(self, label_type: str, min_score=-1): current_span: List[Token] = [] tags: Dict[str, float] = defaultdict(lambda: 0.0) previous_tag_value: str = "O" for token in self: tag: Label = token.get_tag(label_type) tag_value = tag.value # non-set tags are OUT tags if tag_value == "" or tag_value == "O" or tag_value == "_": tag_value = "O-" # anything that is not a BIOES tag is a SINGLE tag if tag_value[0:2] not in ["B-", "I-", "O-", "E-", "S-"]: tag_value = "S-" + tag_value # anything that is not OUT is IN in_span = False if tag_value[0:2] not in ["O-"]: in_span = True # single and begin tags start a new span starts_new_span = False if tag_value[0:2] in ["B-", "S-"]: starts_new_span = True if previous_tag_value[0:2] in ["S-"] and previous_tag_value[2:] != tag_value[2:] and in_span: starts_new_span = True if (starts_new_span or not in_span) and len(current_span) > 0: scores = [t.get_labels(label_type)[0].score for t in current_span] span_score = sum(scores) / len(scores) if span_score > min_score: span = Span(current_span) value = sorted(tags.items(), key=lambda k_v: k_v[1], reverse=True)[0][0] self.add_complex_label( typename=label_type, label=SpanLabel(span=span, value=value, score=span_score), ) current_span = [] tags = defaultdict(lambda: 0.0) if in_span: current_span.append(token) weight = 1.1 if starts_new_span else 1.0 tags[tag_value[2:]] += weight # remember previous tag previous_tag_value = tag_value if len(current_span) > 0: scores = [t.get_labels(label_type)[0].score for t in current_span] span_score = sum(scores) / len(scores) if span_score > min_score: span = Span(current_span) value = sorted(tags.items(), key=lambda k_v: k_v[1], reverse=True)[0][0] self.add_complex_label( typename=label_type, label=SpanLabel(span=span, value=value, score=span_score), ) @property def embedding(self): return self.get_embedding() def to(self, device: str, pin_memory: bool = False): # move sentence embeddings to device super().to(device=device, pin_memory=pin_memory) # also move token embeddings to device for token in self: token.to(device, pin_memory) def clear_embeddings(self, embedding_names: List[str] = None): super().clear_embeddings(embedding_names) # clear token embeddings for token in self: token.clear_embeddings(embedding_names) @lru_cache(maxsize=1) # cache last context, as training repeats calls def left_context(self, context_length: int, respect_document_boundaries: bool = True): sentence = self left_context: List[str] = [] while True: sentence = sentence.previous_sentence() if sentence is None: break if respect_document_boundaries and sentence.is_document_boundary: break left_context = [t.text for t in sentence.tokens] + left_context if len(left_context) > context_length: left_context = left_context[-context_length:] break return left_context @lru_cache(maxsize=1) # cache last context, as training repeats calls def right_context(self, context_length: int, respect_document_boundaries: bool = True): sentence = self right_context: List[str] = [] while True: sentence = sentence.next_sentence() if sentence is None: break if respect_document_boundaries and sentence.is_document_boundary: break right_context += [t.text for t in sentence.tokens] if len(right_context) > context_length: right_context = right_context[:context_length] break return right_context def to_tagged_string(self, main_tag=None) -> str: list = [] for token in self.tokens: list.append(token.text) tags: List[str] = [] for label_type in token.annotation_layers.keys(): if main_tag is not None and main_tag != label_type: continue if token.get_labels(label_type)[0].value == "O": continue if token.get_labels(label_type)[0].value == "_": continue tags.append(token.get_labels(label_type)[0].value) all_tags = "<" + "/".join(tags) + ">" if all_tags != "<>": list.append(all_tags) return " ".join(list) def to_tokenized_string(self) -> str: if self.tokenized is None: self.tokenized = " ".join([t.text for t in self.tokens]) return self.tokenized def to_plain_string(self): plain = "" for token in self.tokens: plain += token.text if token.whitespace_after: plain += " " return plain.rstrip() def infer_space_after(self): """ Heuristics in case you wish to infer whitespace_after values for tokenized text. This is useful for some old NLP tasks (such as CoNLL-03 and CoNLL-2000) that provide only tokenized data with no info of original whitespacing. :return: """ last_token = None quote_count: int = 0 # infer whitespace after field for token in self.tokens: if token.text == '"': quote_count += 1 if quote_count % 2 != 0: token.whitespace_after = False elif last_token is not None: last_token.whitespace_after = False if last_token is not None: if token.text in [".", ":", ",", ";", ")", "n't", "!", "?"]: last_token.whitespace_after = False if token.text.startswith("'"): last_token.whitespace_after = False if token.text in ["("]: token.whitespace_after = False last_token = token return self def to_original_text(self) -> str: str = "" pos = 0 for t in self.tokens: if t.start_pos is None: return self.to_tokenized_string() while t.start_pos > pos: str += " " pos += 1 str += t.text pos += len(t.text) return str def to_dict(self, tag_type: str = None): labels = [] if tag_type: labels = [label.to_dict() for label in self.get_labels(tag_type)] return {"text": self.to_original_text(), tag_type: labels} if self.labels: labels = [label.to_dict() for label in self.labels] return {"text": self.to_original_text(), "all labels": labels} @typing.overload def __getitem__(self, idx: int) -> Token: ... @typing.overload def __getitem__(self, s: slice) -> Span: ... def __getitem__(self, subscript): if isinstance(subscript, slice): return Span(self.tokens[subscript]) else: return self.tokens[subscript] def __iter__(self): return iter(self.tokens) def __len__(self) -> int: return len(self.tokens) def __repr__(self): tagged_string = self.to_tagged_string() tokenized_string = self.to_tokenized_string() # add Sentence labels to output if they exist sentence_labels = f" − Sentence-Labels: {self.annotation_layers}" if self.annotation_layers != {} else "" # add Token labels to output if they exist token_labels = f' − Token-Labels: "{tagged_string}"' if tokenized_string != tagged_string else "" return f'Sentence: "{tokenized_string}" [− Tokens: {len(self)}{token_labels}{sentence_labels}]' def __copy__(self): s = Sentence() for token in self.tokens: nt = Token(token.text) for tag_type in token.tags: nt.add_label( tag_type, token.get_tag(tag_type).value, token.get_tag(tag_type).score, ) s.add_token(nt) return s def __str__(self) -> str: tagged_string = self.to_tagged_string() tokenized_string = self.to_tokenized_string() # add Sentence labels to output if they exist sentence_labels = f" − Sentence-Labels: {self.annotation_layers}" if self.annotation_layers != {} else "" # add Token labels to output if they exist token_labels = f' − Token-Labels: "{tagged_string}"' if tokenized_string != tagged_string else "" return f'Sentence: "{tokenized_string}" [− Tokens: {len(self)}{token_labels}{sentence_labels}]' def get_language_code(self) -> str: if self.language_code is None: import langdetect try: self.language_code = langdetect.detect(self.to_plain_string()) except Exception: self.language_code = "en" return self.language_code @staticmethod def _restore_windows_1252_characters(text: str) -> str: def to_windows_1252(match): try: return bytes([ord(match.group(0))]).decode("windows-1252") except UnicodeDecodeError: # No character at the corresponding code point: remove it return "" return re.sub(r"[\u0080-\u0099]", to_windows_1252, text) def next_sentence(self): """ Get the next sentence in the document (works only if context is set through dataloader or elsewhere) :return: next Sentence in document if set, otherwise None """ if self._next_sentence is not None: return self._next_sentence if self._position_in_dataset is not None: dataset = self._position_in_dataset[0] index = self._position_in_dataset[1] + 1 if index < len(dataset): return dataset[index] return None def previous_sentence(self): """ Get the previous sentence in the document (works only if context is set through dataloader or elsewhere) :return: previous Sentence in document if set, otherwise None """ if self._previous_sentence is not None: return self._previous_sentence if self._position_in_dataset is not None: dataset = self._position_in_dataset[0] index = self._position_in_dataset[1] - 1 if index >= 0: return dataset[index] return None def is_context_set(self) -> bool: """ Return True or False depending on whether context is set (for instance in dataloader or elsewhere) :return: True if context is set, else False """ return self._previous_sentence is not None or self._position_in_dataset is not None def get_labels(self, label_type: str = None): # if no label if specified, return all labels if label_type is None: return self.labels # if the label type exists in the Sentence, return it if label_type in self.annotation_layers: return self.annotation_layers[label_type] # otherwise check if the label exists on the token-level # in this case, create span-labels and return those if label_type in set().union(*(token.annotation_layers.keys() for token in self)): return [ SpanLabel(Span([token]), token.get_tag(label_type).value, token.get_tag(label_type).score) for token in self if label_type in token.annotation_layers ] # return empty list if none of the above return [] class DataPair(DataPoint, typing.Generic[DT, DT2]): def __init__(self, first: DT, second: DT2): super().__init__() self.first = first self.second = second def to(self, device: str, pin_memory: bool = False): self.first.to(device, pin_memory) self.second.to(device, pin_memory) def clear_embeddings(self, embedding_names: List[str] = None): self.first.clear_embeddings(embedding_names) self.second.clear_embeddings(embedding_names) @property def embedding(self): return torch.cat([self.first.embedding, self.second.embedding]) def __str__(self): return f"DataPair:\n − First {self.first}\n − Second {self.second}\n − Labels: {self.labels}" def to_plain_string(self): return f"DataPair: First {self.first} || Second {self.second}" def to_original_text(self): return f"{self.first.to_original_text()} || {self.second.to_original_text()}" def __len__(self): return len(self.first) + len(self.second) TextPair = DataPair[Sentence, Sentence] class Image(DataPoint): def __init__(self, data=None, imageURL=None): super().__init__() self.data = data self._embeddings: Dict = {} self.imageURL = imageURL @property def embedding(self): return self.get_embedding() def __str__(self): image_repr = self.data.size() if self.data else "" image_url = self.imageURL if self.imageURL else "" return f"Image: {image_repr} {image_url}" class FlairDataset(Dataset): @abstractmethod def is_in_memory(self) -> bool: pass class Corpus: def __init__( self, train: Dataset = None, dev: Dataset = None, test: Dataset = None, name: str = "corpus", sample_missing_splits: Union[bool, str] = True, ): # set name self.name: str = name # abort if no data is provided if not train and not dev and not test: raise RuntimeError("No data provided when initializing corpus object.") # sample test data from train if none is provided if test is None and sample_missing_splits and train and not sample_missing_splits == "only_dev": train_length = _len_dataset(train) test_size: int = round(train_length / 10) test, train = randomly_split_into_two_datasets(train, test_size) # sample dev data from train if none is provided if dev is None and sample_missing_splits and train and not sample_missing_splits == "only_test": train_length = _len_dataset(train) dev_size: int = round(train_length / 10) dev, train = randomly_split_into_two_datasets(train, dev_size) # set train dev and test data self._train: Optional[Dataset] = train self._test: Optional[Dataset] = test self._dev: Optional[Dataset] = dev @property def train(self) -> Optional[Dataset]: return self._train @property def dev(self) -> Optional[Dataset]: return self._dev @property def test(self) -> Optional[Dataset]: return self._test def downsample( self, percentage: float = 0.1, downsample_train=True, downsample_dev=True, downsample_test=True, ): if downsample_train and self._train is not None: self._train = self._downsample_to_proportion(self._train, percentage) if downsample_dev and self._dev is not None: self._dev = self._downsample_to_proportion(self._dev, percentage) if downsample_test and self._test is not None: self._test = self._downsample_to_proportion(self._test, percentage) return self def filter_empty_sentences(self): log.info("Filtering empty sentences") if self._train is not None: self._train = Corpus._filter_empty_sentences(self._train) if self._test is not None: self._test = Corpus._filter_empty_sentences(self._test) if self._dev is not None: self._dev = Corpus._filter_empty_sentences(self._dev) log.info(self) def filter_long_sentences(self, max_charlength: int): log.info("Filtering long sentences") if self._train is not None: self._train = Corpus._filter_long_sentences(self._train, max_charlength) if self._test is not None: self._test = Corpus._filter_long_sentences(self._test, max_charlength) if self._dev is not None: self._dev = Corpus._filter_long_sentences(self._dev, max_charlength) log.info(self) @staticmethod def _filter_long_sentences(dataset, max_charlength: int) -> Dataset: # find out empty sentence indices empty_sentence_indices = [] non_empty_sentence_indices = [] for index, sentence in Tqdm.tqdm(enumerate(_iter_dataset(dataset))): if len(sentence.to_plain_string()) > max_charlength: empty_sentence_indices.append(index) else: non_empty_sentence_indices.append(index) # create subset of non-empty sentence indices subset = Subset(dataset, non_empty_sentence_indices) return subset @staticmethod def _filter_empty_sentences(dataset) -> Dataset: # find out empty sentence indices empty_sentence_indices = [] non_empty_sentence_indices = [] for index, sentence in enumerate(_iter_dataset(dataset)): if len(sentence) == 0: empty_sentence_indices.append(index) else: non_empty_sentence_indices.append(index) # create subset of non-empty sentence indices subset = Subset(dataset, non_empty_sentence_indices) return subset def make_vocab_dictionary(self, max_tokens=-1, min_freq=1) -> Dictionary: """ Creates a dictionary of all tokens contained in the corpus. By defining `max_tokens` you can set the maximum number of tokens that should be contained in the dictionary. If there are more than `max_tokens` tokens in the corpus, the most frequent tokens are added first. If `min_freq` is set the a value greater than 1 only tokens occurring more than `min_freq` times are considered to be added to the dictionary. :param max_tokens: the maximum number of tokens that should be added to the dictionary (-1 = take all tokens) :param min_freq: a token needs to occur at least `min_freq` times to be added to the dictionary (-1 = there is no limitation) :return: dictionary of tokens """ tokens = self._get_most_common_tokens(max_tokens, min_freq) vocab_dictionary: Dictionary = Dictionary() for token in tokens: vocab_dictionary.add_item(token) return vocab_dictionary def _get_most_common_tokens(self, max_tokens, min_freq) -> List[str]: tokens_and_frequencies = Counter(self._get_all_tokens()) tokens: List[str] = [] for token, freq in tokens_and_frequencies.most_common(): if (min_freq != -1 and freq < min_freq) or (max_tokens != -1 and len(tokens) == max_tokens): break tokens.append(token) return tokens def _get_all_tokens(self) -> List[str]: assert self.train tokens = list(map((lambda s: s.tokens), _iter_dataset(self.train))) tokens = [token for sublist in tokens for token in sublist] return list(map((lambda t: t.text), tokens)) @staticmethod def _downsample_to_proportion(dataset: Dataset, proportion: float): sampled_size: int = round(_len_dataset(dataset) * proportion) splits = randomly_split_into_two_datasets(dataset, sampled_size) return splits[0] def obtain_statistics(self, label_type: str = None, pretty_print: bool = True) -> Union[dict, str]: """ Print statistics about the class distribution (only labels of sentences are taken into account) and sentence sizes. """ json_data = { "TRAIN": self._obtain_statistics_for(self.train, "TRAIN", label_type), "TEST": self._obtain_statistics_for(self.test, "TEST", label_type), "DEV": self._obtain_statistics_for(self.dev, "DEV", label_type), } if pretty_print: import json return json.dumps(json_data, indent=4) return json_data @staticmethod def _obtain_statistics_for(sentences, name, tag_type) -> dict: if len(sentences) == 0: return {} classes_to_count = Corpus._count_sentence_labels(sentences) tags_to_count = Corpus._count_token_labels(sentences, tag_type) tokens_per_sentence = Corpus._get_tokens_per_sentence(sentences) label_size_dict = {} for label, c in classes_to_count.items(): label_size_dict[label] = c tag_size_dict = {} for tag, c in tags_to_count.items(): tag_size_dict[tag] = c return { "dataset": name, "total_number_of_documents": len(sentences), "number_of_documents_per_class": label_size_dict, "number_of_tokens_per_tag": tag_size_dict, "number_of_tokens": { "total": sum(tokens_per_sentence), "min": min(tokens_per_sentence), "max": max(tokens_per_sentence), "avg": sum(tokens_per_sentence) / len(sentences), }, } @staticmethod def _get_tokens_per_sentence(sentences): return list(map(lambda x: len(x.tokens), sentences)) @staticmethod def _count_sentence_labels(sentences): label_count = defaultdict(lambda: 0) for sent in sentences: for label in sent.labels: label_count[label.value] += 1 return label_count @staticmethod def _count_token_labels(sentences, label_type): label_count = defaultdict(lambda: 0) for sent in sentences: for token in sent.tokens: if label_type in token.annotation_layers.keys(): label = token.get_tag(label_type) label_count[label.value] += 1 return label_count def __str__(self) -> str: return "Corpus: %d train + %d dev + %d test sentences" % ( _len_dataset(self.train) if self.train else 0, _len_dataset(self.dev) if self.dev else 0, _len_dataset(self.test) if self.test else 0, ) def make_label_dictionary(self, label_type: str, min_count: int = -1) -> Dictionary: """ Creates a dictionary of all labels assigned to the sentences in the corpus. :return: dictionary of labels """ label_dictionary: Dictionary = Dictionary(add_unk=True) label_dictionary.span_labels = False assert self.train datasets = [self.train] data: ConcatDataset = ConcatDataset(datasets) log.info("Computing label dictionary. Progress:") all_label_types: typing.Counter[str] = Counter() label_occurrence: typing.Counter[str] = Counter() all_sentence_labels: List[str] = [] for sentence in Tqdm.tqdm(_iter_dataset(data)): # check if sentence itself has labels labels = sentence.get_labels(label_type) all_label_types.update(sentence.annotation_layers.keys()) # go through all labels and increment count for label in labels: if label.value not in all_sentence_labels: label_occurrence[label.value] += 1 # check if there are any span labels if type(label) == SpanLabel and len(label.span) > 1: label_dictionary.span_labels = True if not label_dictionary.multi_label: if len(labels) > 1: label_dictionary.multi_label = True erfasst_count = 0 unked_count = 0 for label, count in label_occurrence.most_common(): if count >= min_count: label_dictionary.add_item(label) erfasst_count += count else: unked_count += count if len(label_dictionary.idx2item) == 0: log.error( f"Corpus contains only the labels: {', '.join([f'{label[0]} (#{label[1]})' for label in all_label_types.most_common()])}" ) log.error(f"You specified as label_type='{label_type}' which is not in this dataset!") raise Exception log.info( f"Corpus contains the labels: {', '.join([label[0] + f' (#{label[1]})' for label in all_label_types.most_common()])}" ) log.info(f"{erfasst_count} instances in dict, {unked_count} instances are UNK'ed") log.info(f"Most commonly observed '{label_type}'-labels are {label_occurrence.most_common(20)}") log.info(f"Created (for label '{label_type}') {label_dictionary}") return label_dictionary def get_label_distribution(self): class_to_count = defaultdict(lambda: 0) for sent in self.train: for label in sent.labels: class_to_count[label.value] += 1 return class_to_count def get_all_sentences(self) -> ConcatDataset: parts = [] if self.train: parts.append(self.train) if self.dev: parts.append(self.dev) if self.test: parts.append(self.test) return ConcatDataset(parts) @deprecated(version="0.8", reason="Use 'make_label_dictionary' instead.") def make_tag_dictionary(self, tag_type: str) -> Dictionary: # Make the tag dictionary tag_dictionary: Dictionary = Dictionary(add_unk=False) tag_dictionary.add_item("O") for sentence in _iter_dataset(self.get_all_sentences()): for token in sentence.tokens: tag_dictionary.add_item(token.get_tag(tag_type).value) tag_dictionary.add_item("<START>") tag_dictionary.add_item("<STOP>") return tag_dictionary class MultiCorpus(Corpus): def __init__(self, corpora: List[Corpus], name: str = "multicorpus", **corpusargs): self.corpora: List[Corpus] = corpora train_parts = [] dev_parts = [] test_parts = [] for corpus in self.corpora: if corpus.train: train_parts.append(corpus.train) if corpus.dev: dev_parts.append(corpus.dev) if corpus.test: test_parts.append(corpus.test) super(MultiCorpus, self).__init__( ConcatDataset(train_parts) if len(train_parts) > 0 else None, ConcatDataset(dev_parts) if len(dev_parts) > 0 else None, ConcatDataset(test_parts) if len(test_parts) > 0 else None, name=name, **corpusargs, ) def __str__(self): output = ( f"MultiCorpus: " f"{len(self.train) if self.train else 0} train + " f"{len(self.dev) if self.dev else 0} dev + " f"{len(self.test) if self.test else 0} test sentences\n - " ) output += "\n - ".join([f"{type(corpus).__name__} {str(corpus)} - {corpus.name}" for corpus in self.corpora]) return output def iob2(tags): """ Check that tags have a valid IOB format. Tags in IOB1 format are converted to IOB2. """ for i, tag in enumerate(tags): if tag.value == "O": continue split = tag.value.split("-") if len(split) != 2 or split[0] not in ["I", "B"]: return False if split[0] == "B": continue elif i == 0 or tags[i - 1].value == "O": # conversion IOB1 to IOB2 tags[i].value = "B" + tag.value[1:] elif tags[i - 1].value[1:] == tag.value[1:]: continue else: # conversion IOB1 to IOB2 tags[i].value = "B" + tag.value[1:] return True def iob_iobes(tags): """ IOB -> IOBES """ for i, tag in enumerate(tags): if tag.value == "O" or tag.value == "": tag.value = "O" continue t, label = tag.value.split("-", 1) if len(tags) == i + 1 or tags[i + 1].value == "O": next_same = False else: nt, next_label = tags[i + 1].value.split("-", 1) next_same = nt == "I" and next_label == label if t == "B": if not next_same: tag.value = tag.value.replace("B-", "S-") elif t == "I": if not next_same: tag.value = tag.value.replace("I-", "E-") else: raise Exception("Invalid IOB format!") def randomly_split_into_two_datasets(dataset, length_of_first): import random indices = [i for i in range(len(dataset))] random.shuffle(indices) first_dataset = indices[:length_of_first] second_dataset = indices[length_of_first:] first_dataset.sort() second_dataset.sort() return Subset(dataset, first_dataset), Subset(dataset, second_dataset)
# AUTOGENERATED! DO NOT EDIT! File to edit: notebooks/00_datasets.internals.mangadex.ipynb (unless otherwise specified). __all__ = ['MangaDexClient', 'get_covers_for_all_tags'] # Cell import requests import json class MangaDexClient: """Client for the MangaDex API""" def __init__(self, credentials_file): with open(credentials_file) as config_file: data = config_file.read() response = requests.post( "https://api.mangadex.org/auth/login", json=json.loads(data) ) content = json.loads(response.content) self.refresh_token = content["token"]["refresh"] self.session_token = content["token"]["session"] def get_manga_tags(self): """Returns a dict from human readable tag names to tag_ids for each tag in the mangadex database""" response = requests.get( "https://api.mangadex.org/manga/tag", headers={ "Authorization": f"Bearer {self.session_token}", }, ) content = json.loads(response.content) return { item["data"]["attributes"]["name"]["en"]: item["data"]["id"] for item in content } def search_manga_tags_covers( self, total=None, limit=100, offset=0, includedTags=None, excludedTags=None ): """Gets a list of manga with id, tags and cover image filenames""" contents = [] while total is None or offset < total: response = requests.get( "https://api.mangadex.org/manga", params={ "limit": limit if not total else min(limit, total - offset), "offset": offset, "includedTags[]": includedTags, "excludedTags[]": excludedTags, "includes[]": "cover_art", }, headers={ "Authorization": f"Bearer {self.session_token}", }, ) content = json.loads(response.content) if not total: total = content["total"] contents.append(content) offset += limit return [ { "mangaId": result["data"]["id"], "tags": [ tag["attributes"]["name"]["en"] for tag in result["data"]["attributes"]["tags"] ], "cover_art_filenames": [ relationship["attributes"]["fileName"] for relationship in result["relationships"] if relationship["type"] == "cover_art" ], } for content in contents for result in content["results"] ] # Cell import pandas as pd from tqdm.auto import tqdm def get_covers_for_all_tags(num_mangas=20): """Returns a pandas DataFrame with covers image urls for each tag in the MangaDex database. It may be possible for a manga to show up in the query for multiple different tags, so we deduplicate those cases. TODO: There seems to be an issue with the API where only one cover image is returned for each manga. We need to investigate this further, so we do not run into the issue of having too much data to handle unexpectedly if this behavior changes suddenly. """ try: client = MangaDexClient('credentials.json') except FileNotFoundError as e: e.strerror = "The current version expects a credentials.json file at cwd." raise e tags = client.get_manga_tags() mangas = [ manga for _, tag_id in tqdm(tags.items()) for manga in client.search_manga_tags_covers(total=num_mangas, includedTags=[tag_id]) ] # Deduplicate mangas in list by mangaId seen = set() mangas = [ seen.add(manga["mangaId"]) or manga for manga in mangas if manga["mangaId"] not in seen ] return pd.DataFrame( [ { "mangaId": manga["mangaId"], "url": f'https://uploads.mangadex.org/covers/{manga['mangaId']}/{filename}', "filename": f'{manga['mangaId']}_{filename}', "tags": "|".join(manga["tags"]), } for manga in mangas for filename in manga["cover_art_filenames"] ] )
# AUTOGENERATED! DO NOT EDIT! File to edit: notebooks/00_datasets.internals.mangadex.ipynb (unless otherwise specified). __all__ = ['MangaDexClient', 'get_covers_for_all_tags'] # Cell import requests import json class MangaDexClient: """Client for the MangaDex API""" def __init__(self, credentials_file): with open(credentials_file) as config_file: data = config_file.read() response = requests.post( "https://api.mangadex.org/auth/login", json=json.loads(data) ) content = json.loads(response.content) self.refresh_token = content["token"]["refresh"] self.session_token = content["token"]["session"] def get_manga_tags(self): """Returns a dict from human readable tag names to tag_ids for each tag in the mangadex database""" response = requests.get( "https://api.mangadex.org/manga/tag", headers={ "Authorization": f"Bearer {self.session_token}", }, ) content = json.loads(response.content) return { item["data"]["attributes"]["name"]["en"]: item["data"]["id"] for item in content } def search_manga_tags_covers( self, total=None, limit=100, offset=0, includedTags=None, excludedTags=None ): """Gets a list of manga with id, tags and cover image filenames""" contents = [] while total is None or offset < total: response = requests.get( "https://api.mangadex.org/manga", params={ "limit": limit if not total else min(limit, total - offset), "offset": offset, "includedTags[]": includedTags, "excludedTags[]": excludedTags, "includes[]": "cover_art", }, headers={ "Authorization": f"Bearer {self.session_token}", }, ) content = json.loads(response.content) if not total: total = content["total"] contents.append(content) offset += limit return [ { "mangaId": result["data"]["id"], "tags": [ tag["attributes"]["name"]["en"] for tag in result["data"]["attributes"]["tags"] ], "cover_art_filenames": [ relationship["attributes"]["fileName"] for relationship in result["relationships"] if relationship["type"] == "cover_art" ], } for content in contents for result in content["results"] ] # Cell import pandas as pd from tqdm.auto import tqdm def get_covers_for_all_tags(num_mangas=20): """Returns a pandas DataFrame with covers image urls for each tag in the MangaDex database. It may be possible for a manga to show up in the query for multiple different tags, so we deduplicate those cases. TODO: There seems to be an issue with the API where only one cover image is returned for each manga. We need to investigate this further, so we do not run into the issue of having too much data to handle unexpectedly if this behavior changes suddenly. """ try: client = MangaDexClient('credentials.json') except FileNotFoundError as e: e.strerror = "The current version expects a credentials.json file at cwd." raise e tags = client.get_manga_tags() mangas = [ manga for _, tag_id in tqdm(tags.items()) for manga in client.search_manga_tags_covers(total=num_mangas, includedTags=[tag_id]) ] # Deduplicate mangas in list by mangaId seen = set() mangas = [ seen.add(manga["mangaId"]) or manga for manga in mangas if manga["mangaId"] not in seen ] return pd.DataFrame( [ { "mangaId": manga["mangaId"], "url": f'https://uploads.mangadex.org/covers/{manga["mangaId"]}/{filename}', "filename": f'{manga["mangaId"]}_{filename}', "tags": "|".join(manga["tags"]), } for manga in mangas for filename in manga["cover_art_filenames"] ] )
#!/usr/bin/env python # coding=utf-8 # Copyright 2021 The HuggingFace Inc. 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 """ Fine-tuning a 🤗 Transformers CTC model for automatic speech recognition""" import functools import json import logging import os import re import sys from dataclasses import dataclass, field from typing import Dict, List, Optional, Union import datasets import numpy as np import torch from datasets import DatasetDict, load_dataset, load_metric import transformers from transformers import ( AutoConfig, AutoFeatureExtractor, AutoModelForCTC, AutoTokenizer, HfArgumentParser, Trainer, TrainingArguments, Wav2Vec2Processor, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process from transformers.utils import check_min_version from transformers.utils.versions import require_version # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.13.0.dev0") require_version("datasets>=1.13.3", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt") logger = logging.getLogger(__name__) def list_field(default=None, metadata=None): return field(default_factory=lambda: default, metadata=metadata) @dataclass class ModelArguments: """ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from. """ model_name_or_path: str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) cache_dir: Optional[str] = field( default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}, ) freeze_feature_extractor: Optional[bool] = field( default=True, metadata={"help": "Whether to freeze the feature extractor layers of the model."} ) attention_dropout: Optional[float] = field( default=0.0, metadata={"help": "The dropout ratio for the attention probabilities."} ) activation_dropout: Optional[float] = field( default=0.0, metadata={"help": "The dropout ratio for activations inside the fully connected layer."} ) feat_proj_dropout: Optional[float] = field( default=0.0, metadata={"help": "The dropout ratio for the projected features."} ) hidden_dropout: Optional[float] = field( default=0.0, metadata={ "help": "The dropout probability for all fully connected layers in the embeddings, encoder, and pooler." }, ) final_dropout: Optional[float] = field( default=0.0, metadata={"help": "The dropout probability for the final projection layer."}, ) mask_time_prob: Optional[float] = field( default=0.05, metadata={ "help": "Probability of each feature vector along the time axis to be chosen as the start of the vector" "span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature" "vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``." }, ) layerdrop: Optional[float] = field(default=0.0, metadata={"help": "The LayerDrop probability."}) ctc_loss_reduction: Optional[str] = field( default="mean", metadata={"help": "The way the ctc loss should be reduced. Should be one of 'mean' or 'sum'."} ) @dataclass class DataTrainingArguments: """ Arguments pertaining to what data we are going to input our model for training and eval. Using `HfArgumentParser` we can turn this class into argparse arguments to be able to specify them on the command line. """ dataset_name: str = field( metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) dataset_config_name: Optional[str] = field( default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) train_split_name: Optional[str] = field( default="train+validation", metadata={ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'" }, ) eval_split_name: Optional[str] = field( default="test", metadata={ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'" }, ) audio_column_name: Optional[str] = field( default="audio", metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"}, ) text_column_name: Optional[str] = field( default="text", metadata={"help": "The name of the dataset column containing the text data. Defaults to 'text'"}, ) overwrite_cache: bool = field( default=False, metadata={"help": "Overwrite the cached preprocessed datasets or not."} ) preprocessing_num_workers: Optional[int] = field( default=None, metadata={"help": "The number of processes to use for the preprocessing."}, ) max_train_samples: Optional[int] = field( default=None, metadata={ "help": "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." }, ) max_eval_samples: Optional[int] = field( default=None, metadata={ "help": "For debugging purposes or quicker training, truncate the number of validation examples to this " "value if set." }, ) chars_to_ignore: Optional[List[str]] = list_field( default=None, metadata={"help": "A list of characters to remove from the transcripts."}, ) max_duration_in_seconds: Optional[float] = field( default=20.0, metadata={ "help": "Truncate audio files that are longer than `max_duration_in_seconds` seconds to 'max_duration_in_seconds`" }, ) min_duration_in_seconds: Optional[float] = field( default=0.0, metadata={"help": "Filter audio files that are shorter than `min_duration_in_seconds` seconds"} ) preprocessing_only: Optional[bool] = field( default=False, metadata={ "help": "Whether to only do data preprocessing and skip training. " "This is especially useful when data preprocessing errors out in distributed training due to timeout. " "In this case, one should run the preprocessing in a non-distributed setup with `preprocessing_only=True` " "so that the cached datasets can consequently be loaded in distributed training" }, ) use_auth_token: Optional[bool] = field( default=False, metadata={ "help": "If :obj:`True`, will use the token generated when running" ":obj:`transformers-cli logiin as HTTP bearer authorization for remote files." }, ) @dataclass class DataCollatorCTCWithPadding: """ Data collator that will dynamically pad the inputs received. Args: processor (:class:`~transformers.Wav2Vec2Processor`) The processor used for proccessing the data. padding (:obj:`bool`, :obj:`str` or :class:`~transformers.tokenization_utils_base.PaddingStrategy`, `optional`, defaults to :obj:`True`): Select a strategy to pad the returned sequences (according to the model's padding side and padding index) among: * :obj:`True` or :obj:`'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided). * :obj:`'max_length'`: Pad to a maximum length specified with the argument :obj:`max_length` or to the maximum acceptable input length for the model if that argument is not provided. * :obj:`False` or :obj:`'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different lengths). max_length (:obj:`int`, `optional`): Maximum length of the ``input_values`` of the returned list and optionally padding length (see above). max_length_labels (:obj:`int`, `optional`): Maximum length of the ``labels`` returned list and optionally padding length (see above). pad_to_multiple_of (:obj:`int`, `optional`): If set will pad the sequence to a multiple of the provided value. This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >= 7.5 (Volta). """ processor: Wav2Vec2Processor padding: Union[bool, str] = "longest" pad_to_multiple_of: Optional[int] = None pad_to_multiple_of_labels: Optional[int] = None def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]: # split inputs and labels since they have to be of different lenghts and need # different padding methods input_features = [{"input_values": feature["input_values"]} for feature in features] label_features = [{"input_ids": feature["labels"]} for feature in features] batch = self.processor.pad( input_features, padding=self.padding, pad_to_multiple_of=self.pad_to_multiple_of, return_tensors="pt", ) with self.processor.as_target_processor(): labels_batch = self.processor.pad( label_features, padding=self.padding, pad_to_multiple_of=self.pad_to_multiple_of_labels, return_tensors="pt", ) # replace padding with -100 to ignore loss correctly labels = labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1), -100) batch["labels"] = labels return batch def create_vocabulary_from_data(datasets: DatasetDict): # Given training and test labels create vocabulary def extract_all_chars(batch): all_text = " ".join(batch["target_text"]) vocab = list(set(all_text)) return {"vocab": [vocab], "all_text": [all_text]} vocabs = datasets.map( extract_all_chars, batched=True, batch_size=-1, keep_in_memory=True, remove_columns=datasets["train"].column_names, ) # take union of all unique characters in each dataset vocab_set = functools.reduce( lambda vocab_1, vocab_2: set(vocab_1["vocab"][0]) | set(vocab_2["vocab"][0]), vocabs.values() ) vocab_dict = {v: k for k, v in enumerate(sorted(list(vocab_set)))} # replace white space with delimiter token vocab_dict["|"] = vocab_dict[" "] del vocab_dict[" "] # add unk and pad token vocab_dict["[UNK]"] = len(vocab_dict) vocab_dict["[PAD]"] = len(vocab_dict) return vocab_dict def main(): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: model_args, data_args, training_args = parser.parse_args_into_dataclasses() # Detecting last checkpoint. last_checkpoint = None if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir: last_checkpoint = get_last_checkpoint(training_args.output_dir) if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. " "Use --overwrite_output_dir to overcome." ) elif last_checkpoint is not None: logger.info( f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", handlers=[logging.StreamHandler(sys.stdout)], ) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN) # Log on each process the small summary: logger.warning( f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}" f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}" ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank): transformers.utils.logging.set_verbosity_info() logger.info("Training/evaluation parameters %s", training_args) # Set seed before initializing model. set_seed(training_args.seed) # 1. First, let's load the dataset raw_datasets = DatasetDict() raw_datasets["train"] = load_dataset( data_args.dataset_name, data_args.dataset_config_name, split=data_args.train_split_name ) raw_datasets["eval"] = load_dataset( data_args.dataset_name, data_args.dataset_config_name, split=data_args.eval_split_name ) if data_args.audio_column_name not in raw_datasets["train"].column_names: raise ValueError( f"--audio_column_name '{data_args.audio_column_name}' not found in dataset '{data_args.dataset_name}'. " "Make sure to set `--audio_column_name` to the correct audio column - one of " f"{", ".join(raw_datasets["train"].column_names)}." ) if data_args.text_column_name not in raw_datasets["train"].column_names: raise ValueError( f"--text_column_name {data_args.text_column_name} not found in dataset '{data_args.dataset_name}'. " "Make sure to set `--text_column_name` to the correct text column - one of " f"{", ".join(raw_datasets["train"].column_names)}." ) # prepare dataset if data_args.max_train_samples is not None: raw_datasets["train"] = raw_datasets["train"].select(range(data_args.max_train_samples)) if data_args.max_eval_samples is not None: raw_datasets["eval"] = raw_datasets["eval"].select(range(data_args.max_eval_samples)) # 2. We remove some special characters from the datasets # that make training complicated and do not help in transcribing the speech # E.g. characters, such as `,` and `.` do not really have an acoustic characteristic # that could be easily picked up by the model chars_to_ignore_regex = ( f'[{''.join(data_args.chars_to_ignore)}]' if data_args.chars_to_ignore is not None else None ) def remove_special_characters(batch): if chars_to_ignore_regex is not None: batch["target_text"] = re.sub(chars_to_ignore_regex, "", batch[data_args.text_column_name]).lower() + " " else: batch["target_text"] = batch[data_args.text_column_name].lower() + " " return batch with training_args.main_process_first(desc="dataset map special characters removal"): raw_datasets = raw_datasets.map( remove_special_characters, remove_columns=[data_args.text_column_name], desc="remove special characters from datasets", ) # 3. Next, we create the vocabulary of the model by extracting all unique characters from # the training and evaluation datasets # We need to make sure that only first rank saves vocabulary # make sure all processes wait until vocab is created vocab_file = os.path.join(training_args.output_dir, "vocab.json") with training_args.main_process_first(): if training_args.overwrite_output_dir and os.path.isfile(vocab_file): os.remove(vocab_file) with training_args.main_process_first(desc="dataset map vocabulary creation"): if not os.path.isfile(vocab_file): os.makedirs(training_args.output_dir, exist_ok=True) vocab_dict = create_vocabulary_from_data(raw_datasets) # save vocab dict to be loaded into tokenizer with open(vocab_file, "w") as file: json.dump(vocab_dict, file) # 4. Now we can instantiate the configuration, feature extractor, tokenizer and model # Note for distributed training, the .from_pretrained methods guarantee that only # one local process can concurrently download model & vocab. # load config config = AutoConfig.from_pretrained( model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_auth_token=data_args.use_auth_token ) # tokenizer is defined by `tokenizer_class` if present in config else by `model_type` config_for_tokenizer = config if config.tokenizer_class is not None else None tokenizer_type = config.model_type if config.tokenizer_class is None else None # load feature_extractor, tokenizer and create processor tokenizer = AutoTokenizer.from_pretrained( training_args.output_dir, config=config_for_tokenizer, tokenizer_type=tokenizer_type, unk_token="[UNK]", pad_token="[PAD]", word_delimiter_token="|", use_auth_token=data_args.use_auth_token, ) feature_extractor = AutoFeatureExtractor.from_pretrained( model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_auth_token=data_args.use_auth_token ) processor = Wav2Vec2Processor(feature_extractor=feature_extractor, tokenizer=tokenizer) # adapt config config.update( { "feat_proj_dropout": model_args.feat_proj_dropout, "attention_dropout": model_args.attention_dropout, "hidden_dropout": model_args.hidden_dropout, "final_dropout": model_args.final_dropout, "mask_time_prob": model_args.mask_time_prob, "gradient_checkpointing": training_args.gradient_checkpointing, "layerdrop": model_args.layerdrop, "ctc_loss_reduction": model_args.ctc_loss_reduction, "pad_token_id": processor.tokenizer.pad_token_id, "vocab_size": len(processor.tokenizer), "activation_dropout": model_args.activation_dropout, } ) # create model model = AutoModelForCTC.from_pretrained( model_args.model_name_or_path, cache_dir=model_args.cache_dir, config=config, use_auth_token=data_args.use_auth_token, ) # freeze encoder if model_args.freeze_feature_extractor: model.freeze_feature_extractor() # 5. Now we preprocess the datasets including loading the audio, resampling and normalization # Thankfully, `datasets` takes care of automatically loading and resampling the audio, # so that we just need to set the correct target sampling rate and normalize the input # via the `feature_extractor` # make sure that dataset decodes audio with correct sampling rate raw_datasets = raw_datasets.cast_column( data_args.audio_column_name, datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate) ) # derive max & min input length for sample rate & max duration max_input_length = data_args.max_duration_in_seconds * processor.feature_extractor.sampling_rate min_input_length = data_args.min_duration_in_seconds * processor.feature_extractor.sampling_rate # Preprocessing the datasets. # We need to read the audio files as arrays and tokenize the targets. def prepare_dataset(batch): # load audio sample = batch[data_args.audio_column_name] batch["input_values"] = processor( sample["array"], sampling_rate=sample["sampling_rate"], truncate=True, max_length=max_input_length ).input_values[0] batch["input_length"] = len(batch["input_values"]) # Setup the processor for targets with processor.as_target_processor(): batch["labels"] = processor(batch["target_text"]).input_ids return batch with training_args.main_process_first(desc="dataset map preprocessing"): vectorized_datasets = raw_datasets.map( prepare_dataset, remove_columns=raw_datasets["train"].column_names, num_proc=data_args.preprocessing_num_workers, desc="preprocess datasets", ) if min_input_length > 0.0: # filter data that is shorter than min_input_length vectorized_datasets = vectorized_datasets.filter( lambda x: x > min_input_length, num_proc=data_args.preprocessing_num_workers, input_columns=["input_length"], ) vectorized_datasets = vectorized_datasets.remove_columns("input_length") # 6. Next, we can prepare the training. # Let's use word error rate (WER) as our evaluation metric, # instantiate a data collator and the trainer # Define Metric during training wer_metric = load_metric("wer") # for large datasets it is advised to run the preprocessing on a # single machine first with ``args.preprocessing_only`` since there will mostly likely # be a timeout when running the script in distributed mode. # In a second step ``args.preprocessing_only`` can then be set to `False` to load the # cached dataset if data_args.preprocessing_only: logger.info(f"Data preprocessing finished. Files cached at {vectorized_datasets.cache_files}") return def compute_metrics(pred): pred_logits = pred.predictions pred_ids = np.argmax(pred_logits, axis=-1) pred.label_ids[pred.label_ids == -100] = processor.tokenizer.pad_token_id pred_str = processor.batch_decode(pred_ids) # we do not want to group tokens when computing the metrics label_str = processor.batch_decode(pred.label_ids, group_tokens=False) wer = wer_metric.compute(predictions=pred_str, references=label_str) return {"wer": wer} # Instantiate custom data collator data_collator = DataCollatorCTCWithPadding(processor=processor) # Initialize Trainer trainer = Trainer( model=model, data_collator=data_collator, args=training_args, compute_metrics=compute_metrics, train_dataset=vectorized_datasets["train"] if training_args.do_train else None, eval_dataset=vectorized_datasets["eval"] if training_args.do_eval else None, tokenizer=processor.feature_extractor, ) # 7. Finally, we can start training # Training if training_args.do_train: # use last checkpoint if exist if last_checkpoint is not None: checkpoint = last_checkpoint elif os.path.isdir(model_args.model_name_or_path): checkpoint = model_args.model_name_or_path else: checkpoint = None # Save the feature_extractor and the tokenizer if is_main_process(training_args.local_rank): processor.save_pretrained(training_args.output_dir) train_result = trainer.train(resume_from_checkpoint=checkpoint) trainer.save_model() metrics = train_result.metrics max_train_samples = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(vectorized_datasets["train"]) ) metrics["train_samples"] = min(max_train_samples, len(vectorized_datasets["train"])) trainer.log_metrics("train", metrics) trainer.save_metrics("train", metrics) trainer.save_state() # Evaluation results = {} if training_args.do_eval: logger.info("*** Evaluate ***") metrics = trainer.evaluate() max_eval_samples = ( data_args.max_eval_samples if data_args.max_eval_samples is not None else len(vectorized_datasets["eval"]) ) metrics["eval_samples"] = min(max_eval_samples, len(vectorized_datasets["eval"])) trainer.log_metrics("eval", metrics) trainer.save_metrics("eval", metrics) # Write model card and (optionally) push to hub config_name = data_args.dataset_config_name if data_args.dataset_config_name is not None else "na" kwargs = { "finetuned_from": model_args.model_name_or_path, "tasks": "speech-recognition", "tags": ["automatic-speech-recognition", data_args.dataset_name], "dataset_args": f"Config: {config_name}, Training split: {data_args.train_split_name}, Eval split: {data_args.eval_split_name}", "dataset": f"{data_args.dataset_name.upper()} - {config_name.upper()}", } if "common_voice" in data_args.dataset_name: kwargs["language"] = config_name if training_args.push_to_hub: trainer.push_to_hub(**kwargs) else: trainer.create_model_card(**kwargs) return results if __name__ == "__main__": main()
#!/usr/bin/env python # coding=utf-8 # Copyright 2021 The HuggingFace Inc. 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 """ Fine-tuning a 🤗 Transformers CTC model for automatic speech recognition""" import functools import json import logging import os import re import sys from dataclasses import dataclass, field from typing import Dict, List, Optional, Union import datasets import numpy as np import torch from datasets import DatasetDict, load_dataset, load_metric import transformers from transformers import ( AutoConfig, AutoFeatureExtractor, AutoModelForCTC, AutoTokenizer, HfArgumentParser, Trainer, TrainingArguments, Wav2Vec2Processor, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process from transformers.utils import check_min_version from transformers.utils.versions import require_version # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.13.0.dev0") require_version("datasets>=1.13.3", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt") logger = logging.getLogger(__name__) def list_field(default=None, metadata=None): return field(default_factory=lambda: default, metadata=metadata) @dataclass class ModelArguments: """ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from. """ model_name_or_path: str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) cache_dir: Optional[str] = field( default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}, ) freeze_feature_extractor: Optional[bool] = field( default=True, metadata={"help": "Whether to freeze the feature extractor layers of the model."} ) attention_dropout: Optional[float] = field( default=0.0, metadata={"help": "The dropout ratio for the attention probabilities."} ) activation_dropout: Optional[float] = field( default=0.0, metadata={"help": "The dropout ratio for activations inside the fully connected layer."} ) feat_proj_dropout: Optional[float] = field( default=0.0, metadata={"help": "The dropout ratio for the projected features."} ) hidden_dropout: Optional[float] = field( default=0.0, metadata={ "help": "The dropout probability for all fully connected layers in the embeddings, encoder, and pooler." }, ) final_dropout: Optional[float] = field( default=0.0, metadata={"help": "The dropout probability for the final projection layer."}, ) mask_time_prob: Optional[float] = field( default=0.05, metadata={ "help": "Probability of each feature vector along the time axis to be chosen as the start of the vector" "span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature" "vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``." }, ) layerdrop: Optional[float] = field(default=0.0, metadata={"help": "The LayerDrop probability."}) ctc_loss_reduction: Optional[str] = field( default="mean", metadata={"help": "The way the ctc loss should be reduced. Should be one of 'mean' or 'sum'."} ) @dataclass class DataTrainingArguments: """ Arguments pertaining to what data we are going to input our model for training and eval. Using `HfArgumentParser` we can turn this class into argparse arguments to be able to specify them on the command line. """ dataset_name: str = field( metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) dataset_config_name: Optional[str] = field( default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) train_split_name: Optional[str] = field( default="train+validation", metadata={ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'" }, ) eval_split_name: Optional[str] = field( default="test", metadata={ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'" }, ) audio_column_name: Optional[str] = field( default="audio", metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"}, ) text_column_name: Optional[str] = field( default="text", metadata={"help": "The name of the dataset column containing the text data. Defaults to 'text'"}, ) overwrite_cache: bool = field( default=False, metadata={"help": "Overwrite the cached preprocessed datasets or not."} ) preprocessing_num_workers: Optional[int] = field( default=None, metadata={"help": "The number of processes to use for the preprocessing."}, ) max_train_samples: Optional[int] = field( default=None, metadata={ "help": "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." }, ) max_eval_samples: Optional[int] = field( default=None, metadata={ "help": "For debugging purposes or quicker training, truncate the number of validation examples to this " "value if set." }, ) chars_to_ignore: Optional[List[str]] = list_field( default=None, metadata={"help": "A list of characters to remove from the transcripts."}, ) max_duration_in_seconds: Optional[float] = field( default=20.0, metadata={ "help": "Truncate audio files that are longer than `max_duration_in_seconds` seconds to 'max_duration_in_seconds`" }, ) min_duration_in_seconds: Optional[float] = field( default=0.0, metadata={"help": "Filter audio files that are shorter than `min_duration_in_seconds` seconds"} ) preprocessing_only: Optional[bool] = field( default=False, metadata={ "help": "Whether to only do data preprocessing and skip training. " "This is especially useful when data preprocessing errors out in distributed training due to timeout. " "In this case, one should run the preprocessing in a non-distributed setup with `preprocessing_only=True` " "so that the cached datasets can consequently be loaded in distributed training" }, ) use_auth_token: Optional[bool] = field( default=False, metadata={ "help": "If :obj:`True`, will use the token generated when running" ":obj:`transformers-cli logiin as HTTP bearer authorization for remote files." }, ) @dataclass class DataCollatorCTCWithPadding: """ Data collator that will dynamically pad the inputs received. Args: processor (:class:`~transformers.Wav2Vec2Processor`) The processor used for proccessing the data. padding (:obj:`bool`, :obj:`str` or :class:`~transformers.tokenization_utils_base.PaddingStrategy`, `optional`, defaults to :obj:`True`): Select a strategy to pad the returned sequences (according to the model's padding side and padding index) among: * :obj:`True` or :obj:`'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided). * :obj:`'max_length'`: Pad to a maximum length specified with the argument :obj:`max_length` or to the maximum acceptable input length for the model if that argument is not provided. * :obj:`False` or :obj:`'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different lengths). max_length (:obj:`int`, `optional`): Maximum length of the ``input_values`` of the returned list and optionally padding length (see above). max_length_labels (:obj:`int`, `optional`): Maximum length of the ``labels`` returned list and optionally padding length (see above). pad_to_multiple_of (:obj:`int`, `optional`): If set will pad the sequence to a multiple of the provided value. This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >= 7.5 (Volta). """ processor: Wav2Vec2Processor padding: Union[bool, str] = "longest" pad_to_multiple_of: Optional[int] = None pad_to_multiple_of_labels: Optional[int] = None def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]: # split inputs and labels since they have to be of different lenghts and need # different padding methods input_features = [{"input_values": feature["input_values"]} for feature in features] label_features = [{"input_ids": feature["labels"]} for feature in features] batch = self.processor.pad( input_features, padding=self.padding, pad_to_multiple_of=self.pad_to_multiple_of, return_tensors="pt", ) with self.processor.as_target_processor(): labels_batch = self.processor.pad( label_features, padding=self.padding, pad_to_multiple_of=self.pad_to_multiple_of_labels, return_tensors="pt", ) # replace padding with -100 to ignore loss correctly labels = labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1), -100) batch["labels"] = labels return batch def create_vocabulary_from_data(datasets: DatasetDict): # Given training and test labels create vocabulary def extract_all_chars(batch): all_text = " ".join(batch["target_text"]) vocab = list(set(all_text)) return {"vocab": [vocab], "all_text": [all_text]} vocabs = datasets.map( extract_all_chars, batched=True, batch_size=-1, keep_in_memory=True, remove_columns=datasets["train"].column_names, ) # take union of all unique characters in each dataset vocab_set = functools.reduce( lambda vocab_1, vocab_2: set(vocab_1["vocab"][0]) | set(vocab_2["vocab"][0]), vocabs.values() ) vocab_dict = {v: k for k, v in enumerate(sorted(list(vocab_set)))} # replace white space with delimiter token vocab_dict["|"] = vocab_dict[" "] del vocab_dict[" "] # add unk and pad token vocab_dict["[UNK]"] = len(vocab_dict) vocab_dict["[PAD]"] = len(vocab_dict) return vocab_dict def main(): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: model_args, data_args, training_args = parser.parse_args_into_dataclasses() # Detecting last checkpoint. last_checkpoint = None if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir: last_checkpoint = get_last_checkpoint(training_args.output_dir) if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. " "Use --overwrite_output_dir to overcome." ) elif last_checkpoint is not None: logger.info( f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", handlers=[logging.StreamHandler(sys.stdout)], ) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN) # Log on each process the small summary: logger.warning( f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}" f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}" ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank): transformers.utils.logging.set_verbosity_info() logger.info("Training/evaluation parameters %s", training_args) # Set seed before initializing model. set_seed(training_args.seed) # 1. First, let's load the dataset raw_datasets = DatasetDict() raw_datasets["train"] = load_dataset( data_args.dataset_name, data_args.dataset_config_name, split=data_args.train_split_name ) raw_datasets["eval"] = load_dataset( data_args.dataset_name, data_args.dataset_config_name, split=data_args.eval_split_name ) if data_args.audio_column_name not in raw_datasets["train"].column_names: raise ValueError( f"--audio_column_name '{data_args.audio_column_name}' not found in dataset '{data_args.dataset_name}'. " "Make sure to set `--audio_column_name` to the correct audio column - one of " f"{', '.join(raw_datasets['train'].column_names)}." ) if data_args.text_column_name not in raw_datasets["train"].column_names: raise ValueError( f"--text_column_name {data_args.text_column_name} not found in dataset '{data_args.dataset_name}'. " "Make sure to set `--text_column_name` to the correct text column - one of " f"{', '.join(raw_datasets['train'].column_names)}." ) # prepare dataset if data_args.max_train_samples is not None: raw_datasets["train"] = raw_datasets["train"].select(range(data_args.max_train_samples)) if data_args.max_eval_samples is not None: raw_datasets["eval"] = raw_datasets["eval"].select(range(data_args.max_eval_samples)) # 2. We remove some special characters from the datasets # that make training complicated and do not help in transcribing the speech # E.g. characters, such as `,` and `.` do not really have an acoustic characteristic # that could be easily picked up by the model chars_to_ignore_regex = ( f'[{"".join(data_args.chars_to_ignore)}]' if data_args.chars_to_ignore is not None else None ) def remove_special_characters(batch): if chars_to_ignore_regex is not None: batch["target_text"] = re.sub(chars_to_ignore_regex, "", batch[data_args.text_column_name]).lower() + " " else: batch["target_text"] = batch[data_args.text_column_name].lower() + " " return batch with training_args.main_process_first(desc="dataset map special characters removal"): raw_datasets = raw_datasets.map( remove_special_characters, remove_columns=[data_args.text_column_name], desc="remove special characters from datasets", ) # 3. Next, we create the vocabulary of the model by extracting all unique characters from # the training and evaluation datasets # We need to make sure that only first rank saves vocabulary # make sure all processes wait until vocab is created vocab_file = os.path.join(training_args.output_dir, "vocab.json") with training_args.main_process_first(): if training_args.overwrite_output_dir and os.path.isfile(vocab_file): os.remove(vocab_file) with training_args.main_process_first(desc="dataset map vocabulary creation"): if not os.path.isfile(vocab_file): os.makedirs(training_args.output_dir, exist_ok=True) vocab_dict = create_vocabulary_from_data(raw_datasets) # save vocab dict to be loaded into tokenizer with open(vocab_file, "w") as file: json.dump(vocab_dict, file) # 4. Now we can instantiate the configuration, feature extractor, tokenizer and model # Note for distributed training, the .from_pretrained methods guarantee that only # one local process can concurrently download model & vocab. # load config config = AutoConfig.from_pretrained( model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_auth_token=data_args.use_auth_token ) # tokenizer is defined by `tokenizer_class` if present in config else by `model_type` config_for_tokenizer = config if config.tokenizer_class is not None else None tokenizer_type = config.model_type if config.tokenizer_class is None else None # load feature_extractor, tokenizer and create processor tokenizer = AutoTokenizer.from_pretrained( training_args.output_dir, config=config_for_tokenizer, tokenizer_type=tokenizer_type, unk_token="[UNK]", pad_token="[PAD]", word_delimiter_token="|", use_auth_token=data_args.use_auth_token, ) feature_extractor = AutoFeatureExtractor.from_pretrained( model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_auth_token=data_args.use_auth_token ) processor = Wav2Vec2Processor(feature_extractor=feature_extractor, tokenizer=tokenizer) # adapt config config.update( { "feat_proj_dropout": model_args.feat_proj_dropout, "attention_dropout": model_args.attention_dropout, "hidden_dropout": model_args.hidden_dropout, "final_dropout": model_args.final_dropout, "mask_time_prob": model_args.mask_time_prob, "gradient_checkpointing": training_args.gradient_checkpointing, "layerdrop": model_args.layerdrop, "ctc_loss_reduction": model_args.ctc_loss_reduction, "pad_token_id": processor.tokenizer.pad_token_id, "vocab_size": len(processor.tokenizer), "activation_dropout": model_args.activation_dropout, } ) # create model model = AutoModelForCTC.from_pretrained( model_args.model_name_or_path, cache_dir=model_args.cache_dir, config=config, use_auth_token=data_args.use_auth_token, ) # freeze encoder if model_args.freeze_feature_extractor: model.freeze_feature_extractor() # 5. Now we preprocess the datasets including loading the audio, resampling and normalization # Thankfully, `datasets` takes care of automatically loading and resampling the audio, # so that we just need to set the correct target sampling rate and normalize the input # via the `feature_extractor` # make sure that dataset decodes audio with correct sampling rate raw_datasets = raw_datasets.cast_column( data_args.audio_column_name, datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate) ) # derive max & min input length for sample rate & max duration max_input_length = data_args.max_duration_in_seconds * processor.feature_extractor.sampling_rate min_input_length = data_args.min_duration_in_seconds * processor.feature_extractor.sampling_rate # Preprocessing the datasets. # We need to read the audio files as arrays and tokenize the targets. def prepare_dataset(batch): # load audio sample = batch[data_args.audio_column_name] batch["input_values"] = processor( sample["array"], sampling_rate=sample["sampling_rate"], truncate=True, max_length=max_input_length ).input_values[0] batch["input_length"] = len(batch["input_values"]) # Setup the processor for targets with processor.as_target_processor(): batch["labels"] = processor(batch["target_text"]).input_ids return batch with training_args.main_process_first(desc="dataset map preprocessing"): vectorized_datasets = raw_datasets.map( prepare_dataset, remove_columns=raw_datasets["train"].column_names, num_proc=data_args.preprocessing_num_workers, desc="preprocess datasets", ) if min_input_length > 0.0: # filter data that is shorter than min_input_length vectorized_datasets = vectorized_datasets.filter( lambda x: x > min_input_length, num_proc=data_args.preprocessing_num_workers, input_columns=["input_length"], ) vectorized_datasets = vectorized_datasets.remove_columns("input_length") # 6. Next, we can prepare the training. # Let's use word error rate (WER) as our evaluation metric, # instantiate a data collator and the trainer # Define Metric during training wer_metric = load_metric("wer") # for large datasets it is advised to run the preprocessing on a # single machine first with ``args.preprocessing_only`` since there will mostly likely # be a timeout when running the script in distributed mode. # In a second step ``args.preprocessing_only`` can then be set to `False` to load the # cached dataset if data_args.preprocessing_only: logger.info(f"Data preprocessing finished. Files cached at {vectorized_datasets.cache_files}") return def compute_metrics(pred): pred_logits = pred.predictions pred_ids = np.argmax(pred_logits, axis=-1) pred.label_ids[pred.label_ids == -100] = processor.tokenizer.pad_token_id pred_str = processor.batch_decode(pred_ids) # we do not want to group tokens when computing the metrics label_str = processor.batch_decode(pred.label_ids, group_tokens=False) wer = wer_metric.compute(predictions=pred_str, references=label_str) return {"wer": wer} # Instantiate custom data collator data_collator = DataCollatorCTCWithPadding(processor=processor) # Initialize Trainer trainer = Trainer( model=model, data_collator=data_collator, args=training_args, compute_metrics=compute_metrics, train_dataset=vectorized_datasets["train"] if training_args.do_train else None, eval_dataset=vectorized_datasets["eval"] if training_args.do_eval else None, tokenizer=processor.feature_extractor, ) # 7. Finally, we can start training # Training if training_args.do_train: # use last checkpoint if exist if last_checkpoint is not None: checkpoint = last_checkpoint elif os.path.isdir(model_args.model_name_or_path): checkpoint = model_args.model_name_or_path else: checkpoint = None # Save the feature_extractor and the tokenizer if is_main_process(training_args.local_rank): processor.save_pretrained(training_args.output_dir) train_result = trainer.train(resume_from_checkpoint=checkpoint) trainer.save_model() metrics = train_result.metrics max_train_samples = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(vectorized_datasets["train"]) ) metrics["train_samples"] = min(max_train_samples, len(vectorized_datasets["train"])) trainer.log_metrics("train", metrics) trainer.save_metrics("train", metrics) trainer.save_state() # Evaluation results = {} if training_args.do_eval: logger.info("*** Evaluate ***") metrics = trainer.evaluate() max_eval_samples = ( data_args.max_eval_samples if data_args.max_eval_samples is not None else len(vectorized_datasets["eval"]) ) metrics["eval_samples"] = min(max_eval_samples, len(vectorized_datasets["eval"])) trainer.log_metrics("eval", metrics) trainer.save_metrics("eval", metrics) # Write model card and (optionally) push to hub config_name = data_args.dataset_config_name if data_args.dataset_config_name is not None else "na" kwargs = { "finetuned_from": model_args.model_name_or_path, "tasks": "speech-recognition", "tags": ["automatic-speech-recognition", data_args.dataset_name], "dataset_args": f"Config: {config_name}, Training split: {data_args.train_split_name}, Eval split: {data_args.eval_split_name}", "dataset": f"{data_args.dataset_name.upper()} - {config_name.upper()}", } if "common_voice" in data_args.dataset_name: kwargs["language"] = config_name if training_args.push_to_hub: trainer.push_to_hub(**kwargs) else: trainer.create_model_card(**kwargs) return results if __name__ == "__main__": main()
# Copyright (c) FULIUCANSHENG. # Licensed under the MIT License. import os from collections import OrderedDict from lazydocs import generate_docs generate_docs( ["../"], output_path="./references", src_root_path="../", src_base_url="https://github.com/fuliucansheng/unitorch/blob/master/", ignored_modules=[ "unitorch.cli", "unitorch.microsoft", "unitorch.scripts", "unitorch.services", "unitorch.modules.replace", "unitorch.modules.prefix_model", "unitorch.models.detectron2.backbone", "unitorch.models.detectron2.meta_arch", "unitorch.ops", "unitorch.optim", "unitorch.task", "unitorch.writer", "unitorch_cli", ], ) def get_folder_files(folder): files = [os.path.join(folder, f) for f in os.listdir(folder) if f.endswith(".md") and f.lower() != "readme.md"] files = [os.path.normpath(f) for f in files] return sorted(files, key=lambda x: x[:-3]) def get_markdown_docs(files, space=0): docs = [] for f in files: name = os.path.basename(f)[:-3] link = f"/{f}" name, link = name.replace("_", "\_"), link.replace("_", "\_") docs += [f"{" " * space}* [**{name}**]({link})"] return docs sidebar_docs = [] ## Quick Start quick_start = "* [**Quick Start**](/quick-start.md)" sidebar_docs += [quick_start] ## Installation installation = "* [**Installation**](/install.md)" sidebar_docs += [installation] ## Overview introduction = "* **Introduction**" overview = " * [**overview**](/overview.md)" optimized_techniques = " * [**optimized techniques**](/optimized_techniques.md)" configuration = " * [**configuration**](/configuration.md)" sidebar_docs += [introduction, overview, optimized_techniques, configuration] ## Tutorials tutorials = "* [**Tutorials**](/tutorials/readme.md)" tutorials_files = get_folder_files("./tutorials") sidebar_docs += [tutorials] + get_markdown_docs(tutorials_files, space=2) ## References references = "* [**References**](/references/readme.md)" references_files = get_folder_files("./references") def generate_reference_readme(files): docs = get_markdown_docs(files, space=0) title = "## unitorch documents" description = "unitorch provides efficient implementation of popular unified NLU / NLG / CV / MM / RL models with PyTorch. It automatically optimizes training / inference speed based on pupular deep learning toolkits (transformers, fairseq, fastseq, etc) without accuracy loss." notes = "> Notes" contents = [title, description, notes] + docs with open("./references/readme.md", "w") as f: f.write("\n".join(contents)) def process_reference_file(doc_files): replace_dict = OrderedDict( { ": # Copyright (c) FULIUCANSHENG.": "", "# ": "### ", "**Global Variables**": "### **Global Variables**", } ) def process_contents(contents): new_contents = [] for content in contents: if "lazydocs" in content.lower(): continue if "licensed under the mit license." in content.lower(): continue for k, v in replace_dict.items(): content = content.replace(k, v) new_contents.append(content) return new_contents doc_file = doc_files[0] doc_contents = open(doc_file, "r").read().split("\n") file_pointer = open(doc_file, "w") write_contents = process_contents(doc_contents) for more_doc_file in doc_files[1:]: doc_contents = open(more_doc_file, "r").read().split("\n") write_contents += process_contents(doc_contents) os.remove(more_doc_file) file_pointer.write("\n".join(write_contents)) def is_single(path): mfile = os.path.basename(path) if mfile in [ "unitorch.md", "unitorch.cli.md", "unitorch.cli.models.md", "unitorch.models.md", ]: return True if mfile.startswith("unitorch.cli.models"): return mfile.count(".") == 4 if mfile.startswith("unitorch.cli"): return mfile.count(".") == 3 if mfile.startswith("unitorch.models"): return mfile.count(".") == 3 if mfile.startswith("unitorch_cli"): return mfile.count(".") == 1 if mfile.startswith("unitorch"): return mfile.count(".") == 2 return mfile.count(".") == 1 index = 0 while index < len(references_files): process_files = [references_files[index]] index += 1 while index < len(references_files) and not is_single(references_files[index]): process_files.append(references_files[index]) index += 1 print(process_files) process_reference_file(process_files) new_references_files = get_folder_files("./references") generate_reference_readme(new_references_files) sidebar_docs += [references] + get_markdown_docs(new_references_files, space=2) ## Benchmarks benchmarks = "* [**Benchmarks**](/benchmarks/readme.md)" benchmarks_files = get_folder_files("./benchmarks") sidebar_docs += [benchmarks] + get_markdown_docs(benchmarks_files, space=2) with open("./_sidebar.md", "w") as f: f.write("\n".join(sidebar_docs))
# Copyright (c) FULIUCANSHENG. # Licensed under the MIT License. import os from collections import OrderedDict from lazydocs import generate_docs generate_docs( ["../"], output_path="./references", src_root_path="../", src_base_url="https://github.com/fuliucansheng/unitorch/blob/master/", ignored_modules=[ "unitorch.cli", "unitorch.microsoft", "unitorch.scripts", "unitorch.services", "unitorch.modules.replace", "unitorch.modules.prefix_model", "unitorch.models.detectron2.backbone", "unitorch.models.detectron2.meta_arch", "unitorch.ops", "unitorch.optim", "unitorch.task", "unitorch.writer", "unitorch_cli", ], ) def get_folder_files(folder): files = [os.path.join(folder, f) for f in os.listdir(folder) if f.endswith(".md") and f.lower() != "readme.md"] files = [os.path.normpath(f) for f in files] return sorted(files, key=lambda x: x[:-3]) def get_markdown_docs(files, space=0): docs = [] for f in files: name = os.path.basename(f)[:-3] link = f"/{f}" name, link = name.replace("_", "\_"), link.replace("_", "\_") docs += [f"{' ' * space}* [**{name}**]({link})"] return docs sidebar_docs = [] ## Quick Start quick_start = "* [**Quick Start**](/quick-start.md)" sidebar_docs += [quick_start] ## Installation installation = "* [**Installation**](/install.md)" sidebar_docs += [installation] ## Overview introduction = "* **Introduction**" overview = " * [**overview**](/overview.md)" optimized_techniques = " * [**optimized techniques**](/optimized_techniques.md)" configuration = " * [**configuration**](/configuration.md)" sidebar_docs += [introduction, overview, optimized_techniques, configuration] ## Tutorials tutorials = "* [**Tutorials**](/tutorials/readme.md)" tutorials_files = get_folder_files("./tutorials") sidebar_docs += [tutorials] + get_markdown_docs(tutorials_files, space=2) ## References references = "* [**References**](/references/readme.md)" references_files = get_folder_files("./references") def generate_reference_readme(files): docs = get_markdown_docs(files, space=0) title = "## unitorch documents" description = "unitorch provides efficient implementation of popular unified NLU / NLG / CV / MM / RL models with PyTorch. It automatically optimizes training / inference speed based on pupular deep learning toolkits (transformers, fairseq, fastseq, etc) without accuracy loss." notes = "> Notes" contents = [title, description, notes] + docs with open("./references/readme.md", "w") as f: f.write("\n".join(contents)) def process_reference_file(doc_files): replace_dict = OrderedDict( { ": # Copyright (c) FULIUCANSHENG.": "", "# ": "### ", "**Global Variables**": "### **Global Variables**", } ) def process_contents(contents): new_contents = [] for content in contents: if "lazydocs" in content.lower(): continue if "licensed under the mit license." in content.lower(): continue for k, v in replace_dict.items(): content = content.replace(k, v) new_contents.append(content) return new_contents doc_file = doc_files[0] doc_contents = open(doc_file, "r").read().split("\n") file_pointer = open(doc_file, "w") write_contents = process_contents(doc_contents) for more_doc_file in doc_files[1:]: doc_contents = open(more_doc_file, "r").read().split("\n") write_contents += process_contents(doc_contents) os.remove(more_doc_file) file_pointer.write("\n".join(write_contents)) def is_single(path): mfile = os.path.basename(path) if mfile in [ "unitorch.md", "unitorch.cli.md", "unitorch.cli.models.md", "unitorch.models.md", ]: return True if mfile.startswith("unitorch.cli.models"): return mfile.count(".") == 4 if mfile.startswith("unitorch.cli"): return mfile.count(".") == 3 if mfile.startswith("unitorch.models"): return mfile.count(".") == 3 if mfile.startswith("unitorch_cli"): return mfile.count(".") == 1 if mfile.startswith("unitorch"): return mfile.count(".") == 2 return mfile.count(".") == 1 index = 0 while index < len(references_files): process_files = [references_files[index]] index += 1 while index < len(references_files) and not is_single(references_files[index]): process_files.append(references_files[index]) index += 1 print(process_files) process_reference_file(process_files) new_references_files = get_folder_files("./references") generate_reference_readme(new_references_files) sidebar_docs += [references] + get_markdown_docs(new_references_files, space=2) ## Benchmarks benchmarks = "* [**Benchmarks**](/benchmarks/readme.md)" benchmarks_files = get_folder_files("./benchmarks") sidebar_docs += [benchmarks] + get_markdown_docs(benchmarks_files, space=2) with open("./_sidebar.md", "w") as f: f.write("\n".join(sidebar_docs))
from cscmiko.devices.base.device import Device from cscmiko.models import layer2, layer3, security, system from abc import ABC from cscmiko.exceptions import CscmikoNotSyncedError, CscmikoInvalidFeatureError _INVETORY_CMD = "show version" _VLAN_CMD = "show vlan" _INTERFACE_CMD = "show interface" _INTERFACE_CONF_CMD = "show run | section interface" _ROUTE_CMD = "show ip route" _CDP_CMD = "show cdp neighbors detail" _BGP_CMD = "show ip bgp" _OSPF_CMD = "show ip ospf neighbor" _ACL_CMD = "show ip access-list" _VRF_CMD = "show vrf" _VTP_CMD = "show vtp status" _CPU_CMD = "show processes cpu" _MEM_CMD = "show processes memory" _VPC_CMD = "show vpc" _MODULE_CMD = "show module" _STP_CMD = "show spanning-tree" class _CiscoSwitch(Device, ABC): """ Base Cisco Switch manager , this manager handle Cat switch config fetch , config push , my_swicth = CatSwitch(host='4.71.144.98', username='admin', password='J3llyfish1') my_swicth.fetch_cpu_status() this example fetch CPU status , and set a cpu_status attibute for myswitch object """ features_list = ['inventory', 'interfaces', 'vlans', 'cdp_neighbors', 'routes', 'access_lists', 'vtp_status', 'spanning_tree', 'interfaces_configs','lldp_neighbors'] def __getattr__(self, item): """ this is only for raising CiscoSDKNotSyncedError, as the fetch method need to be called before accessing the config attribute (e.g. myswitch.vlans ) for every config compnent(vlans,vrfs,interfaces ... etc) we have a fetch method listed below , :param item: attribute :return: """ if item not in self.features_list: raise CscmikoInvalidFeatureError( f"{item.replace("fetch_","")} is not a valid feature , available models = {self.features_list}") if not item.endswith('s'): item = item + 's' raise CscmikoNotSyncedError( f"{item} is not collected please make sure to call fetch_{item} before, available models : {self.features_list}") # Sync Methods # TODO : make the add fetch to base class to have a reusable fetch code def fetch_inventory(self): print(f"Collecting Inventory details from {self.host} ...") inventory_dict = self.get_command_output(_INVETORY_CMD) if not inventory_dict: print("No inventory details collected") return None self.inventory = system.Inventory(inventory_dict[0]) # layer 2 fetch methods def fetch_interfaces(self): print(f"Collecting Interfaces from {self.host} ...") interfaces_dicts = self.get_command_output(_INTERFACE_CMD) if not interfaces_dicts: print("No interfaces collected") return None self.interfaces = layer2.Interfaces(interfaces_dicts) def fetch_interfaces_configs(self): print(f"Collecting Interfaces configs from {self.host} ...") interfaces_configs_dicts = self.get_command_output(_INTERFACE_CONF_CMD) if not interfaces_configs_dicts: print("No interfaces config collected") return None self.interfaces_configs = layer2.InterfaceConfigs(interfaces_configs_dicts) def fetch_vlans(self): print(f"Collecting Vlans from {self.host} ...") vlans_dicts = self.get_command_output(_VLAN_CMD) if not vlans_dicts: print("No vlans collected") return None self.vlans = layer2.Vlans(vlans_dicts) def fetch_cdp_neighbors(self): print(f"Collecting CDP neighbors from {self.host} ...") cdps_dicts = self.get_command_output(_CDP_CMD) if not cdps_dicts: print("No cdp neighbors collected") return None self.cdp_neighbors = layer2.CdpNeighbors(cdps_dicts) def fetch_lldp_neighbors(self): print(f"Collecting LLDP neighbors from {self.host} ...") lldps_dicts = self.get_command_output(_CDP_CMD) if not lldps_dicts: print("No LLDP neighbors collected") return None self.lldp_neighbors = layer2.LldpNeighbors(lldps_dicts) # Layer 3 fetch methods def fetch_routes(self): print(f"Collecting Routes from {self.host} ...") routes_dicts = self.get_command_output(_ROUTE_CMD) if not routes_dicts: print("No Routes collected") return None self.routes = layer3.Routes(routes_dicts) # security fetch methods def fetch_access_lists(self): print(f"Collecting access-lists from {self.host} ...") acls_dicts = self.get_command_output(_ACL_CMD) if not acls_dicts: print("No acls collected") self.access_lists = None return None self.access_lists = security.AccessLists(acls_dicts) def fetch_spanning_tree(self): print(f"Collecting spanning-tree from {self.host} ...") stp_dict = self.get_command_output(_STP_CMD) if not stp_dict: print("No stp collected") self.spanning_tree = None return None self.spanning_tree = layer2.Stps(stp_dict) def fetch_vtp_status(self): print(f"Collecting vtp status from {self.host} ...") vtp_dicts = self.get_command_output(_VTP_CMD) if not vtp_dicts: print("No vlans collected") return None self.vtp_status = layer2.Vtp(vtp_dicts[0]) def fetch(self): """ this call all the fetch_methods incase you want to fetch all components , :return: """ self.fetch_interfaces() self.fetch_vlans() self.fetch_spanning_tree() self.fetch_cdp_neighbors() self.fetch_routes() self.fetch_access_lists() self.fetch_vtp_status()
from cscmiko.devices.base.device import Device from cscmiko.models import layer2, layer3, security, system from abc import ABC from cscmiko.exceptions import CscmikoNotSyncedError, CscmikoInvalidFeatureError _INVETORY_CMD = "show version" _VLAN_CMD = "show vlan" _INTERFACE_CMD = "show interface" _INTERFACE_CONF_CMD = "show run | section interface" _ROUTE_CMD = "show ip route" _CDP_CMD = "show cdp neighbors detail" _BGP_CMD = "show ip bgp" _OSPF_CMD = "show ip ospf neighbor" _ACL_CMD = "show ip access-list" _VRF_CMD = "show vrf" _VTP_CMD = "show vtp status" _CPU_CMD = "show processes cpu" _MEM_CMD = "show processes memory" _VPC_CMD = "show vpc" _MODULE_CMD = "show module" _STP_CMD = "show spanning-tree" class _CiscoSwitch(Device, ABC): """ Base Cisco Switch manager , this manager handle Cat switch config fetch , config push , my_swicth = CatSwitch(host='4.71.144.98', username='admin', password='J3llyfish1') my_swicth.fetch_cpu_status() this example fetch CPU status , and set a cpu_status attibute for myswitch object """ features_list = ['inventory', 'interfaces', 'vlans', 'cdp_neighbors', 'routes', 'access_lists', 'vtp_status', 'spanning_tree', 'interfaces_configs','lldp_neighbors'] def __getattr__(self, item): """ this is only for raising CiscoSDKNotSyncedError, as the fetch method need to be called before accessing the config attribute (e.g. myswitch.vlans ) for every config compnent(vlans,vrfs,interfaces ... etc) we have a fetch method listed below , :param item: attribute :return: """ if item not in self.features_list: raise CscmikoInvalidFeatureError( f"{item.replace('fetch_','')} is not a valid feature , available models = {self.features_list}") if not item.endswith('s'): item = item + 's' raise CscmikoNotSyncedError( f"{item} is not collected please make sure to call fetch_{item} before, available models : {self.features_list}") # Sync Methods # TODO : make the add fetch to base class to have a reusable fetch code def fetch_inventory(self): print(f"Collecting Inventory details from {self.host} ...") inventory_dict = self.get_command_output(_INVETORY_CMD) if not inventory_dict: print("No inventory details collected") return None self.inventory = system.Inventory(inventory_dict[0]) # layer 2 fetch methods def fetch_interfaces(self): print(f"Collecting Interfaces from {self.host} ...") interfaces_dicts = self.get_command_output(_INTERFACE_CMD) if not interfaces_dicts: print("No interfaces collected") return None self.interfaces = layer2.Interfaces(interfaces_dicts) def fetch_interfaces_configs(self): print(f"Collecting Interfaces configs from {self.host} ...") interfaces_configs_dicts = self.get_command_output(_INTERFACE_CONF_CMD) if not interfaces_configs_dicts: print("No interfaces config collected") return None self.interfaces_configs = layer2.InterfaceConfigs(interfaces_configs_dicts) def fetch_vlans(self): print(f"Collecting Vlans from {self.host} ...") vlans_dicts = self.get_command_output(_VLAN_CMD) if not vlans_dicts: print("No vlans collected") return None self.vlans = layer2.Vlans(vlans_dicts) def fetch_cdp_neighbors(self): print(f"Collecting CDP neighbors from {self.host} ...") cdps_dicts = self.get_command_output(_CDP_CMD) if not cdps_dicts: print("No cdp neighbors collected") return None self.cdp_neighbors = layer2.CdpNeighbors(cdps_dicts) def fetch_lldp_neighbors(self): print(f"Collecting LLDP neighbors from {self.host} ...") lldps_dicts = self.get_command_output(_CDP_CMD) if not lldps_dicts: print("No LLDP neighbors collected") return None self.lldp_neighbors = layer2.LldpNeighbors(lldps_dicts) # Layer 3 fetch methods def fetch_routes(self): print(f"Collecting Routes from {self.host} ...") routes_dicts = self.get_command_output(_ROUTE_CMD) if not routes_dicts: print("No Routes collected") return None self.routes = layer3.Routes(routes_dicts) # security fetch methods def fetch_access_lists(self): print(f"Collecting access-lists from {self.host} ...") acls_dicts = self.get_command_output(_ACL_CMD) if not acls_dicts: print("No acls collected") self.access_lists = None return None self.access_lists = security.AccessLists(acls_dicts) def fetch_spanning_tree(self): print(f"Collecting spanning-tree from {self.host} ...") stp_dict = self.get_command_output(_STP_CMD) if not stp_dict: print("No stp collected") self.spanning_tree = None return None self.spanning_tree = layer2.Stps(stp_dict) def fetch_vtp_status(self): print(f"Collecting vtp status from {self.host} ...") vtp_dicts = self.get_command_output(_VTP_CMD) if not vtp_dicts: print("No vlans collected") return None self.vtp_status = layer2.Vtp(vtp_dicts[0]) def fetch(self): """ this call all the fetch_methods incase you want to fetch all components , :return: """ self.fetch_interfaces() self.fetch_vlans() self.fetch_spanning_tree() self.fetch_cdp_neighbors() self.fetch_routes() self.fetch_access_lists() self.fetch_vtp_status()
import asyncio import click import logging import pprint from .session import Session from .socket import SocketSession _LOGGER = logging.getLogger(__name__) @click.group(chain=True) @click.option("-a", "--api-name", required=True, help="API name") @click.option( "-b", "--basic-auth-creds", required=True, help="API basic auth credentials" ) @click.option("-u", "--username", required=True, help="API username") @click.option("-p", "--password", required=True, help="API password") @click.option( "-v", "--verbose/--no-verbose", default=False, help="Enable verbose logging" ) @click.pass_context def smartbox(ctx, api_name, basic_auth_creds, username, password, verbose): ctx.ensure_object(dict) logging.basicConfig( format="%(asctime)s %(levelname)-8s [%(name)s.%(funcName)s:%(lineno)d] %(message)s", level=logging.DEBUG if verbose else logging.INFO, datefmt="%Y-%m-%d %H:%M:%S", ) session = Session(api_name, basic_auth_creds, username, password) ctx.obj["session"] = session ctx.obj["verbose"] = verbose @smartbox.command(help="Show devices") @click.pass_context def devices(ctx): session = ctx.obj["session"] devices = session.get_devices() pp = pprint.PrettyPrinter(indent=4) pp.pprint(devices) @smartbox.command(help="Show nodes") @click.pass_context def nodes(ctx): session = ctx.obj["session"] devices = session.get_devices() pp = pprint.PrettyPrinter(indent=4) for device in devices: print(f"{device["name"]} (dev_id: {device["dev_id"]})") nodes = session.get_nodes(device["dev_id"]) pp.pprint(nodes) @smartbox.command(help="Show node status") @click.pass_context def status(ctx): session = ctx.obj["session"] devices = session.get_devices() pp = pprint.PrettyPrinter(indent=4) for device in devices: print(f"{device["name"]} (dev_id: {device["dev_id"]})") nodes = session.get_nodes(device["dev_id"]) for node in nodes: print(f"{node["name"]} (addr: {node["addr"]})") status = session.get_status(device["dev_id"], node) pp.pprint(status) @smartbox.command(help="Set node status (pass settings as extra args, e.g. mode=auto)") @click.option( "-d", "--device-id", required=True, help="Device ID for node to set status on" ) @click.option( "-n", "--node-addr", type=int, required=True, help="Address of node to set status on", ) @click.option("--locked", type=bool) @click.option("--mode") @click.option("--stemp") @click.option("--units") # TODO: other options @click.pass_context def set_status(ctx, device_id, node_addr, **kwargs): session = ctx.obj["session"] devices = session.get_devices() device = next(d for d in devices if d["dev_id"] == device_id) nodes = session.get_nodes(device["dev_id"]) node = next(n for n in nodes if n["addr"] == node_addr) session.set_status(device["dev_id"], node, kwargs) @smartbox.command(help="Show node setup") @click.pass_context def setup(ctx): session = ctx.obj["session"] devices = session.get_devices() pp = pprint.PrettyPrinter(indent=4) for device in devices: print(f"{device["name"]} (dev_id: {device["dev_id"]})") nodes = session.get_nodes(device["dev_id"]) for node in nodes: print(f"{node["name"]} (addr: {node["addr"]})") setup = session.get_setup(device["dev_id"], node) pp.pprint(setup) @smartbox.command(help="Set node setup (pass settings as extra args, e.g. mode=auto)") @click.option( "-d", "--device-id", required=True, help="Device ID for node to set setup on" ) @click.option( "-n", "--node-addr", type=int, required=True, help="Address of node to set setup on" ) @click.option("--true-radiant-enabled", type=bool) # TODO: other options @click.pass_context def set_setup(ctx, device_id, node_addr, **kwargs): session = ctx.obj["session"] devices = session.get_devices() device = next(d for d in devices if d["dev_id"] == device_id) nodes = session.get_nodes(device["dev_id"]) node = next(n for n in nodes if n["addr"] == node_addr) session.set_setup(device["dev_id"], node, kwargs) @smartbox.command(help="Show device away_status") @click.pass_context def device_away_status(ctx): session = ctx.obj["session"] devices = session.get_devices() pp = pprint.PrettyPrinter(indent=4) for device in devices: print(f"{device["name"]} (dev_id: {device["dev_id"]})") device_away_status = session.get_device_away_status(device["dev_id"]) pp.pprint(device_away_status) @smartbox.command( help="Set device away_status (pass settings as extra args, e.g. mode=auto)" ) @click.option( "-d", "--device-id", required=True, help="Device ID to set away_status on" ) @click.option("--away", type=bool) @click.option("--enabled", type=bool) @click.option("--forced", type=bool) @click.pass_context def set_device_away_status(ctx, device_id, **kwargs): session = ctx.obj["session"] devices = session.get_devices() device = next(d for d in devices if d["dev_id"] == device_id) session.set_device_away_status(device["dev_id"], kwargs) @smartbox.command(help="Open socket.io connection to device.") @click.option("-d", "--device-id", required=True, help="Device ID to open socket for") @click.pass_context def socket(ctx, device_id): session = ctx.obj["session"] verbose = ctx.obj["verbose"] pp = pprint.PrettyPrinter(indent=4) def on_dev_data(data): _LOGGER.info("Received dev_data:") pp.pprint(data) def on_update(data): _LOGGER.info("Received update:") pp.pprint(data) socket_session = SocketSession( session, device_id, on_dev_data, on_update, verbose, add_sigint_handler=True ) event_loop = asyncio.get_event_loop() task = event_loop.create_task(socket_session.run()) event_loop.run_until_complete(task)
import asyncio import click import logging import pprint from .session import Session from .socket import SocketSession _LOGGER = logging.getLogger(__name__) @click.group(chain=True) @click.option("-a", "--api-name", required=True, help="API name") @click.option( "-b", "--basic-auth-creds", required=True, help="API basic auth credentials" ) @click.option("-u", "--username", required=True, help="API username") @click.option("-p", "--password", required=True, help="API password") @click.option( "-v", "--verbose/--no-verbose", default=False, help="Enable verbose logging" ) @click.pass_context def smartbox(ctx, api_name, basic_auth_creds, username, password, verbose): ctx.ensure_object(dict) logging.basicConfig( format="%(asctime)s %(levelname)-8s [%(name)s.%(funcName)s:%(lineno)d] %(message)s", level=logging.DEBUG if verbose else logging.INFO, datefmt="%Y-%m-%d %H:%M:%S", ) session = Session(api_name, basic_auth_creds, username, password) ctx.obj["session"] = session ctx.obj["verbose"] = verbose @smartbox.command(help="Show devices") @click.pass_context def devices(ctx): session = ctx.obj["session"] devices = session.get_devices() pp = pprint.PrettyPrinter(indent=4) pp.pprint(devices) @smartbox.command(help="Show nodes") @click.pass_context def nodes(ctx): session = ctx.obj["session"] devices = session.get_devices() pp = pprint.PrettyPrinter(indent=4) for device in devices: print(f"{device['name']} (dev_id: {device['dev_id']})") nodes = session.get_nodes(device["dev_id"]) pp.pprint(nodes) @smartbox.command(help="Show node status") @click.pass_context def status(ctx): session = ctx.obj["session"] devices = session.get_devices() pp = pprint.PrettyPrinter(indent=4) for device in devices: print(f"{device['name']} (dev_id: {device['dev_id']})") nodes = session.get_nodes(device["dev_id"]) for node in nodes: print(f"{node['name']} (addr: {node['addr']})") status = session.get_status(device["dev_id"], node) pp.pprint(status) @smartbox.command(help="Set node status (pass settings as extra args, e.g. mode=auto)") @click.option( "-d", "--device-id", required=True, help="Device ID for node to set status on" ) @click.option( "-n", "--node-addr", type=int, required=True, help="Address of node to set status on", ) @click.option("--locked", type=bool) @click.option("--mode") @click.option("--stemp") @click.option("--units") # TODO: other options @click.pass_context def set_status(ctx, device_id, node_addr, **kwargs): session = ctx.obj["session"] devices = session.get_devices() device = next(d for d in devices if d["dev_id"] == device_id) nodes = session.get_nodes(device["dev_id"]) node = next(n for n in nodes if n["addr"] == node_addr) session.set_status(device["dev_id"], node, kwargs) @smartbox.command(help="Show node setup") @click.pass_context def setup(ctx): session = ctx.obj["session"] devices = session.get_devices() pp = pprint.PrettyPrinter(indent=4) for device in devices: print(f"{device['name']} (dev_id: {device['dev_id']})") nodes = session.get_nodes(device["dev_id"]) for node in nodes: print(f"{node['name']} (addr: {node['addr']})") setup = session.get_setup(device["dev_id"], node) pp.pprint(setup) @smartbox.command(help="Set node setup (pass settings as extra args, e.g. mode=auto)") @click.option( "-d", "--device-id", required=True, help="Device ID for node to set setup on" ) @click.option( "-n", "--node-addr", type=int, required=True, help="Address of node to set setup on" ) @click.option("--true-radiant-enabled", type=bool) # TODO: other options @click.pass_context def set_setup(ctx, device_id, node_addr, **kwargs): session = ctx.obj["session"] devices = session.get_devices() device = next(d for d in devices if d["dev_id"] == device_id) nodes = session.get_nodes(device["dev_id"]) node = next(n for n in nodes if n["addr"] == node_addr) session.set_setup(device["dev_id"], node, kwargs) @smartbox.command(help="Show device away_status") @click.pass_context def device_away_status(ctx): session = ctx.obj["session"] devices = session.get_devices() pp = pprint.PrettyPrinter(indent=4) for device in devices: print(f"{device['name']} (dev_id: {device['dev_id']})") device_away_status = session.get_device_away_status(device["dev_id"]) pp.pprint(device_away_status) @smartbox.command( help="Set device away_status (pass settings as extra args, e.g. mode=auto)" ) @click.option( "-d", "--device-id", required=True, help="Device ID to set away_status on" ) @click.option("--away", type=bool) @click.option("--enabled", type=bool) @click.option("--forced", type=bool) @click.pass_context def set_device_away_status(ctx, device_id, **kwargs): session = ctx.obj["session"] devices = session.get_devices() device = next(d for d in devices if d["dev_id"] == device_id) session.set_device_away_status(device["dev_id"], kwargs) @smartbox.command(help="Open socket.io connection to device.") @click.option("-d", "--device-id", required=True, help="Device ID to open socket for") @click.pass_context def socket(ctx, device_id): session = ctx.obj["session"] verbose = ctx.obj["verbose"] pp = pprint.PrettyPrinter(indent=4) def on_dev_data(data): _LOGGER.info("Received dev_data:") pp.pprint(data) def on_update(data): _LOGGER.info("Received update:") pp.pprint(data) socket_session = SocketSession( session, device_id, on_dev_data, on_update, verbose, add_sigint_handler=True ) event_loop = asyncio.get_event_loop() task = event_loop.create_task(socket_session.run()) event_loop.run_until_complete(task)
# Exercício 13: Reajuste Salarial # Descrição: Faça um programa que leia o salário de um funcionário e mostre seu # novo salário, com 15% de aumento. class ReajustadorDeSalario(): porcentagem_de_reajuste = 0.15 def __init(self): self.salario_atual = 0 self.aumento = 0 self.novo_salario = 0 def iniciar(self): '''Área inicial do programa.''' print(f'{' CALCULADORA DE AUMENTO SALARIAL ':*^43}') self.receber_valor_salario() self.reajustar_salario() self.exibir_novo_salario() def receber_valor_salario(self): '''Recebe o valor do salário atual.''' print('Digite o valor do salário atual:') while True: try: salario_atual = float(input()) break except ValueError: print('\nDigite o valor em números, sem espaços.') self.salario_atual = salario_atual return None def reajustar_salario(self): '''Calcula e reajusta salário atual com 15% de aumento.''' salario = self.salario_atual reajuste = reajustador.porcentagem_de_reajuste aumento = salario * reajuste self.novo_salario = salario + aumento self.aumento = aumento return None def exibir_novo_salario(self): '''Recebe o valor reajustado e mostra o resultado.''' print(f'\nO salário de R${self.salario_atual:.2f} será reajustado em R${self.aumento:.2f}.') print(f'Novo salário = R${self.novo_salario:.2f}') print('\nTenha um bom dia!') reajustador = ReajustadorDeSalario() reajustador.iniciar()
# Exercício 13: Reajuste Salarial # Descrição: Faça um programa que leia o salário de um funcionário e mostre seu # novo salário, com 15% de aumento. class ReajustadorDeSalario(): porcentagem_de_reajuste = 0.15 def __init(self): self.salario_atual = 0 self.aumento = 0 self.novo_salario = 0 def iniciar(self): '''Área inicial do programa.''' print(f'{" CALCULADORA DE AUMENTO SALARIAL ":*^43}') self.receber_valor_salario() self.reajustar_salario() self.exibir_novo_salario() def receber_valor_salario(self): '''Recebe o valor do salário atual.''' print('Digite o valor do salário atual:') while True: try: salario_atual = float(input()) break except ValueError: print('\nDigite o valor em números, sem espaços.') self.salario_atual = salario_atual return None def reajustar_salario(self): '''Calcula e reajusta salário atual com 15% de aumento.''' salario = self.salario_atual reajuste = reajustador.porcentagem_de_reajuste aumento = salario * reajuste self.novo_salario = salario + aumento self.aumento = aumento return None def exibir_novo_salario(self): '''Recebe o valor reajustado e mostra o resultado.''' print(f'\nO salário de R${self.salario_atual:.2f} será reajustado em R${self.aumento:.2f}.') print(f'Novo salário = R${self.novo_salario:.2f}') print('\nTenha um bom dia!') reajustador = ReajustadorDeSalario() reajustador.iniciar()
""" COMBINED_SNAPSHOT should be set to create a new snapshot dataset while running this cleaning rule. """ # Python imports import logging # Project imports import constants.bq_utils as bq_consts import constants.cdr_cleaner.clean_cdr as cdr_consts from cdr_cleaner.cleaning_rules import domain_mapping, field_mapping import resources from resources import get_domain_id_field from common import JINJA_ENV from cdr_cleaner.cleaning_rules.domain_mapping import EMPTY_STRING, METADATA_DOMAIN from tools.combine_ehr_rdr import mapping_table_for from utils import bq LOGGER = logging.getLogger(__name__) # issue numbers ISSUE_NUMBERS = ['DC402', 'DC1466'] # Define constants for SQL reserved values AND = ' AND ' NULL_VALUE = 'NULL' UNION_ALL = '\n\tUNION ALL\n' # Define the name of the domain alignment table name DOMAIN_ALIGNMENT_TABLE_NAME = '_logging_domain_alignment' DOMAIN_REROUTE_INCLUDED_INNER_QUERY = JINJA_ENV.from_string(""" SELECT '{{src_table}}' AS src_table, '{{dest_table}}' AS dest_table, {{src_id}} AS src_id, {{dest_id}} AS dest_id, True AS is_rerouted FROM `{{project_id}}.{{dataset_id}}.{{src_table}}` AS s JOIN `{{project_id}}.{{dataset_id}}.concept` AS c ON s.{{domain_concept_id}} = c.concept_id WHERE c.domain_id in ({{domain}}) """) DOMAIN_REROUTE_EXCLUDED_INNER_QUERY = JINJA_ENV.from_string(""" SELECT '{{src_table}}' AS src_table, CAST(NULL AS STRING) AS dest_table, s.{{src_id}} AS src_id, NULL AS dest_id, False AS is_rerouted FROM `{{project_id}}.{{dataset_id}}.{{src_table}}` AS s LEFT JOIN `{{project_id}}.{{dataset_id}}._logging_domain_alignment` AS m ON s.{{src_id}} = m.src_id AND m.src_table = '{{src_table}}' WHERE m.src_id IS NULL """) MAXIMUM_DOMAIN_ID_QUERY = JINJA_ENV.from_string(""" SELECT MAX({{domain_id_field}}) AS max_id FROM `{{project_id}}.{{dataset_id}}.{{domain_table}}` """) DOMAIN_MAPPING_OUTER_QUERY = JINJA_ENV.from_string(""" SELECT u.src_table, u.dest_table, u.src_id, ROW_NUMBER() OVER(ORDER BY u.src_table, u.src_id) + src.max_id AS dest_id, u.is_rerouted FROM ( {{union_query}} ) u CROSS JOIN ( {{domain_query}} ) src """) REROUTE_DOMAIN_RECORD_QUERY = JINJA_ENV.from_string(""" SELECT m.dest_id AS {{dest_domain_id_field}}, {{field_mapping_expr}} FROM `{{project_id}}.{{dataset_id}}.{{src_table}}` AS s JOIN `{{project_id}}.{{dataset_id}}._logging_domain_alignment` AS m ON s.{{src_domain_id_field}} = m.src_id AND m.src_table = '{{src_table}}' AND m.dest_table = '{{dest_table}}' AND m.is_rerouted = True """) SELECT_DOMAIN_RECORD_QUERY = JINJA_ENV.from_string(""" SELECT {{dest_domain_id_field}}, {{field_mapping_expr}} FROM `{{project_id}}.{{dataset_id}}.{{dest_table}}` """) SANDBOX_DOMAIN_RECORD_QUERY_TEMPLATE = JINJA_ENV.from_string(""" SELECT d.* FROM `{{project_id}}.{{dataset_id}}.{{domain_table}}` AS d LEFT JOIN `{{project_id}}.{{dataset_id}}._logging_domain_alignment` AS m ON d.{{domain_table}}_id = m.dest_id AND m.dest_table = '{{domain_table}}' AND m.is_rerouted = True WHERE m.dest_id IS NULL """) CLEAN_DOMAIN_RECORD_QUERY_TEMPLATE = JINJA_ENV.from_string(""" SELECT d.* FROM `{{project_id}}.{{dataset_id}}.{% if is_mapping %}_mapping_{% endif %}{{domain_table}}` AS d LEFT JOIN `{{project_id}}.{{sandbox_dataset_id}}.{{sandbox_table}}` AS s ON d.{{domain_table}}_id = s.{{domain_table}}_id WHERE s.{{domain_table}}_id IS NULL """) REROUTE_DOMAIN_MAPPING_RECORD_QUERY = JINJA_ENV.from_string(""" {% for src_table in src_tables %} {% if loop.previtem is defined %}{{'\n'}}UNION ALL{{'\n\n'}}{% endif %} -- if src_table is the same as dest_table, we want to keep all the records -- {% if src_table == dest_table %} SELECT src.src_{{src_table}}_id, src.{{src_table}}_id, src.src_dataset_id, src.src_hpo_id, src.src_table_id FROM `{{project_id}}.{{dataset_id}}._mapping_{{src_table}}` AS src {% else %} -- if src_table and dest_table are not the same -- -- we want to reroute the mapping records from _mapping_src_table to the _mapping_dest_table -- SELECT src.src_{{src_table}}_id AS src_{{dest_table}}_id, m.dest_id AS {{dest_table}}_id, src.src_dataset_id, src.src_hpo_id, src.src_table_id FROM `{{project_id}}.{{dataset_id}}._logging_domain_alignment` AS m JOIN `{{project_id}}.{{dataset_id}}._mapping_{{src_table}}` AS src ON m.src_id = src.{{src_table}}_id AND m.src_table = '{{src_table}}' AND m.dest_table = '{{dest_table}}' WHERE m.is_rerouted = True {% endif %} {% endfor %} """) CASE_STATEMENT = (' CASE {src_field} ' ' {statements} ' ' ELSE NULL ' ' END AS {dest_field} ') WHEN_STATEMENT = 'WHEN {src_value} THEN {dest_value}' SRC_FIELD_AS_DEST_FIELD = '{src_field} AS {dest_field}' NULL_AS_DEST_FIELD = 'NULL AS {dest_field}' ZERO_AS_DEST_FIELD = '0 AS {dest_field}' def parse_domain_mapping_query_cross_domain(project_id, dataset_id, dest_table): """ This function creates a query that generates id mappings in _logging_domain_alignment for the rerouting records for dest_table :param project_id: the project_id in which the query is run :param dataset_id: the dataset_id in which the query is run :param dest_table: the destination table to which the records are rerouted :return: the query that generates id mappings for the rerouting records """ union_query = EMPTY_STRING domain = resources.get_domain(dest_table) dest_id_field = resources.get_domain_id_field(dest_table) for src_table in domain_mapping.DOMAIN_TABLE_NAMES: if src_table != dest_table and domain_mapping.exist_domain_mappings( src_table, dest_table): src_id_field = resources.get_domain_id_field(src_table) domain_concept_id = resources.get_domain_concept_id(src_table) if union_query != EMPTY_STRING: union_query += UNION_ALL union_query += DOMAIN_REROUTE_INCLUDED_INNER_QUERY.render( project_id=project_id, dataset_id=dataset_id, src_table=src_table, dest_table=dest_table, src_id=src_id_field, dest_id=NULL_VALUE, domain_concept_id=domain_concept_id, domain='\'{}\''.format(domain)) criteria = domain_mapping.get_rerouting_criteria( src_table, dest_table) if criteria != EMPTY_STRING: union_query += AND + criteria output_query = EMPTY_STRING if union_query != EMPTY_STRING: # the query to get the max id for the dest table domain_query = MAXIMUM_DOMAIN_ID_QUERY.render( project_id=project_id, dataset_id=dataset_id, domain_table=dest_table, domain_id_field=dest_id_field) output_query = DOMAIN_MAPPING_OUTER_QUERY.render( union_query=union_query, domain_query=domain_query) return output_query def parse_domain_mapping_query_for_same_domains(project_id, dataset_id): """ This function generates a query that generates id mappings in _logging_domain_alignment for the records being copied to the same domain table :param project_id: the project_id in which the query is run :param dataset_id: the dataset_id in which the query is run :return: a query that generates id mappings for the records that will get copied over to the same domain """ union_query = EMPTY_STRING for domain_table in domain_mapping.DOMAIN_TABLE_NAMES: domain = resources.get_domain(domain_table) domain_id_field = resources.get_domain_id_field(domain_table) domain_concept_id = resources.get_domain_concept_id(domain_table) if union_query != EMPTY_STRING: union_query += UNION_ALL union_query += DOMAIN_REROUTE_INCLUDED_INNER_QUERY.render( project_id=project_id, dataset_id=dataset_id, src_table=domain_table, dest_table=domain_table, src_id=domain_id_field, dest_id=domain_id_field, domain_concept_id=domain_concept_id, domain='\'{}\''.format('\',\''.join([domain, METADATA_DOMAIN]))) return union_query def parse_domain_mapping_query_for_excluded_records(project_id, dataset_id): """ This function generates a query that generates id mappings in _logging_domain_alignment for the records that will get dropped during rerouting because those records either fail the rerouting criteria or rerouting is not possible between src_table and dest_table such as condition_occurrence -> measurement :param project_id: the project_id in which the query is run :param dataset_id: the dataset_id in which the query is run :return: a query that generates id mappings for the records that will get dropped """ union_query = EMPTY_STRING for domain_table in domain_mapping.DOMAIN_TABLE_NAMES: domain_id_field = get_domain_id_field(domain_table) if union_query != EMPTY_STRING: union_query += UNION_ALL union_query += DOMAIN_REROUTE_EXCLUDED_INNER_QUERY.render( project_id=project_id, dataset_id=dataset_id, src_table=domain_table, src_id=domain_id_field, src_domain_id_field=domain_id_field) return union_query def get_domain_mapping_queries(project_id, dataset_id): """ This function generates a list of query dicts for creating id mappings in _logging_domain_alignment. The list will get consumed clean_engine :param project_id: the project_id in which the query is run :param dataset_id: the dataset_id in which the query is run :return: a list of query dicts for creating id mappings in _logging_domain_alignment """ # Create _logging_domain_alignment client = bq.get_client(project_id) table_id = f'{project_id}.{dataset_id}.{DOMAIN_ALIGNMENT_TABLE_NAME}' client.delete_table(table_id, not_found_ok=True) bq.create_tables(client, project_id, [table_id], exists_ok=False) domain_mapping_queries = [] for domain_table in domain_mapping.DOMAIN_TABLE_NAMES: query = parse_domain_mapping_query_cross_domain(project_id, dataset_id, domain_table) domain_mapping_queries.append(query) # Create the query for creating field_mappings for the records moving between the same domain query = parse_domain_mapping_query_for_same_domains(project_id, dataset_id) domain_mapping_queries.append(query) # Create the query for the records that are in the wrong domain but will not be moved query = parse_domain_mapping_query_for_excluded_records( project_id, dataset_id) domain_mapping_queries.append(query) unioned_query = { cdr_consts.QUERY: UNION_ALL.join(domain_mapping_queries), cdr_consts.DESTINATION_TABLE: DOMAIN_ALIGNMENT_TABLE_NAME, cdr_consts.DISPOSITION: bq_consts.WRITE_EMPTY, cdr_consts.DESTINATION_DATASET: dataset_id } return [unioned_query] def resolve_field_mappings(src_table, dest_table): """ This function generates the content of SQL select statement for the given src_table and dest_table. :param src_table: the source CDM table for rerouting :param dest_table: the destination CDM table for rerouting :return: the content of the SQL select statements """ select_statements = [] field_mappings = domain_mapping.get_field_mappings(src_table, dest_table) for dest_field, src_field in field_mappings.items(): if domain_mapping.value_requires_translation(src_table, dest_table, src_field, dest_field): value_mappings = domain_mapping.get_value_mappings( src_table, dest_table, src_field, dest_field) if len(value_mappings) == 0: if field_mapping.is_field_required(dest_table, dest_field): case_statements = ZERO_AS_DEST_FIELD.format( dest_field=dest_field) else: case_statements = NULL_AS_DEST_FIELD.format( dest_field=dest_field) else: case_statements = '\n\t\t'.join([ WHEN_STATEMENT.format(src_value=s, dest_value=d) for d, s in value_mappings.items() ]) case_statements = CASE_STATEMENT.format( src_field=src_field, dest_field=dest_field, statements=case_statements) select_statements.append(case_statements) else: select_statements.append( SRC_FIELD_AS_DEST_FIELD.format(src_field=src_field, dest_field=dest_field)) return ',\n\t'.join(select_statements) def parse_reroute_domain_query(project_id, dataset_id, dest_table): """ This function generates a query that reroutes the records from all domain tables for the given dest_table. It uses _mapping_alignment_table to determine in which domain table the records should land. :param project_id: the project_id in which the query is run :param dataset_id: the dataset_id in which the query is run :param dest_table: the destination CDM table for rerouting :return: a query that reroutes the records from all domain tables for the given dest_table """ union_queries = [] for src_table in domain_mapping.DOMAIN_TABLE_NAMES: src_domain_id_field = get_domain_id_field(src_table) dest_domain_id_field = get_domain_id_field(dest_table) field_mapping_expr = resolve_field_mappings(src_table, dest_table) if src_table == dest_table: # We are doing this to make sure the schema doesn't change and also keep all the # records in the domain table for later rerouting to the other domains union_queries.append( SELECT_DOMAIN_RECORD_QUERY.render( project_id=project_id, dataset_id=dataset_id, dest_table=dest_table, field_mapping_expr=field_mapping_expr, dest_domain_id_field=dest_domain_id_field)) elif domain_mapping.exist_domain_mappings(src_table, dest_table): # We are only rerouting the records between domain tables that are not the same union_queries.append( REROUTE_DOMAIN_RECORD_QUERY.render( project_id=project_id, dataset_id=dataset_id, src_table=src_table, dest_table=dest_table, src_domain_id_field=src_domain_id_field, dest_domain_id_field=dest_domain_id_field, field_mapping_expr=field_mapping_expr)) return UNION_ALL.join(union_queries) def get_reroute_domain_queries(project_id, dataset_id): """ This function creates a new dataset called snapshot_dataset_id and copies all content from dataset_id to it. It generates a list of query dicts for rerouting the records to the corresponding destination table. :param project_id: the project_id in which the query is run :param dataset_id: the dataset_id in which the query is run :return: a list of query dicts for rerouting the records to the corresponding destination table """ queries = [] for domain_table in domain_mapping.DOMAIN_TABLE_NAMES: query = dict() query[cdr_consts.QUERY] = parse_reroute_domain_query( project_id, dataset_id, domain_table) query[cdr_consts.DESTINATION_TABLE] = domain_table query[cdr_consts.DISPOSITION] = bq_consts.WRITE_TRUNCATE query[cdr_consts.DESTINATION_DATASET] = dataset_id query[cdr_consts.BATCH] = True queries.append(query) return queries def get_clean_domain_queries(project_id, dataset_id, sandbox_dataset_id): """ This function generates a list of query dicts for dropping records that do not belong to the domain table after rerouting. :param project_id: the project_id in which the query is run :param dataset_id: the dataset_id in which the query is run :param sandbox_dataset_id: sandbox dataset for dataset_id :return: list of query dicts to run """ queries = [] sandbox_queries = [] for domain_table in domain_mapping.DOMAIN_TABLE_NAMES: sandbox_queries.append({ cdr_consts.QUERY: SANDBOX_DOMAIN_RECORD_QUERY_TEMPLATE.render( project_id=project_id, dataset_id=dataset_id, domain_table=domain_table), cdr_consts.DESTINATION_TABLE: sandbox_name_for(domain_table), cdr_consts.DISPOSITION: bq_consts.WRITE_TRUNCATE, cdr_consts.DESTINATION_DATASET: sandbox_dataset_id }) # add the clean-up query for the domain table queries.append({ cdr_consts.QUERY: CLEAN_DOMAIN_RECORD_QUERY_TEMPLATE.render( project_id=project_id, dataset_id=dataset_id, sandbox_dataset_id=sandbox_dataset_id, domain_table=domain_table, sandbox_table=sandbox_name_for(domain_table), is_mapping=False), cdr_consts.DESTINATION_TABLE: domain_table, cdr_consts.DISPOSITION: bq_consts.WRITE_TRUNCATE, cdr_consts.DESTINATION_DATASET: dataset_id }) # add the clean-up query for the corresponding mapping of the domain table queries.append({ cdr_consts.QUERY: CLEAN_DOMAIN_RECORD_QUERY_TEMPLATE.render( project_id=project_id, dataset_id=dataset_id, sandbox_dataset_id=sandbox_dataset_id, domain_table=domain_table, sandbox_table=sandbox_name_for(domain_table), is_mapping=True), cdr_consts.DESTINATION_TABLE: mapping_table_for(domain_table), cdr_consts.DISPOSITION: bq_consts.WRITE_TRUNCATE, cdr_consts.DESTINATION_DATASET: dataset_id }) return sandbox_queries + queries def get_reroute_domain_mapping_queries(project_id, dataset_id): """ The functions generates a list of query dicts for rerouting the mapping records to the approapriate domain. :param project_id: the project_id in which the query is run :param dataset_id: the dataset_id in which the query is run :return: a list of query dicts for rerouting the mapping records to the corresponding mapping table """ queries = [] for dest_table in domain_mapping.DOMAIN_TABLE_NAMES: # Figure out all possible rerouting source tables for a given destination table src_tables = [ src_table for src_table in domain_mapping.DOMAIN_TABLE_NAMES if (src_table == dest_table) or domain_mapping.exist_domain_mappings(src_table, dest_table) ] queries.append({ cdr_consts.QUERY: REROUTE_DOMAIN_MAPPING_RECORD_QUERY.render( project_id=project_id, dataset_id=dataset_id, src_tables=src_tables, dest_table=dest_table), cdr_consts.DESTINATION_TABLE: mapping_table_for(dest_table), cdr_consts.DISPOSITION: bq_consts.WRITE_TRUNCATE, cdr_consts.DESTINATION_DATASET: dataset_id }) return queries def sandbox_name_for(domain_table): """ This function is used temporarily and can be replaced by the class method once this CR is upgraded to the baseclass :param domain_table: CDM table name :return: sandbox table name for the CDM table """ return f'{'_'.join(ISSUE_NUMBERS).lower()}_{domain_table}' def domain_alignment(project_id, dataset_id, sandbox_dataset_id=None): """ This function returns a list of dictionaries containing query parameters required for applying domain alignment. :param project_id: the project_id in which the query is run :param dataset_id: the dataset_id in which the query is run :param sandbox_dataset_id: Identifies the sandbox dataset to store rows #TODO use sandbox_dataset_id for CR :return: a list of query dicts for rerouting the records to the corresponding destination table """ queries_list = [] queries_list.extend(get_domain_mapping_queries(project_id, dataset_id)) queries_list.extend(get_reroute_domain_queries(project_id, dataset_id)) queries_list.extend( get_reroute_domain_mapping_queries(project_id, dataset_id)) queries_list.extend( get_clean_domain_queries(project_id, dataset_id, sandbox_dataset_id)) return queries_list if __name__ == '__main__': import cdr_cleaner.args_parser as parser import cdr_cleaner.clean_cdr_engine as clean_engine ARGS = parser.parse_args() if ARGS.list_queries: clean_engine.add_console_logging() query_list = clean_engine.get_query_list(ARGS.project_id, ARGS.dataset_id, ARGS.sandbox_dataset_id, [(domain_alignment,)]) for query in query_list: LOGGER.info(query) else: clean_engine.add_console_logging(ARGS.console_log) clean_engine.clean_dataset(ARGS.project_id, ARGS.dataset_id, ARGS.sandbox_dataset_id, [(domain_alignment,)])
""" COMBINED_SNAPSHOT should be set to create a new snapshot dataset while running this cleaning rule. """ # Python imports import logging # Project imports import constants.bq_utils as bq_consts import constants.cdr_cleaner.clean_cdr as cdr_consts from cdr_cleaner.cleaning_rules import domain_mapping, field_mapping import resources from resources import get_domain_id_field from common import JINJA_ENV from cdr_cleaner.cleaning_rules.domain_mapping import EMPTY_STRING, METADATA_DOMAIN from tools.combine_ehr_rdr import mapping_table_for from utils import bq LOGGER = logging.getLogger(__name__) # issue numbers ISSUE_NUMBERS = ['DC402', 'DC1466'] # Define constants for SQL reserved values AND = ' AND ' NULL_VALUE = 'NULL' UNION_ALL = '\n\tUNION ALL\n' # Define the name of the domain alignment table name DOMAIN_ALIGNMENT_TABLE_NAME = '_logging_domain_alignment' DOMAIN_REROUTE_INCLUDED_INNER_QUERY = JINJA_ENV.from_string(""" SELECT '{{src_table}}' AS src_table, '{{dest_table}}' AS dest_table, {{src_id}} AS src_id, {{dest_id}} AS dest_id, True AS is_rerouted FROM `{{project_id}}.{{dataset_id}}.{{src_table}}` AS s JOIN `{{project_id}}.{{dataset_id}}.concept` AS c ON s.{{domain_concept_id}} = c.concept_id WHERE c.domain_id in ({{domain}}) """) DOMAIN_REROUTE_EXCLUDED_INNER_QUERY = JINJA_ENV.from_string(""" SELECT '{{src_table}}' AS src_table, CAST(NULL AS STRING) AS dest_table, s.{{src_id}} AS src_id, NULL AS dest_id, False AS is_rerouted FROM `{{project_id}}.{{dataset_id}}.{{src_table}}` AS s LEFT JOIN `{{project_id}}.{{dataset_id}}._logging_domain_alignment` AS m ON s.{{src_id}} = m.src_id AND m.src_table = '{{src_table}}' WHERE m.src_id IS NULL """) MAXIMUM_DOMAIN_ID_QUERY = JINJA_ENV.from_string(""" SELECT MAX({{domain_id_field}}) AS max_id FROM `{{project_id}}.{{dataset_id}}.{{domain_table}}` """) DOMAIN_MAPPING_OUTER_QUERY = JINJA_ENV.from_string(""" SELECT u.src_table, u.dest_table, u.src_id, ROW_NUMBER() OVER(ORDER BY u.src_table, u.src_id) + src.max_id AS dest_id, u.is_rerouted FROM ( {{union_query}} ) u CROSS JOIN ( {{domain_query}} ) src """) REROUTE_DOMAIN_RECORD_QUERY = JINJA_ENV.from_string(""" SELECT m.dest_id AS {{dest_domain_id_field}}, {{field_mapping_expr}} FROM `{{project_id}}.{{dataset_id}}.{{src_table}}` AS s JOIN `{{project_id}}.{{dataset_id}}._logging_domain_alignment` AS m ON s.{{src_domain_id_field}} = m.src_id AND m.src_table = '{{src_table}}' AND m.dest_table = '{{dest_table}}' AND m.is_rerouted = True """) SELECT_DOMAIN_RECORD_QUERY = JINJA_ENV.from_string(""" SELECT {{dest_domain_id_field}}, {{field_mapping_expr}} FROM `{{project_id}}.{{dataset_id}}.{{dest_table}}` """) SANDBOX_DOMAIN_RECORD_QUERY_TEMPLATE = JINJA_ENV.from_string(""" SELECT d.* FROM `{{project_id}}.{{dataset_id}}.{{domain_table}}` AS d LEFT JOIN `{{project_id}}.{{dataset_id}}._logging_domain_alignment` AS m ON d.{{domain_table}}_id = m.dest_id AND m.dest_table = '{{domain_table}}' AND m.is_rerouted = True WHERE m.dest_id IS NULL """) CLEAN_DOMAIN_RECORD_QUERY_TEMPLATE = JINJA_ENV.from_string(""" SELECT d.* FROM `{{project_id}}.{{dataset_id}}.{% if is_mapping %}_mapping_{% endif %}{{domain_table}}` AS d LEFT JOIN `{{project_id}}.{{sandbox_dataset_id}}.{{sandbox_table}}` AS s ON d.{{domain_table}}_id = s.{{domain_table}}_id WHERE s.{{domain_table}}_id IS NULL """) REROUTE_DOMAIN_MAPPING_RECORD_QUERY = JINJA_ENV.from_string(""" {% for src_table in src_tables %} {% if loop.previtem is defined %}{{'\n'}}UNION ALL{{'\n\n'}}{% endif %} -- if src_table is the same as dest_table, we want to keep all the records -- {% if src_table == dest_table %} SELECT src.src_{{src_table}}_id, src.{{src_table}}_id, src.src_dataset_id, src.src_hpo_id, src.src_table_id FROM `{{project_id}}.{{dataset_id}}._mapping_{{src_table}}` AS src {% else %} -- if src_table and dest_table are not the same -- -- we want to reroute the mapping records from _mapping_src_table to the _mapping_dest_table -- SELECT src.src_{{src_table}}_id AS src_{{dest_table}}_id, m.dest_id AS {{dest_table}}_id, src.src_dataset_id, src.src_hpo_id, src.src_table_id FROM `{{project_id}}.{{dataset_id}}._logging_domain_alignment` AS m JOIN `{{project_id}}.{{dataset_id}}._mapping_{{src_table}}` AS src ON m.src_id = src.{{src_table}}_id AND m.src_table = '{{src_table}}' AND m.dest_table = '{{dest_table}}' WHERE m.is_rerouted = True {% endif %} {% endfor %} """) CASE_STATEMENT = (' CASE {src_field} ' ' {statements} ' ' ELSE NULL ' ' END AS {dest_field} ') WHEN_STATEMENT = 'WHEN {src_value} THEN {dest_value}' SRC_FIELD_AS_DEST_FIELD = '{src_field} AS {dest_field}' NULL_AS_DEST_FIELD = 'NULL AS {dest_field}' ZERO_AS_DEST_FIELD = '0 AS {dest_field}' def parse_domain_mapping_query_cross_domain(project_id, dataset_id, dest_table): """ This function creates a query that generates id mappings in _logging_domain_alignment for the rerouting records for dest_table :param project_id: the project_id in which the query is run :param dataset_id: the dataset_id in which the query is run :param dest_table: the destination table to which the records are rerouted :return: the query that generates id mappings for the rerouting records """ union_query = EMPTY_STRING domain = resources.get_domain(dest_table) dest_id_field = resources.get_domain_id_field(dest_table) for src_table in domain_mapping.DOMAIN_TABLE_NAMES: if src_table != dest_table and domain_mapping.exist_domain_mappings( src_table, dest_table): src_id_field = resources.get_domain_id_field(src_table) domain_concept_id = resources.get_domain_concept_id(src_table) if union_query != EMPTY_STRING: union_query += UNION_ALL union_query += DOMAIN_REROUTE_INCLUDED_INNER_QUERY.render( project_id=project_id, dataset_id=dataset_id, src_table=src_table, dest_table=dest_table, src_id=src_id_field, dest_id=NULL_VALUE, domain_concept_id=domain_concept_id, domain='\'{}\''.format(domain)) criteria = domain_mapping.get_rerouting_criteria( src_table, dest_table) if criteria != EMPTY_STRING: union_query += AND + criteria output_query = EMPTY_STRING if union_query != EMPTY_STRING: # the query to get the max id for the dest table domain_query = MAXIMUM_DOMAIN_ID_QUERY.render( project_id=project_id, dataset_id=dataset_id, domain_table=dest_table, domain_id_field=dest_id_field) output_query = DOMAIN_MAPPING_OUTER_QUERY.render( union_query=union_query, domain_query=domain_query) return output_query def parse_domain_mapping_query_for_same_domains(project_id, dataset_id): """ This function generates a query that generates id mappings in _logging_domain_alignment for the records being copied to the same domain table :param project_id: the project_id in which the query is run :param dataset_id: the dataset_id in which the query is run :return: a query that generates id mappings for the records that will get copied over to the same domain """ union_query = EMPTY_STRING for domain_table in domain_mapping.DOMAIN_TABLE_NAMES: domain = resources.get_domain(domain_table) domain_id_field = resources.get_domain_id_field(domain_table) domain_concept_id = resources.get_domain_concept_id(domain_table) if union_query != EMPTY_STRING: union_query += UNION_ALL union_query += DOMAIN_REROUTE_INCLUDED_INNER_QUERY.render( project_id=project_id, dataset_id=dataset_id, src_table=domain_table, dest_table=domain_table, src_id=domain_id_field, dest_id=domain_id_field, domain_concept_id=domain_concept_id, domain='\'{}\''.format('\',\''.join([domain, METADATA_DOMAIN]))) return union_query def parse_domain_mapping_query_for_excluded_records(project_id, dataset_id): """ This function generates a query that generates id mappings in _logging_domain_alignment for the records that will get dropped during rerouting because those records either fail the rerouting criteria or rerouting is not possible between src_table and dest_table such as condition_occurrence -> measurement :param project_id: the project_id in which the query is run :param dataset_id: the dataset_id in which the query is run :return: a query that generates id mappings for the records that will get dropped """ union_query = EMPTY_STRING for domain_table in domain_mapping.DOMAIN_TABLE_NAMES: domain_id_field = get_domain_id_field(domain_table) if union_query != EMPTY_STRING: union_query += UNION_ALL union_query += DOMAIN_REROUTE_EXCLUDED_INNER_QUERY.render( project_id=project_id, dataset_id=dataset_id, src_table=domain_table, src_id=domain_id_field, src_domain_id_field=domain_id_field) return union_query def get_domain_mapping_queries(project_id, dataset_id): """ This function generates a list of query dicts for creating id mappings in _logging_domain_alignment. The list will get consumed clean_engine :param project_id: the project_id in which the query is run :param dataset_id: the dataset_id in which the query is run :return: a list of query dicts for creating id mappings in _logging_domain_alignment """ # Create _logging_domain_alignment client = bq.get_client(project_id) table_id = f'{project_id}.{dataset_id}.{DOMAIN_ALIGNMENT_TABLE_NAME}' client.delete_table(table_id, not_found_ok=True) bq.create_tables(client, project_id, [table_id], exists_ok=False) domain_mapping_queries = [] for domain_table in domain_mapping.DOMAIN_TABLE_NAMES: query = parse_domain_mapping_query_cross_domain(project_id, dataset_id, domain_table) domain_mapping_queries.append(query) # Create the query for creating field_mappings for the records moving between the same domain query = parse_domain_mapping_query_for_same_domains(project_id, dataset_id) domain_mapping_queries.append(query) # Create the query for the records that are in the wrong domain but will not be moved query = parse_domain_mapping_query_for_excluded_records( project_id, dataset_id) domain_mapping_queries.append(query) unioned_query = { cdr_consts.QUERY: UNION_ALL.join(domain_mapping_queries), cdr_consts.DESTINATION_TABLE: DOMAIN_ALIGNMENT_TABLE_NAME, cdr_consts.DISPOSITION: bq_consts.WRITE_EMPTY, cdr_consts.DESTINATION_DATASET: dataset_id } return [unioned_query] def resolve_field_mappings(src_table, dest_table): """ This function generates the content of SQL select statement for the given src_table and dest_table. :param src_table: the source CDM table for rerouting :param dest_table: the destination CDM table for rerouting :return: the content of the SQL select statements """ select_statements = [] field_mappings = domain_mapping.get_field_mappings(src_table, dest_table) for dest_field, src_field in field_mappings.items(): if domain_mapping.value_requires_translation(src_table, dest_table, src_field, dest_field): value_mappings = domain_mapping.get_value_mappings( src_table, dest_table, src_field, dest_field) if len(value_mappings) == 0: if field_mapping.is_field_required(dest_table, dest_field): case_statements = ZERO_AS_DEST_FIELD.format( dest_field=dest_field) else: case_statements = NULL_AS_DEST_FIELD.format( dest_field=dest_field) else: case_statements = '\n\t\t'.join([ WHEN_STATEMENT.format(src_value=s, dest_value=d) for d, s in value_mappings.items() ]) case_statements = CASE_STATEMENT.format( src_field=src_field, dest_field=dest_field, statements=case_statements) select_statements.append(case_statements) else: select_statements.append( SRC_FIELD_AS_DEST_FIELD.format(src_field=src_field, dest_field=dest_field)) return ',\n\t'.join(select_statements) def parse_reroute_domain_query(project_id, dataset_id, dest_table): """ This function generates a query that reroutes the records from all domain tables for the given dest_table. It uses _mapping_alignment_table to determine in which domain table the records should land. :param project_id: the project_id in which the query is run :param dataset_id: the dataset_id in which the query is run :param dest_table: the destination CDM table for rerouting :return: a query that reroutes the records from all domain tables for the given dest_table """ union_queries = [] for src_table in domain_mapping.DOMAIN_TABLE_NAMES: src_domain_id_field = get_domain_id_field(src_table) dest_domain_id_field = get_domain_id_field(dest_table) field_mapping_expr = resolve_field_mappings(src_table, dest_table) if src_table == dest_table: # We are doing this to make sure the schema doesn't change and also keep all the # records in the domain table for later rerouting to the other domains union_queries.append( SELECT_DOMAIN_RECORD_QUERY.render( project_id=project_id, dataset_id=dataset_id, dest_table=dest_table, field_mapping_expr=field_mapping_expr, dest_domain_id_field=dest_domain_id_field)) elif domain_mapping.exist_domain_mappings(src_table, dest_table): # We are only rerouting the records between domain tables that are not the same union_queries.append( REROUTE_DOMAIN_RECORD_QUERY.render( project_id=project_id, dataset_id=dataset_id, src_table=src_table, dest_table=dest_table, src_domain_id_field=src_domain_id_field, dest_domain_id_field=dest_domain_id_field, field_mapping_expr=field_mapping_expr)) return UNION_ALL.join(union_queries) def get_reroute_domain_queries(project_id, dataset_id): """ This function creates a new dataset called snapshot_dataset_id and copies all content from dataset_id to it. It generates a list of query dicts for rerouting the records to the corresponding destination table. :param project_id: the project_id in which the query is run :param dataset_id: the dataset_id in which the query is run :return: a list of query dicts for rerouting the records to the corresponding destination table """ queries = [] for domain_table in domain_mapping.DOMAIN_TABLE_NAMES: query = dict() query[cdr_consts.QUERY] = parse_reroute_domain_query( project_id, dataset_id, domain_table) query[cdr_consts.DESTINATION_TABLE] = domain_table query[cdr_consts.DISPOSITION] = bq_consts.WRITE_TRUNCATE query[cdr_consts.DESTINATION_DATASET] = dataset_id query[cdr_consts.BATCH] = True queries.append(query) return queries def get_clean_domain_queries(project_id, dataset_id, sandbox_dataset_id): """ This function generates a list of query dicts for dropping records that do not belong to the domain table after rerouting. :param project_id: the project_id in which the query is run :param dataset_id: the dataset_id in which the query is run :param sandbox_dataset_id: sandbox dataset for dataset_id :return: list of query dicts to run """ queries = [] sandbox_queries = [] for domain_table in domain_mapping.DOMAIN_TABLE_NAMES: sandbox_queries.append({ cdr_consts.QUERY: SANDBOX_DOMAIN_RECORD_QUERY_TEMPLATE.render( project_id=project_id, dataset_id=dataset_id, domain_table=domain_table), cdr_consts.DESTINATION_TABLE: sandbox_name_for(domain_table), cdr_consts.DISPOSITION: bq_consts.WRITE_TRUNCATE, cdr_consts.DESTINATION_DATASET: sandbox_dataset_id }) # add the clean-up query for the domain table queries.append({ cdr_consts.QUERY: CLEAN_DOMAIN_RECORD_QUERY_TEMPLATE.render( project_id=project_id, dataset_id=dataset_id, sandbox_dataset_id=sandbox_dataset_id, domain_table=domain_table, sandbox_table=sandbox_name_for(domain_table), is_mapping=False), cdr_consts.DESTINATION_TABLE: domain_table, cdr_consts.DISPOSITION: bq_consts.WRITE_TRUNCATE, cdr_consts.DESTINATION_DATASET: dataset_id }) # add the clean-up query for the corresponding mapping of the domain table queries.append({ cdr_consts.QUERY: CLEAN_DOMAIN_RECORD_QUERY_TEMPLATE.render( project_id=project_id, dataset_id=dataset_id, sandbox_dataset_id=sandbox_dataset_id, domain_table=domain_table, sandbox_table=sandbox_name_for(domain_table), is_mapping=True), cdr_consts.DESTINATION_TABLE: mapping_table_for(domain_table), cdr_consts.DISPOSITION: bq_consts.WRITE_TRUNCATE, cdr_consts.DESTINATION_DATASET: dataset_id }) return sandbox_queries + queries def get_reroute_domain_mapping_queries(project_id, dataset_id): """ The functions generates a list of query dicts for rerouting the mapping records to the approapriate domain. :param project_id: the project_id in which the query is run :param dataset_id: the dataset_id in which the query is run :return: a list of query dicts for rerouting the mapping records to the corresponding mapping table """ queries = [] for dest_table in domain_mapping.DOMAIN_TABLE_NAMES: # Figure out all possible rerouting source tables for a given destination table src_tables = [ src_table for src_table in domain_mapping.DOMAIN_TABLE_NAMES if (src_table == dest_table) or domain_mapping.exist_domain_mappings(src_table, dest_table) ] queries.append({ cdr_consts.QUERY: REROUTE_DOMAIN_MAPPING_RECORD_QUERY.render( project_id=project_id, dataset_id=dataset_id, src_tables=src_tables, dest_table=dest_table), cdr_consts.DESTINATION_TABLE: mapping_table_for(dest_table), cdr_consts.DISPOSITION: bq_consts.WRITE_TRUNCATE, cdr_consts.DESTINATION_DATASET: dataset_id }) return queries def sandbox_name_for(domain_table): """ This function is used temporarily and can be replaced by the class method once this CR is upgraded to the baseclass :param domain_table: CDM table name :return: sandbox table name for the CDM table """ return f'{"_".join(ISSUE_NUMBERS).lower()}_{domain_table}' def domain_alignment(project_id, dataset_id, sandbox_dataset_id=None): """ This function returns a list of dictionaries containing query parameters required for applying domain alignment. :param project_id: the project_id in which the query is run :param dataset_id: the dataset_id in which the query is run :param sandbox_dataset_id: Identifies the sandbox dataset to store rows #TODO use sandbox_dataset_id for CR :return: a list of query dicts for rerouting the records to the corresponding destination table """ queries_list = [] queries_list.extend(get_domain_mapping_queries(project_id, dataset_id)) queries_list.extend(get_reroute_domain_queries(project_id, dataset_id)) queries_list.extend( get_reroute_domain_mapping_queries(project_id, dataset_id)) queries_list.extend( get_clean_domain_queries(project_id, dataset_id, sandbox_dataset_id)) return queries_list if __name__ == '__main__': import cdr_cleaner.args_parser as parser import cdr_cleaner.clean_cdr_engine as clean_engine ARGS = parser.parse_args() if ARGS.list_queries: clean_engine.add_console_logging() query_list = clean_engine.get_query_list(ARGS.project_id, ARGS.dataset_id, ARGS.sandbox_dataset_id, [(domain_alignment,)]) for query in query_list: LOGGER.info(query) else: clean_engine.add_console_logging(ARGS.console_log) clean_engine.clean_dataset(ARGS.project_id, ARGS.dataset_id, ARGS.sandbox_dataset_id, [(domain_alignment,)])
from screen import Screen import cv2 from config import Config from template_finder import TemplateFinder from utils.misc import load_template, cut_roi import mouse import keyboard import os import shutil from pathlib import Path from typing import Tuple import math class NodeRecorder: def __init__(self, screen: Screen, config: Config, run_name): if os.path.exists("generated"): for path in Path("generated").glob("**/*"): if path.is_file(): os.remove(path) elif path.is_dir(): shutil.rmtree(path) shutil.rmtree("generated") os.system("mkdir generated") os.system(f"cd generated && mkdir templates && cd templates && mkdir {run_name} && cd {run_name} && mkdir nodes") self._run_name = run_name self._offset = 100 self._template_counter = 0 self._half_width = config.ui_pos["screen_width"] // 2 self._half_height = config.ui_pos["screen_height"] // 2 self._screen = screen self._curr_state = 0 self._upper_left = None self._template_finder = TemplateFinder(self._screen) self._template_finder._templates = {} self._pather_code_file = "generated/pather_generated.py" self.ref_points = {} self.nodes = {} self.debug_node_pos = {} # Starting with template recording: print("1 - Select top-left corner and press f8") @staticmethod def _convert_rel_to_abs(rel_loc: Tuple[float, float], pos_abs: Tuple[float, float]) -> Tuple[float, float]: return (rel_loc[0] + pos_abs[0], rel_loc[1] + pos_abs[1]) def find_templates(self, img): ref_points = {} for key in self._template_finder._templates: found = self._template_finder.search(key, img, use_grayscale=False, threshold=0.77) if found.valid: ref_points[key] = found.center return ref_points def hook(self, e): if e.event_type == "down": if e.name == "f12": os._exit(1) self.ref_points = {} self.debug_node_pos = {} img = self._screen.grab() loc_monitor = mouse.get_position() loc_screen = self._screen.convert_monitor_to_screen(loc_monitor) if e.name == "f8" and self._curr_state == 0: # create a tempalte if self._upper_left is None: self._upper_left = loc_screen print("-- Select bottom-right corner and press f8") return else: bottom_right = loc_screen width = (bottom_right[0] - self._upper_left[0]) height = (bottom_right[1] - self._upper_left[1]) ref_point_name = f"{self._run_name}_{self._template_counter}" self._template_counter += 1 # save as png template_img = cut_roi(img, [*self._upper_left, width, height]) template_path = f"generated/templates/{self._run_name}/{ref_point_name}.png" cv2.imwrite(template_path, template_img) self._upper_left = None template_img = load_template(template_path, 1.0, False) self._template_finder._templates[ref_point_name] = [template_img, cv2.cvtColor(template_img, cv2.COLOR_BGRA2GRAY), 1.0, None] elif e.name == "f7": self.ref_points = {} else: self.ref_points = self.find_templates(img) if e.name == "f9": # add current loc screen as node new_node_idx = self._offset + len(self.nodes) self.nodes[new_node_idx] = {} for key in self.ref_points: rel_loc = (loc_screen[0] - self.ref_points[key][0], loc_screen[1] - self.ref_points[key][1]) self.nodes[new_node_idx][key] = rel_loc if e.name == "f10" or e.name == "f9" and self.ref_points is not None: # find all nodes: for node_idx in self.nodes: # try to find the screen coordinate of the node node_screen_pos = None for template_key in self.nodes[node_idx]: if template_key in self.ref_points: ref_pos_screen = self.ref_points[template_key] # Get reference position of template in abs coordinates ref_pos_abs = self._screen.convert_screen_to_abs(ref_pos_screen) # Calc the abs node position with the relative coordinates (relative to ref) node_pos_rel = self.nodes[node_idx][template_key] node_pos_abs = self._convert_rel_to_abs(node_pos_rel, ref_pos_abs) node_screen_pos = self._screen.convert_abs_to_screen(node_pos_abs) self.debug_node_pos[node_idx] = node_screen_pos break # if it was found try to add all other visible templates to it that are not already included if node_screen_pos is not None: for template_key in self.ref_points: if template_key not in self.nodes[node_idx]: rel_loc = (node_screen_pos[0] - self.ref_points[template_key][0], node_screen_pos[1] - self.ref_points[template_key][1]) self.nodes[node_idx][template_key] = rel_loc # print info to console and write code f = open(self._pather_code_file, 'w') print("---- Current Recorded Nodes: ----") for k in self.nodes: print(self.nodes[k]) new_path = [] for template in self.nodes[k]: dist = math.dist((0, 0), self.nodes[k][template]) new_path.append({"key": template, "pos": self.nodes[k][template], "dist": dist}) results = sorted(new_path, key=lambda r: r["dist"]) code = f"{k}: " + "{" for i, res in enumerate(results): if res["dist"] < 1100 and i < 8: code += f'"{res['key'].upper()}": {res['pos']}, ' f.write(code + "}\n") f.close() print("") print("f8: Create Template | f9: New node at cursor | f10: update nodes with visible templates") if __name__ == "__main__": keyboard.add_hotkey('f12', lambda: print('Force Exit (f12)') or os._exit(1)) print("Enter run name...") run_name = input() config = Config() screen = Screen() recorder = NodeRecorder(screen, config, run_name) keyboard.hook(recorder.hook, suppress=True) while 1: img = screen.grab().copy() try: for key in recorder.debug_node_pos: cv2.circle(img, recorder.debug_node_pos[key], 8, (0, 0, 255), 4) cv2.putText(img, str(key), recorder.debug_node_pos[key], cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA) for key in recorder.ref_points: cv2.circle(img, recorder.ref_points[key], 8, (0, 255, 0), 4) cv2.putText(img, key, recorder.ref_points[key], cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA) except Exception: pass img = cv2.resize(img, None, fx=0.5, fy=0.5) cv2.imshow("vis", img) cv2.waitKey(1)
from screen import Screen import cv2 from config import Config from template_finder import TemplateFinder from utils.misc import load_template, cut_roi import mouse import keyboard import os import shutil from pathlib import Path from typing import Tuple import math class NodeRecorder: def __init__(self, screen: Screen, config: Config, run_name): if os.path.exists("generated"): for path in Path("generated").glob("**/*"): if path.is_file(): os.remove(path) elif path.is_dir(): shutil.rmtree(path) shutil.rmtree("generated") os.system("mkdir generated") os.system(f"cd generated && mkdir templates && cd templates && mkdir {run_name} && cd {run_name} && mkdir nodes") self._run_name = run_name self._offset = 100 self._template_counter = 0 self._half_width = config.ui_pos["screen_width"] // 2 self._half_height = config.ui_pos["screen_height"] // 2 self._screen = screen self._curr_state = 0 self._upper_left = None self._template_finder = TemplateFinder(self._screen) self._template_finder._templates = {} self._pather_code_file = "generated/pather_generated.py" self.ref_points = {} self.nodes = {} self.debug_node_pos = {} # Starting with template recording: print("1 - Select top-left corner and press f8") @staticmethod def _convert_rel_to_abs(rel_loc: Tuple[float, float], pos_abs: Tuple[float, float]) -> Tuple[float, float]: return (rel_loc[0] + pos_abs[0], rel_loc[1] + pos_abs[1]) def find_templates(self, img): ref_points = {} for key in self._template_finder._templates: found = self._template_finder.search(key, img, use_grayscale=False, threshold=0.77) if found.valid: ref_points[key] = found.center return ref_points def hook(self, e): if e.event_type == "down": if e.name == "f12": os._exit(1) self.ref_points = {} self.debug_node_pos = {} img = self._screen.grab() loc_monitor = mouse.get_position() loc_screen = self._screen.convert_monitor_to_screen(loc_monitor) if e.name == "f8" and self._curr_state == 0: # create a tempalte if self._upper_left is None: self._upper_left = loc_screen print("-- Select bottom-right corner and press f8") return else: bottom_right = loc_screen width = (bottom_right[0] - self._upper_left[0]) height = (bottom_right[1] - self._upper_left[1]) ref_point_name = f"{self._run_name}_{self._template_counter}" self._template_counter += 1 # save as png template_img = cut_roi(img, [*self._upper_left, width, height]) template_path = f"generated/templates/{self._run_name}/{ref_point_name}.png" cv2.imwrite(template_path, template_img) self._upper_left = None template_img = load_template(template_path, 1.0, False) self._template_finder._templates[ref_point_name] = [template_img, cv2.cvtColor(template_img, cv2.COLOR_BGRA2GRAY), 1.0, None] elif e.name == "f7": self.ref_points = {} else: self.ref_points = self.find_templates(img) if e.name == "f9": # add current loc screen as node new_node_idx = self._offset + len(self.nodes) self.nodes[new_node_idx] = {} for key in self.ref_points: rel_loc = (loc_screen[0] - self.ref_points[key][0], loc_screen[1] - self.ref_points[key][1]) self.nodes[new_node_idx][key] = rel_loc if e.name == "f10" or e.name == "f9" and self.ref_points is not None: # find all nodes: for node_idx in self.nodes: # try to find the screen coordinate of the node node_screen_pos = None for template_key in self.nodes[node_idx]: if template_key in self.ref_points: ref_pos_screen = self.ref_points[template_key] # Get reference position of template in abs coordinates ref_pos_abs = self._screen.convert_screen_to_abs(ref_pos_screen) # Calc the abs node position with the relative coordinates (relative to ref) node_pos_rel = self.nodes[node_idx][template_key] node_pos_abs = self._convert_rel_to_abs(node_pos_rel, ref_pos_abs) node_screen_pos = self._screen.convert_abs_to_screen(node_pos_abs) self.debug_node_pos[node_idx] = node_screen_pos break # if it was found try to add all other visible templates to it that are not already included if node_screen_pos is not None: for template_key in self.ref_points: if template_key not in self.nodes[node_idx]: rel_loc = (node_screen_pos[0] - self.ref_points[template_key][0], node_screen_pos[1] - self.ref_points[template_key][1]) self.nodes[node_idx][template_key] = rel_loc # print info to console and write code f = open(self._pather_code_file, 'w') print("---- Current Recorded Nodes: ----") for k in self.nodes: print(self.nodes[k]) new_path = [] for template in self.nodes[k]: dist = math.dist((0, 0), self.nodes[k][template]) new_path.append({"key": template, "pos": self.nodes[k][template], "dist": dist}) results = sorted(new_path, key=lambda r: r["dist"]) code = f"{k}: " + "{" for i, res in enumerate(results): if res["dist"] < 1100 and i < 8: code += f'"{res["key"].upper()}": {res["pos"]}, ' f.write(code + "}\n") f.close() print("") print("f8: Create Template | f9: New node at cursor | f10: update nodes with visible templates") if __name__ == "__main__": keyboard.add_hotkey('f12', lambda: print('Force Exit (f12)') or os._exit(1)) print("Enter run name...") run_name = input() config = Config() screen = Screen() recorder = NodeRecorder(screen, config, run_name) keyboard.hook(recorder.hook, suppress=True) while 1: img = screen.grab().copy() try: for key in recorder.debug_node_pos: cv2.circle(img, recorder.debug_node_pos[key], 8, (0, 0, 255), 4) cv2.putText(img, str(key), recorder.debug_node_pos[key], cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA) for key in recorder.ref_points: cv2.circle(img, recorder.ref_points[key], 8, (0, 255, 0), 4) cv2.putText(img, key, recorder.ref_points[key], cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA) except Exception: pass img = cv2.resize(img, None, fx=0.5, fy=0.5) cv2.imshow("vis", img) cv2.waitKey(1)
# Copyright 2019 IBM 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 sklearn import sklearn.ensemble import lale.docstrings import lale.operators class GradientBoostingClassifierImpl: def __init__(self, **hyperparams): self._hyperparams = hyperparams self._wrapped_model = sklearn.ensemble.GradientBoostingClassifier( **self._hyperparams ) def fit(self, X, y, **fit_params): self._wrapped_model.fit(X, y, **fit_params) return self def predict(self, X): return self._wrapped_model.predict(X) def predict_proba(self, X): return self._wrapped_model.predict_proba(X) def decision_function(self, X): return self._wrapped_model.decision_function(X) _hyperparams_schema = { "description": "Gradient Boosting for classification.", "allOf": [ { "type": "object", "required": ["init", "presort"], "relevantToOptimizer": [ "loss", "n_estimators", "min_samples_split", "min_samples_leaf", "max_depth", "max_features", "presort", ], "additionalProperties": False, "properties": { "loss": { "enum": ["deviance", "exponential"], "default": "deviance", "description": "loss function to be optimized. 'deviance' refers to", }, "learning_rate": { "type": "number", "minimumForOptimizer": 0.01, "maximumForOptimizer": 1.0, "distribution": "loguniform", "default": 0.1, "description": "learning rate shrinks the contribution of each tree by `learning_rate`.", }, "n_estimators": { "type": "integer", "minimumForOptimizer": 10, "maximumForOptimizer": 100, "distribution": "uniform", "default": 100, "description": "The number of boosting stages to perform. Gradient boosting", }, "subsample": { "type": "number", "minimumForOptimizer": 0.01, "maximumForOptimizer": 1.0, "distribution": "uniform", "default": 1.0, "description": "The fraction of samples to be used for fitting the individual base", }, "criterion": { "enum": ["friedman_mse", "mse", "mae"], "default": "friedman_mse", "description": "The function to measure the quality of a split. Supported criteria", }, "min_samples_split": { "anyOf": [ { "type": "integer", "minimumForOptimizer": 2, "maximumForOptimizer": 20, "distribution": "uniform", }, { "type": "number", "minimumForOptimizer": 0.01, "maximumForOptimizer": 0.5, "default": 0.05, }, ], "default": 2, "description": "The minimum number of samples required to split an internal node:", }, "min_samples_leaf": { "anyOf": [ { "type": "integer", "minimumForOptimizer": 1, "maximumForOptimizer": 20, "distribution": "uniform", }, { "type": "number", "minimumForOptimizer": 0.01, "maximumForOptimizer": 0.5, "default": 0.05, }, ], "default": 1, "description": "The minimum number of samples required to be at a leaf node.", }, "min_weight_fraction_leaf": { "type": "number", "default": 0.0, "description": "The minimum weighted fraction of the sum total of weights (of all", }, "max_depth": { "type": "integer", "minimumForOptimizer": 3, "maximumForOptimizer": 5, "default": 3, "description": "maximum depth of the individual regression estimators. The maximum", }, "min_impurity_decrease": { "type": "number", "default": 0.0, "description": "A node will be split if this split induces a decrease of the impurity", }, "min_impurity_split": { "anyOf": [{"type": "number"}, {"enum": [None]}], "default": None, "description": "Threshold for early stopping in tree growth. A node will split", }, "init": { "anyOf": [{"type": "object"}, {"enum": ["zero", None]}], "default": None, "description": "An estimator object that is used to compute the initial", }, "random_state": { "anyOf": [ {"type": "integer"}, {"laleType": "numpy.random.RandomState"}, {"enum": [None]}, ], "default": None, "description": "If int, random_state is the seed used by the random number generator;", }, "max_features": { "anyOf": [ {"type": "integer", "minimum": 1, "forOptimizer": False}, { "type": "number", "minimum": 0.0, "exclusiveMinimum": True, "maximum": 1.0, "exclusiveMaximum": True, "minimumForOptimizer": 0.01, "default": 0.5, "distribution": "uniform", }, {"enum": ["auto", "sqrt", "log2", None]}, ], "default": None, "description": "The number of features to consider when looking for the best split.", }, "verbose": { "type": "integer", "default": 0, "description": "Enable verbose output. If 1 then it prints progress and performance", }, "max_leaf_nodes": { "anyOf": [{"type": "integer"}, {"enum": [None]}], "default": None, "description": "Grow trees with ``max_leaf_nodes`` in best-first fashion.", }, "warm_start": { "type": "boolean", "default": False, "description": "When set to ``True``, reuse the solution of the previous call to fit", }, "presort": { "anyOf": [{"type": "boolean"}, {"enum": ["auto"]}], "default": "auto", "description": "Whether to presort the data to speed up the finding of best splits in", }, "validation_fraction": { "type": "number", "default": 0.1, "description": "The proportion of training data to set aside as validation set for", }, "n_iter_no_change": { "anyOf": [ { "type": "integer", "minimumForOptimizer": 5, "maximumForOptimizer": 10, }, {"enum": [None]}, ], "default": None, "description": "``n_iter_no_change`` is used to decide if early stopping will be used", }, "tol": { "type": "number", "minimumForOptimizer": 1e-08, "maximumForOptimizer": 0.01, "distribution": "loguniform", "default": 0.0001, "description": "Tolerance for the early stopping. When the loss is not improving", }, }, } ], } _input_fit_schema = { "description": "Fit the gradient boosting model.", "type": "object", "required": ["X", "y"], "properties": { "X": { "type": "array", "items": {"type": "array", "items": {"type": "number"},}, "description": "The input samples. Internally, it will be converted to", }, "y": { "anyOf": [ {"type": "array", "items": {"type": "number"}}, {"type": "array", "items": {"type": "string"}}, {"type": "array", "items": {"type": "boolean"}}, ], "description": "Target values (strings or integers in classification, real numbers", }, "sample_weight": { "anyOf": [ {"type": "array", "items": {"type": "number"},}, {"enum": [None]}, ], "default": None, "description": "Sample weights. If None, then samples are equally weighted. Splits", }, "monitor": { "anyOf": [{"laleType": "callable"}, {"enum": [None]}], "default": None, "description": "The monitor is called after each iteration with the current the current iteration, a reference to the estimator and the local variables of _fit_stages as keyword arguments callable(i, self, locals()).", }, }, } _input_predict_schema = { "description": "Predict class for X.", "type": "object", "properties": { "X": { "type": "array", "items": {"type": "array", "items": {"type": "number"},}, "description": "The input samples. Internally, it will be converted to", }, }, } _output_predict_schema = { "description": "The predicted values.", "anyOf": [ {"type": "array", "items": {"type": "number"}}, {"type": "array", "items": {"type": "string"}}, {"type": "array", "items": {"type": "boolean"}}, ], } _input_predict_proba_schema = { "description": "Predict class probabilities for X.", "type": "object", "properties": { "X": { "type": "array", "items": {"type": "array", "items": {"type": "number"},}, "description": "The input samples. Internally, it will be converted to", }, }, } _output_predict_proba_schema = { "description": "The class probabilities of the input samples. The order of the", "type": "array", "items": {"type": "array", "items": {"type": "number"},}, } _input_decision_function_schema = { "type": "object", "required": ["X"], "additionalProperties": False, "properties": { "X": { "description": "Features; the outer array is over samples.", "type": "array", "items": {"type": "array", "items": {"type": "number"}}, } }, } _output_decision_function_schema = { "description": "Confidence scores for samples for each class in the model.", "anyOf": [ { "description": "In the multi-way case, score per (sample, class) combination.", "type": "array", "items": {"type": "array", "items": {"type": "number"}}, }, { "description": "In the binary case, score for `self._classes[1]`.", "type": "array", "items": {"type": "number"}, }, ], } _combined_schemas = { "$schema": "http://json-schema.org/draft-04/schema#", "description": """`Gradient boosting classifier`_ random forest from scikit-learn. .. _`Gradient boosting classifier`: https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingClassifier.html """, "documentation_url": "https://lale.readthedocs.io/en/latest/modules/lale.lib.sklearn.gradient_boosting_classifier.html", "import_from": "sklearn.ensemble", "type": "object", "tags": {"pre": [], "op": ["estimator", "classifier"], "post": []}, "properties": { "hyperparams": _hyperparams_schema, "input_fit": _input_fit_schema, "input_predict": _input_predict_schema, "output_predict": _output_predict_schema, "input_predict_proba": _input_predict_proba_schema, "output_predict_proba": _output_predict_proba_schema, "input_decision_function": _input_decision_function_schema, "output_decision_function": _output_decision_function_schema, }, } GradientBoostingClassifier: lale.operators.PlannedIndividualOp GradientBoostingClassifier = lale.operators.make_operator( GradientBoostingClassifierImpl, _combined_schemas ) if sklearn.__version__ >= "0.22": # old: https://scikit-learn.org/0.20/modules/generated/sklearn.ensemble.GradientBoostingClassifier.html # new: https://scikit-learn.org/0.22/modules/generated/sklearn.ensemble.GradientBoostingClassifier.html from lale.schemas import AnyOf, Bool, Enum, Float GradientBoostingClassifier = GradientBoostingClassifier.customize_schema( presort=AnyOf( types=[Bool(), Enum(["deprecated", "auto"])], desc="This parameter is deprecated and will be removed in v0.24.", default="deprecated", ), ccp_alpha=Float( desc="Complexity parameter used for Minimal Cost-Complexity Pruning. The subtree with the largest cost complexity that is smaller than ccp_alpha will be chosen. By default, no pruning is performed.", default=0.0, forOptimizer=False, min=0.0, maxForOptimizer=0.1, ), ) if sklearn.__version__ >= "0.24": # old: https://scikit-learn.org/0.22/modules/generated/sklearn.ensemble.GradientBoostingClassifier.html # new: https://scikit-learn.org/0.24/modules/generated/sklearn.ensemble.GradientBoostingClassifier.html from lale.schemas import JSON GradientBoostingClassifier = GradientBoostingClassifier.customize_schema( presort=None, criterion=JSON( { "description": "Function to measure the quality of a split.", "anyOf": [ {"enum": ["mse", "friedman_mse"]}, { "description": "Deprecated since version 0.24.", "enum": ["mae"], "forOptimizer": False, }, ], "default": "friedman_mse", } ), ) lale.docstrings.set_docstrings( GradientBoostingClassifierImpl, GradientBoostingClassifier._schemas )
# Copyright 2019 IBM 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 sklearn import sklearn.ensemble import lale.docstrings import lale.operators class GradientBoostingClassifierImpl: def __init__(self, **hyperparams): self._hyperparams = hyperparams self._wrapped_model = sklearn.ensemble.GradientBoostingClassifier( **self._hyperparams ) def fit(self, X, y, **fit_params): self._wrapped_model.fit(X, y, **fit_params) return self def predict(self, X): return self._wrapped_model.predict(X) def predict_proba(self, X): return self._wrapped_model.predict_proba(X) def decision_function(self, X): return self._wrapped_model.decision_function(X) _hyperparams_schema = { "description": "Gradient Boosting for classification.", "allOf": [ { "type": "object", "required": ["init", "presort"], "relevantToOptimizer": [ "loss", "n_estimators", "min_samples_split", "min_samples_leaf", "max_depth", "max_features", "presort", ], "additionalProperties": False, "properties": { "loss": { "enum": ["deviance", "exponential"], "default": "deviance", "description": "loss function to be optimized. 'deviance' refers to", }, "learning_rate": { "type": "number", "minimumForOptimizer": 0.01, "maximumForOptimizer": 1.0, "distribution": "loguniform", "default": 0.1, "description": "learning rate shrinks the contribution of each tree by `learning_rate`.", }, "n_estimators": { "type": "integer", "minimumForOptimizer": 10, "maximumForOptimizer": 100, "distribution": "uniform", "default": 100, "description": "The number of boosting stages to perform. Gradient boosting", }, "subsample": { "type": "number", "minimumForOptimizer": 0.01, "maximumForOptimizer": 1.0, "distribution": "uniform", "default": 1.0, "description": "The fraction of samples to be used for fitting the individual base", }, "criterion": { "enum": ["friedman_mse", "mse", "mae"], "default": "friedman_mse", "description": "The function to measure the quality of a split. Supported criteria", }, "min_samples_split": { "anyOf": [ { "type": "integer", "minimumForOptimizer": 2, "maximumForOptimizer": 20, "distribution": "uniform", }, { "type": "number", "minimumForOptimizer": 0.01, "maximumForOptimizer": 0.5, "default": 0.05, }, ], "default": 2, "description": "The minimum number of samples required to split an internal node:", }, "min_samples_leaf": { "anyOf": [ { "type": "integer", "minimumForOptimizer": 1, "maximumForOptimizer": 20, "distribution": "uniform", }, { "type": "number", "minimumForOptimizer": 0.01, "maximumForOptimizer": 0.5, "default": 0.05, }, ], "default": 1, "description": "The minimum number of samples required to be at a leaf node.", }, "min_weight_fraction_leaf": { "type": "number", "default": 0.0, "description": "The minimum weighted fraction of the sum total of weights (of all", }, "max_depth": { "type": "integer", "minimumForOptimizer": 3, "maximumForOptimizer": 5, "default": 3, "description": "maximum depth of the individual regression estimators. The maximum", }, "min_impurity_decrease": { "type": "number", "default": 0.0, "description": "A node will be split if this split induces a decrease of the impurity", }, "min_impurity_split": { "anyOf": [{"type": "number"}, {"enum": [None]}], "default": None, "description": "Threshold for early stopping in tree growth. A node will split", }, "init": { "anyOf": [{"type": "object"}, {"enum": ["zero", None]}], "default": None, "description": "An estimator object that is used to compute the initial", }, "random_state": { "anyOf": [ {"type": "integer"}, {"laleType": "numpy.random.RandomState"}, {"enum": [None]}, ], "default": None, "description": "If int, random_state is the seed used by the random number generator;", }, "max_features": { "anyOf": [ {"type": "integer", "minimum": 1, "forOptimizer": False}, { "type": "number", "minimum": 0.0, "exclusiveMinimum": True, "maximum": 1.0, "exclusiveMaximum": True, "minimumForOptimizer": 0.01, "default": 0.5, "distribution": "uniform", }, {"enum": ["auto", "sqrt", "log2", None]}, ], "default": None, "description": "The number of features to consider when looking for the best split.", }, "verbose": { "type": "integer", "default": 0, "description": "Enable verbose output. If 1 then it prints progress and performance", }, "max_leaf_nodes": { "anyOf": [{"type": "integer"}, {"enum": [None]}], "default": None, "description": "Grow trees with ``max_leaf_nodes`` in best-first fashion.", }, "warm_start": { "type": "boolean", "default": False, "description": "When set to ``True``, reuse the solution of the previous call to fit", }, "presort": { "anyOf": [{"type": "boolean"}, {"enum": ["auto"]}], "default": "auto", "description": "Whether to presort the data to speed up the finding of best splits in", }, "validation_fraction": { "type": "number", "default": 0.1, "description": "The proportion of training data to set aside as validation set for", }, "n_iter_no_change": { "anyOf": [ { "type": "integer", "minimumForOptimizer": 5, "maximumForOptimizer": 10, }, {"enum": [None]}, ], "default": None, "description": "``n_iter_no_change`` is used to decide if early stopping will be used", }, "tol": { "type": "number", "minimumForOptimizer": 1e-08, "maximumForOptimizer": 0.01, "distribution": "loguniform", "default": 0.0001, "description": "Tolerance for the early stopping. When the loss is not improving", }, }, } ], } _input_fit_schema = { "description": "Fit the gradient boosting model.", "type": "object", "required": ["X", "y"], "properties": { "X": { "type": "array", "items": {"type": "array", "items": {"type": "number"},}, "description": "The input samples. Internally, it will be converted to", }, "y": { "anyOf": [ {"type": "array", "items": {"type": "number"}}, {"type": "array", "items": {"type": "string"}}, {"type": "array", "items": {"type": "boolean"}}, ], "description": "Target values (strings or integers in classification, real numbers", }, "sample_weight": { "anyOf": [ {"type": "array", "items": {"type": "number"},}, {"enum": [None]}, ], "default": None, "description": "Sample weights. If None, then samples are equally weighted. Splits", }, "monitor": { "anyOf": [{"laleType": "callable"}, {"enum": [None]}], "default": None, "description": "The monitor is called after each iteration with the current the current iteration, a reference to the estimator and the local variables of _fit_stages as keyword arguments callable(i, self, locals()).", }, }, } _input_predict_schema = { "description": "Predict class for X.", "type": "object", "properties": { "X": { "type": "array", "items": {"type": "array", "items": {"type": "number"},}, "description": "The input samples. Internally, it will be converted to", }, }, } _output_predict_schema = { "description": "The predicted values.", "anyOf": [ {"type": "array", "items": {"type": "number"}}, {"type": "array", "items": {"type": "string"}}, {"type": "array", "items": {"type": "boolean"}}, ], } _input_predict_proba_schema = { "description": "Predict class probabilities for X.", "type": "object", "properties": { "X": { "type": "array", "items": {"type": "array", "items": {"type": "number"},}, "description": "The input samples. Internally, it will be converted to", }, }, } _output_predict_proba_schema = { "description": "The class probabilities of the input samples. The order of the", "type": "array", "items": {"type": "array", "items": {"type": "number"},}, } _input_decision_function_schema = { "type": "object", "required": ["X"], "additionalProperties": False, "properties": { "X": { "description": "Features; the outer array is over samples.", "type": "array", "items": {"type": "array", "items": {"type": "number"}}, } }, } _output_decision_function_schema = { "description": "Confidence scores for samples for each class in the model.", "anyOf": [ { "description": "In the multi-way case, score per (sample, class) combination.", "type": "array", "items": {"type": "array", "items": {"type": "number"}}, }, { "description": "In the binary case, score for `self._classes[1]`.", "type": "array", "items": {"type": "number"}, }, ], } _combined_schemas = { "$schema": "http://json-schema.org/draft-04/schema#", "description": """`Gradient boosting classifier`_ random forest from scikit-learn. .. _`Gradient boosting classifier`: https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingClassifier.html """, "documentation_url": "https://lale.readthedocs.io/en/latest/modules/lale.lib.sklearn.gradient_boosting_classifier.html", "import_from": "sklearn.ensemble", "type": "object", "tags": {"pre": [], "op": ["estimator", "classifier"], "post": []}, "properties": { "hyperparams": _hyperparams_schema, "input_fit": _input_fit_schema, "input_predict": _input_predict_schema, "output_predict": _output_predict_schema, "input_predict_proba": _input_predict_proba_schema, "output_predict_proba": _output_predict_proba_schema, "input_decision_function": _input_decision_function_schema, "output_decision_function": _output_decision_function_schema, }, } GradientBoostingClassifier: lale.operators.PlannedIndividualOp GradientBoostingClassifier = lale.operators.make_operator( GradientBoostingClassifierImpl, _combined_schemas ) if sklearn.__version__ >= "0.22": # old: https://scikit-learn.org/0.20/modules/generated/sklearn.ensemble.GradientBoostingClassifier.html # new: https://scikit-learn.org/0.22/modules/generated/sklearn.ensemble.GradientBoostingClassifier.html from lale.schemas import AnyOf, Bool, Enum, Float GradientBoostingClassifier = GradientBoostingClassifier.customize_schema( presort=AnyOf( types=[Bool(), Enum(["deprecated", "auto"])], desc="This parameter is deprecated and will be removed in v0.24.", default="deprecated", ), ccp_alpha=Float( desc="Complexity parameter used for Minimal Cost-Complexity Pruning. The subtree with the largest cost complexity that is smaller than ccp_alpha will be chosen. By default, no pruning is performed.", default=0.0, forOptimizer=False, min=0.0, maxForOptimizer=0.1, ), ) if sklearn.__version__ >= "0.24": # old: https://scikit-learn.org/0.22/modules/generated/sklearn.ensemble.GradientBoostingClassifier.html # new: https://scikit-learn.org/0.24/modules/generated/sklearn.ensemble.GradientBoostingClassifier.html from lale.schemas import JSON GradientBoostingClassifier = GradientBoostingClassifier.customize_schema( presort=None, criterion=JSON( { "description": "Function to measure the quality of a split.", "anyOf": [ {"enum": ["mse", "friedman_mse"]}, { "description": "Deprecated since version 0.24.", "enum": ["mae"], "forOptimizer": False, }, ], "default": "friedman_mse", } ), ) lale.docstrings.set_docstrings( GradientBoostingClassifierImpl, GradientBoostingClassifier._schemas )
import pandas as pd import numpy as np import json from tqdm import tqdm from scipy.stats import poisson from scipy.optimize import minimize from utils import odds, clean_sheet, score_mtx, get_next_gw, time_decay from ranked_probability_score import ranked_probability_score, match_outcome import warnings # Dangerous but avoids warnings when computing the log of the rho_correction warnings.filterwarnings("ignore") class Dixon_Coles: """ Model scored goals at home and away as Poisson Random variables """ def __init__(self, games, parameters=None, decay=True): """ Args: games (pd.DataFrame): Finished games to used for training. parameters (array): Initial parameters to use decay (boolean): Apply time decay """ self.games = games.loc[:, [ "score1", "score2", "team1", "team2", "date"]] self.games = self.games.dropna() self.games["date"] = pd.to_datetime(self.games["date"]) self.games["days_since"] = ( self.games["date"].max() - self.games["date"]).dt.days self.games["weight"] = ( time_decay(0.001, self.games["days_since"]) if decay else 1) self.decay = decay self.games["score1"] = self.games["score1"].astype(int) self.games["score2"] = self.games["score2"].astype(int) self.teams = np.sort(np.unique(self.games["team1"])) self.league_size = len(self.teams) if parameters is None: self.parameters = np.concatenate(( np.random.uniform(0, 1, (self.league_size)), # Attack ratings np.random.uniform(0, 1, (self.league_size)), # Defense ratings [-0.1], # Rho [0.1], # Home advantage [0.1], # Intercept )) else: self.parameters = parameters def _rho_correction(self, x, y, lambda_x, mu_y, rho): """ Adjust the probabilities for low scores Args: x (pd.Series): Goals scored by the home team y (pd.Series): Goals scored by the away team lambda_x (pd.Series): Predicted goals scored by the home team mu_y (pd.Series): Predicted goals scored by the away team rho (pd.Series): Strength of the correction for low scores """ return np.select( [ (x == 0) & (y == 0), (x == 0) & (y == 1), (x == 1) & (y == 0), (x == 1) & (y == 1), ], [ 1 - (lambda_x * mu_y * rho), 1 + (lambda_x * rho), 1 + (mu_y * rho), 1 - rho, ], default=1, ) def neg_log_likelihood(self, parameters, games): """ Perform sample prediction and compare with outcome Args: parameters (pd.DataFrame): Current estimate of the parameters games (pd.DataFrame): Fixtures Returns: (float): Negative log likelihood """ parameter_df = ( pd.DataFrame() .assign(attack=parameters[:self.league_size]) .assign(defence=parameters[self.league_size: self.league_size * 2]) .assign(team=self.teams) ) fixtures_df = ( pd.merge( games, parameter_df, left_on='team1', right_on='team') .rename(columns={"attack": "attack1", "defence": "defence1"}) .merge(parameter_df, left_on='team2', right_on='team') .rename(columns={"attack": "attack2", "defence": "defence2"}) .drop("team_y", axis=1) .drop("team_x", axis=1) .assign(intercept=self.parameters[-1]) .assign(home_adv=self.parameters[-2]) .assign(rho=self.parameters[-3]) ) score1_inferred = ( np.exp( fixtures_df["home_adv"] + fixtures_df["intercept"] + fixtures_df["attack1"] - fixtures_df["defence2"]) ) score2_inferred = ( np.exp( fixtures_df["intercept"] + fixtures_df["attack2"] - fixtures_df["defence1"]) ) score1_loglikelihood = poisson.logpmf( fixtures_df["score1"], score1_inferred) score2_loglikelihood = poisson.logpmf( fixtures_df["score2"], score2_inferred) return -( ( score1_loglikelihood + score2_loglikelihood + np.log(self._rho_correction( fixtures_df["score1"], fixtures_df["score2"], score1_inferred, score2_inferred, parameters[-3])) ) * fixtures_df['weight'] ).sum() def maximum_likelihood_estimation(self): """ Maximum likelihood estimation of the model parameters for team strengths and the home field advantage. """ # Set strength ratings to have unique set of values for reproducibility constraints = [{ "type": "eq", "fun": lambda x: sum(x[: self.league_size]) - self.league_size }] # Set the maximum and minimum values the parameters can take bounds = [(0, 3)] * self.league_size * 2 bounds += [(-.2, .2)] bounds += [(0, 1)] * 2 self.solution = minimize( self.neg_log_likelihood, self.parameters, args=self.games, constraints=constraints, bounds=bounds, options={'disp': False, 'maxiter': 100}) self.parameters = self.solution["x"] def predict(self, games): """ Predict score for several fixtures Args: games (pd.DataFrame): Fixtures Returns: pd.DataFrame: Fixtures with appended odds """ parameter_df = ( pd.DataFrame() .assign(attack=self.parameters[:self.league_size]) .assign(defence=self.parameters[ self.league_size: self.league_size * 2]) .assign(team=self.teams) ) fixtures_df = ( pd.merge(games, parameter_df, left_on='team1', right_on='team') .rename(columns={"attack": "attack1", "defence": "defence1"}) .merge(parameter_df, left_on='team2', right_on='team') .rename(columns={"attack": "attack2", "defence": "defence2"}) .drop("team_y", axis=1) .drop("team_x", axis=1) .assign(intercept=self.parameters[-1]) .assign(home_adv=self.parameters[-2]) .assign(rho=self.parameters[-3]) ) fixtures_df["score1_infered"] = ( np.exp( fixtures_df["home_adv"] + fixtures_df["intercept"] + fixtures_df["attack1"] - fixtures_df["defence2"])) fixtures_df["score2_infered"] = ( np.exp( fixtures_df["intercept"] + fixtures_df["attack2"] - fixtures_df["defence1"])) def synthesize_odds(row): """ Lambda function that parses row by row to compute score matrix Args: row (array): Fixture Returns: (tuple): Home and Away win and clean sheets odds """ m = score_mtx(row["score1_infered"], row["score2_infered"]) # Apply Dixon and Coles adjustment m[0, 0] *= ( 1 - row["score1_infered"] * row["score2_infered"] * row["rho"]) m[0, 1] *= 1 + row["score1_infered"] * row["rho"] m[1, 0] *= 1 + row["score2_infered"] * row["rho"] m[1, 1] *= 1 - row["rho"] home_win_p, draw_p, away_win_p = odds(m) home_cs_p, away_cs_p = clean_sheet(m) return home_win_p, draw_p, away_win_p, home_cs_p, away_cs_p ( fixtures_df["home_win_p"], fixtures_df["draw_p"], fixtures_df["away_win_p"], fixtures_df["home_cs_p"], fixtures_df["away_cs_p"] ) = zip(*fixtures_df.apply( lambda row: synthesize_odds(row), axis=1)) return fixtures_df def evaluate(self, games): """ Evaluate the model's prediction accuracy Args: games (pd.DataFrame): Fixtured to evaluate on Returns: pd.DataFrame: df with appended metrics """ fixtures_df = self.predict(games) fixtures_df["winner"] = match_outcome(fixtures_df) fixtures_df["rps"] = fixtures_df.apply( lambda row: ranked_probability_score( [row["home_win_p"], row["draw_p"], row["away_win_p"]], row["winner"]), axis=1) return fixtures_df def backtest( self, train_games, test_season, path='', cold_start=False, save=True): """ Test the model's accuracy on past/finished games by iteratively training and testing on parts of the data. Args: train_games (pd.DataFrame): All the training samples test_season (int): Season to use a test set path (string): Path extension to adjust to ipynb use cold_start (boolean): Resume training with random parameters save (boolean): Save predictions to disk Returns: (float): Evaluation metric """ # Get training data self.train_games = train_games # Initialize model self.__init__( self.train_games[self.train_games['season'] != test_season], decay=self.decay) # Initial train self.maximum_likelihood_estimation() # Get test data # Separate testing based on per GW intervals fixtures = ( pd.read_csv( f"{path}data/fpl_official/vaastav/data/2021-22/fixtures.csv") .loc[:, ['event', 'kickoff_time']]) fixtures["kickoff_time"] = ( pd.to_datetime(fixtures["kickoff_time"]).dt.date) # Get only EPL games from the test season self.test_games = ( self.train_games .loc[self.train_games['league_id'] == 2411] .loc[self.train_games['season'] == test_season] .dropna() ) self.test_games["kickoff_time"] = ( pd.to_datetime(self.test_games["date"]).dt.date) # Merge on date self.test_games = pd.merge( self.test_games, fixtures, left_on='kickoff_time', right_on='kickoff_time') # Add the home team and away team index for running inference idx = ( pd.DataFrame() .assign(team=self.teams) .assign(team_index=np.arange(self.league_size))) self.test_games = ( pd.merge(self.test_games, idx, left_on="team1", right_on="team") .rename(columns={"team_index": "hg"}) .drop(["team"], axis=1) .drop_duplicates() .merge(idx, left_on="team2", right_on="team") .rename(columns={"team_index": "ag"}) .drop(["team"], axis=1) .sort_values("date") ) predictions = pd.DataFrame() for gw in tqdm(range(1, 39)): # For each GW of the season if gw in self.test_games['event'].values: # Handle case when the season is not finished # Run inference on the specific GW and save data. predictions = pd.concat([ predictions, self.evaluate( self.test_games[self.test_games['event'] == gw]) ]) if cold_start: previous_parameters = None else: previous_parameters = self.parameters # Retrain model with the new GW added to the train set. self.__init__( pd.concat([ self.train_games[ self.train_games['season'] != test_season], self.test_games[self.test_games['event'] <= gw] ]) .drop(columns=['ag', 'hg']), parameters=previous_parameters, decay=self.decay) self.maximum_likelihood_estimation() if save: ( predictions .loc[:, [ 'date', 'team1', 'team2', 'event', 'hg', 'ag', 'attack1', 'defence1', 'attack2', 'defence2', 'home_adv', 'intercept', 'rho', 'score1_infered', 'score2_infered', 'home_win_p', 'draw_p', 'away_win_p', 'home_cs_p', 'away_cs_p']] .to_csv( f"{path}data/predictions/fixtures/dixon_coles" + f"{self.weight if self.decay else "_no_decay"}.csv", index=False) ) return predictions if __name__ == "__main__": with open('info.json') as f: season = json.load(f)['season'] next_gw = get_next_gw() df = pd.read_csv("data/fivethirtyeight/spi_matches.csv") df = ( df .loc[(df['league_id'] == 2411) | (df['league_id'] == 2412)] ) # Get GW dates fixtures = ( pd.read_csv("data/fpl_official/vaastav/data/2021-22/fixtures.csv") .loc[:, ['event', 'kickoff_time']]) fixtures["kickoff_time"] = pd.to_datetime(fixtures["kickoff_time"]).dt.date # Get only EPL games from the current season season_games = ( df .loc[df['league_id'] == 2411] .loc[df['season'] == season] ) season_games["kickoff_time"] = pd.to_datetime(season_games["date"]).dt.date # Merge on date season_games = ( pd.merge( season_games, fixtures, left_on='kickoff_time', right_on='kickoff_time') .drop_duplicates() ) # Train model on all games up to the previous GW model = Dixon_Coles( pd.concat([ df.loc[df['season'] != season], season_games[season_games['event'] < next_gw] ])) model.maximum_likelihood_estimation() # Add the home team and away team index for running inference idx = ( pd.DataFrame() .assign(team=model.teams) .assign(team_index=np.arange(model.league_size))) season_games = ( pd.merge(season_games, idx, left_on="team1", right_on="team") .rename(columns={"team_index": "hg"}) .drop(["team"], axis=1) .drop_duplicates() .merge(idx, left_on="team2", right_on="team") .rename(columns={"team_index": "ag"}) .drop(["team"], axis=1) .sort_values("date") ) predictions = model.evaluate( season_games[season_games['event'] == next_gw]) print(predictions.rps.mean())
import pandas as pd import numpy as np import json from tqdm import tqdm from scipy.stats import poisson from scipy.optimize import minimize from utils import odds, clean_sheet, score_mtx, get_next_gw, time_decay from ranked_probability_score import ranked_probability_score, match_outcome import warnings # Dangerous but avoids warnings when computing the log of the rho_correction warnings.filterwarnings("ignore") class Dixon_Coles: """ Model scored goals at home and away as Poisson Random variables """ def __init__(self, games, parameters=None, decay=True): """ Args: games (pd.DataFrame): Finished games to used for training. parameters (array): Initial parameters to use decay (boolean): Apply time decay """ self.games = games.loc[:, [ "score1", "score2", "team1", "team2", "date"]] self.games = self.games.dropna() self.games["date"] = pd.to_datetime(self.games["date"]) self.games["days_since"] = ( self.games["date"].max() - self.games["date"]).dt.days self.games["weight"] = ( time_decay(0.001, self.games["days_since"]) if decay else 1) self.decay = decay self.games["score1"] = self.games["score1"].astype(int) self.games["score2"] = self.games["score2"].astype(int) self.teams = np.sort(np.unique(self.games["team1"])) self.league_size = len(self.teams) if parameters is None: self.parameters = np.concatenate(( np.random.uniform(0, 1, (self.league_size)), # Attack ratings np.random.uniform(0, 1, (self.league_size)), # Defense ratings [-0.1], # Rho [0.1], # Home advantage [0.1], # Intercept )) else: self.parameters = parameters def _rho_correction(self, x, y, lambda_x, mu_y, rho): """ Adjust the probabilities for low scores Args: x (pd.Series): Goals scored by the home team y (pd.Series): Goals scored by the away team lambda_x (pd.Series): Predicted goals scored by the home team mu_y (pd.Series): Predicted goals scored by the away team rho (pd.Series): Strength of the correction for low scores """ return np.select( [ (x == 0) & (y == 0), (x == 0) & (y == 1), (x == 1) & (y == 0), (x == 1) & (y == 1), ], [ 1 - (lambda_x * mu_y * rho), 1 + (lambda_x * rho), 1 + (mu_y * rho), 1 - rho, ], default=1, ) def neg_log_likelihood(self, parameters, games): """ Perform sample prediction and compare with outcome Args: parameters (pd.DataFrame): Current estimate of the parameters games (pd.DataFrame): Fixtures Returns: (float): Negative log likelihood """ parameter_df = ( pd.DataFrame() .assign(attack=parameters[:self.league_size]) .assign(defence=parameters[self.league_size: self.league_size * 2]) .assign(team=self.teams) ) fixtures_df = ( pd.merge( games, parameter_df, left_on='team1', right_on='team') .rename(columns={"attack": "attack1", "defence": "defence1"}) .merge(parameter_df, left_on='team2', right_on='team') .rename(columns={"attack": "attack2", "defence": "defence2"}) .drop("team_y", axis=1) .drop("team_x", axis=1) .assign(intercept=self.parameters[-1]) .assign(home_adv=self.parameters[-2]) .assign(rho=self.parameters[-3]) ) score1_inferred = ( np.exp( fixtures_df["home_adv"] + fixtures_df["intercept"] + fixtures_df["attack1"] - fixtures_df["defence2"]) ) score2_inferred = ( np.exp( fixtures_df["intercept"] + fixtures_df["attack2"] - fixtures_df["defence1"]) ) score1_loglikelihood = poisson.logpmf( fixtures_df["score1"], score1_inferred) score2_loglikelihood = poisson.logpmf( fixtures_df["score2"], score2_inferred) return -( ( score1_loglikelihood + score2_loglikelihood + np.log(self._rho_correction( fixtures_df["score1"], fixtures_df["score2"], score1_inferred, score2_inferred, parameters[-3])) ) * fixtures_df['weight'] ).sum() def maximum_likelihood_estimation(self): """ Maximum likelihood estimation of the model parameters for team strengths and the home field advantage. """ # Set strength ratings to have unique set of values for reproducibility constraints = [{ "type": "eq", "fun": lambda x: sum(x[: self.league_size]) - self.league_size }] # Set the maximum and minimum values the parameters can take bounds = [(0, 3)] * self.league_size * 2 bounds += [(-.2, .2)] bounds += [(0, 1)] * 2 self.solution = minimize( self.neg_log_likelihood, self.parameters, args=self.games, constraints=constraints, bounds=bounds, options={'disp': False, 'maxiter': 100}) self.parameters = self.solution["x"] def predict(self, games): """ Predict score for several fixtures Args: games (pd.DataFrame): Fixtures Returns: pd.DataFrame: Fixtures with appended odds """ parameter_df = ( pd.DataFrame() .assign(attack=self.parameters[:self.league_size]) .assign(defence=self.parameters[ self.league_size: self.league_size * 2]) .assign(team=self.teams) ) fixtures_df = ( pd.merge(games, parameter_df, left_on='team1', right_on='team') .rename(columns={"attack": "attack1", "defence": "defence1"}) .merge(parameter_df, left_on='team2', right_on='team') .rename(columns={"attack": "attack2", "defence": "defence2"}) .drop("team_y", axis=1) .drop("team_x", axis=1) .assign(intercept=self.parameters[-1]) .assign(home_adv=self.parameters[-2]) .assign(rho=self.parameters[-3]) ) fixtures_df["score1_infered"] = ( np.exp( fixtures_df["home_adv"] + fixtures_df["intercept"] + fixtures_df["attack1"] - fixtures_df["defence2"])) fixtures_df["score2_infered"] = ( np.exp( fixtures_df["intercept"] + fixtures_df["attack2"] - fixtures_df["defence1"])) def synthesize_odds(row): """ Lambda function that parses row by row to compute score matrix Args: row (array): Fixture Returns: (tuple): Home and Away win and clean sheets odds """ m = score_mtx(row["score1_infered"], row["score2_infered"]) # Apply Dixon and Coles adjustment m[0, 0] *= ( 1 - row["score1_infered"] * row["score2_infered"] * row["rho"]) m[0, 1] *= 1 + row["score1_infered"] * row["rho"] m[1, 0] *= 1 + row["score2_infered"] * row["rho"] m[1, 1] *= 1 - row["rho"] home_win_p, draw_p, away_win_p = odds(m) home_cs_p, away_cs_p = clean_sheet(m) return home_win_p, draw_p, away_win_p, home_cs_p, away_cs_p ( fixtures_df["home_win_p"], fixtures_df["draw_p"], fixtures_df["away_win_p"], fixtures_df["home_cs_p"], fixtures_df["away_cs_p"] ) = zip(*fixtures_df.apply( lambda row: synthesize_odds(row), axis=1)) return fixtures_df def evaluate(self, games): """ Evaluate the model's prediction accuracy Args: games (pd.DataFrame): Fixtured to evaluate on Returns: pd.DataFrame: df with appended metrics """ fixtures_df = self.predict(games) fixtures_df["winner"] = match_outcome(fixtures_df) fixtures_df["rps"] = fixtures_df.apply( lambda row: ranked_probability_score( [row["home_win_p"], row["draw_p"], row["away_win_p"]], row["winner"]), axis=1) return fixtures_df def backtest( self, train_games, test_season, path='', cold_start=False, save=True): """ Test the model's accuracy on past/finished games by iteratively training and testing on parts of the data. Args: train_games (pd.DataFrame): All the training samples test_season (int): Season to use a test set path (string): Path extension to adjust to ipynb use cold_start (boolean): Resume training with random parameters save (boolean): Save predictions to disk Returns: (float): Evaluation metric """ # Get training data self.train_games = train_games # Initialize model self.__init__( self.train_games[self.train_games['season'] != test_season], decay=self.decay) # Initial train self.maximum_likelihood_estimation() # Get test data # Separate testing based on per GW intervals fixtures = ( pd.read_csv( f"{path}data/fpl_official/vaastav/data/2021-22/fixtures.csv") .loc[:, ['event', 'kickoff_time']]) fixtures["kickoff_time"] = ( pd.to_datetime(fixtures["kickoff_time"]).dt.date) # Get only EPL games from the test season self.test_games = ( self.train_games .loc[self.train_games['league_id'] == 2411] .loc[self.train_games['season'] == test_season] .dropna() ) self.test_games["kickoff_time"] = ( pd.to_datetime(self.test_games["date"]).dt.date) # Merge on date self.test_games = pd.merge( self.test_games, fixtures, left_on='kickoff_time', right_on='kickoff_time') # Add the home team and away team index for running inference idx = ( pd.DataFrame() .assign(team=self.teams) .assign(team_index=np.arange(self.league_size))) self.test_games = ( pd.merge(self.test_games, idx, left_on="team1", right_on="team") .rename(columns={"team_index": "hg"}) .drop(["team"], axis=1) .drop_duplicates() .merge(idx, left_on="team2", right_on="team") .rename(columns={"team_index": "ag"}) .drop(["team"], axis=1) .sort_values("date") ) predictions = pd.DataFrame() for gw in tqdm(range(1, 39)): # For each GW of the season if gw in self.test_games['event'].values: # Handle case when the season is not finished # Run inference on the specific GW and save data. predictions = pd.concat([ predictions, self.evaluate( self.test_games[self.test_games['event'] == gw]) ]) if cold_start: previous_parameters = None else: previous_parameters = self.parameters # Retrain model with the new GW added to the train set. self.__init__( pd.concat([ self.train_games[ self.train_games['season'] != test_season], self.test_games[self.test_games['event'] <= gw] ]) .drop(columns=['ag', 'hg']), parameters=previous_parameters, decay=self.decay) self.maximum_likelihood_estimation() if save: ( predictions .loc[:, [ 'date', 'team1', 'team2', 'event', 'hg', 'ag', 'attack1', 'defence1', 'attack2', 'defence2', 'home_adv', 'intercept', 'rho', 'score1_infered', 'score2_infered', 'home_win_p', 'draw_p', 'away_win_p', 'home_cs_p', 'away_cs_p']] .to_csv( f"{path}data/predictions/fixtures/dixon_coles" + f"{self.weight if self.decay else '_no_decay'}.csv", index=False) ) return predictions if __name__ == "__main__": with open('info.json') as f: season = json.load(f)['season'] next_gw = get_next_gw() df = pd.read_csv("data/fivethirtyeight/spi_matches.csv") df = ( df .loc[(df['league_id'] == 2411) | (df['league_id'] == 2412)] ) # Get GW dates fixtures = ( pd.read_csv("data/fpl_official/vaastav/data/2021-22/fixtures.csv") .loc[:, ['event', 'kickoff_time']]) fixtures["kickoff_time"] = pd.to_datetime(fixtures["kickoff_time"]).dt.date # Get only EPL games from the current season season_games = ( df .loc[df['league_id'] == 2411] .loc[df['season'] == season] ) season_games["kickoff_time"] = pd.to_datetime(season_games["date"]).dt.date # Merge on date season_games = ( pd.merge( season_games, fixtures, left_on='kickoff_time', right_on='kickoff_time') .drop_duplicates() ) # Train model on all games up to the previous GW model = Dixon_Coles( pd.concat([ df.loc[df['season'] != season], season_games[season_games['event'] < next_gw] ])) model.maximum_likelihood_estimation() # Add the home team and away team index for running inference idx = ( pd.DataFrame() .assign(team=model.teams) .assign(team_index=np.arange(model.league_size))) season_games = ( pd.merge(season_games, idx, left_on="team1", right_on="team") .rename(columns={"team_index": "hg"}) .drop(["team"], axis=1) .drop_duplicates() .merge(idx, left_on="team2", right_on="team") .rename(columns={"team_index": "ag"}) .drop(["team"], axis=1) .sort_values("date") ) predictions = model.evaluate( season_games[season_games['event'] == next_gw]) print(predictions.rps.mean())
#!/usr/bin/env python3 # ############################################################################# # Helper script to generate us-counties.csv file # * Download counties information from census.gov # * Download geo-location from datasciencetoolkit.org # Save result into the '../../common/us/counties.csv' file # # requirements: pandas, xlrd # ############################################################################# import codecs import csv import json import os import pandas import re import sys from urllib import request, parse as urlparse from pathlib import Path codecs.register_error('strict', codecs.ignore_errors) URL = 'https://www2.census.gov/programs-surveys/popest/geographies/2017/all-geocodes-v2017.xlsx' # URL = f'file://{(Path(__file__).parent / 'all-geocodes-v2017.xlsx').resolve()}' CORRECT_US_STATES_COUNTIES_COUNT = 3143 # value on end 2017 CORRECT_US_TERRITORIES_COUNTIES_COUNT = 78 # value on 2020 output_file = Path(__file__).parent / '..' / '..' / '..' / 'common' / 'us' / 'counties.csv' counties = [] # ----------------------------------------------------------------------------- # Show debug output only with the env.DEBUG = true debug = lambda msg: print(msg) if os.environ.get('DEBUG') == 'true' else lambda msg: None # ----------------------------------------------------------------------------- # Load all states {state_fips: (state_id, state_name)} states_file = Path(__file__).parent / '..' / '..' / '..' / 'common' / 'us' / 'states.csv' print(f'Read csv with states: {states_file}') states = dict([(r[1].rjust(2, '0'), (r[0], r[2])) for r in csv.reader(states_file.open('r'), delimiter=',', quotechar='"')]) # ----------------------------------------------------------------------------- # Load geo location for a county def get_geo_location(county_name, state_id): urlquery = urlparse.quote(f'address={county_name},{state_id},US') url = f'http://www.datasciencetoolkit.org/maps/api/geocode/json?{urlquery}' try: debug(f'Load geolocation from: {url}') response = codecs.decode(request.urlopen(url).read(), 'utf-8') debug(f'Parse data') data = json.loads(response) location = data['results'][0]['geometry']['location'] debug(f'Found location: {location}') return (location['lat'], location['lng']) except Exception as ex: print(f'Error get/parse data from {url}') print(ex) raise ex # ----------------------------------------------------------------------------- # Safety add county information to the main list def add_county_to_the_list(fips, state_id, name, latitude=None, longitude=None): for item in counties: if item[0] == fips: debug(f'{fips}, {state_id}, {name} - Skip. Already exists in the list.') return if latitude is None or longitude is None: (latitude, longitude) = get_geo_location(name, state_id) print(f'{fips}, {state_id}, {name}, {latitude}, {longitude}') counties.append([fips, state_id, name, latitude, longitude]) # ----------------------------------------------------------------------------- # Main method print(f'Load data from {URL}') data = pandas.read_excel(URL, sheet_name=0) print(f'Parsing data line by line') name_replace_patterns = [ re.compile(' city', re.IGNORECASE), re.compile(' town', re.IGNORECASE), re.compile(' county', re.IGNORECASE) ] for row in data.itertuples(): level = str(row._1) state_fips = str(row._2) county_fips = str(row._3) subdiv_fips = str(row._4) place_fips = str(row._5) city_fips = str(row._6) name = str(row._7) if not level.isdigit() or not state_fips.isdigit() or not county_fips.isdigit(): debug(f'Skip header: {row}') continue # Skip headers if county_fips == '000' or not (subdiv_fips == '00000' and place_fips == '00000' and city_fips == '00000'): debug(f'Skip non county: {row}') continue # skip states and country and non county fips = f'{state_fips}{county_fips}' country_id = 'US' state_id = states[state_fips][0] if fips in ['02093', '02261']: # Skip: Valdez–Cordova Census Area (Alaska) - on Jan 2019 debug(f'{fips}, {state_id}, {name} - Skip.') else: add_county_to_the_list(fips, state_id, name) # Correction on 2020 # Jan 2019 update for Valdez–Cordova Census Area (Alaska) add_county_to_the_list('02063', 'AK', 'Chugach Census Area', 61.130833, -146.348333) add_county_to_the_list('02066', 'AK', 'Copper River Census Area', 62.109722, -145.557222) # ----------------------------------------------------------------------------- # Write counties to the csv file found_total_counties = len(counties) with output_file.open('w') as file_writer: csv_writer = csv.writer(file_writer, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) csv_writer.writerow(['fips', 'state_id', 'name', 'latitude', 'longitude']) for county in sorted(counties, key=lambda x: x[0]): csv_writer.writerow(county) # ----------------------------------------------------------------------------- # Show validation result correct_counties_count = CORRECT_US_STATES_COUNTIES_COUNT + CORRECT_US_TERRITORIES_COUNTIES_COUNT if found_total_counties == correct_counties_count: print(f'[OK ] Found {found_total_counties} counties - correct') else: print(f'[ERR] Found {found_total_counties} counties - incorrect (should be {correct_counties_count} <- ' f'{CORRECT_US_STATES_COUNTIES_COUNT} + {CORRECT_US_TERRITORIES_COUNTIES_COUNT})') sys.exit(1)
#!/usr/bin/env python3 # ############################################################################# # Helper script to generate us-counties.csv file # * Download counties information from census.gov # * Download geo-location from datasciencetoolkit.org # Save result into the '../../common/us/counties.csv' file # # requirements: pandas, xlrd # ############################################################################# import codecs import csv import json import os import pandas import re import sys from urllib import request, parse as urlparse from pathlib import Path codecs.register_error('strict', codecs.ignore_errors) URL = 'https://www2.census.gov/programs-surveys/popest/geographies/2017/all-geocodes-v2017.xlsx' # URL = f'file://{(Path(__file__).parent / "all-geocodes-v2017.xlsx").resolve()}' CORRECT_US_STATES_COUNTIES_COUNT = 3143 # value on end 2017 CORRECT_US_TERRITORIES_COUNTIES_COUNT = 78 # value on 2020 output_file = Path(__file__).parent / '..' / '..' / '..' / 'common' / 'us' / 'counties.csv' counties = [] # ----------------------------------------------------------------------------- # Show debug output only with the env.DEBUG = true debug = lambda msg: print(msg) if os.environ.get('DEBUG') == 'true' else lambda msg: None # ----------------------------------------------------------------------------- # Load all states {state_fips: (state_id, state_name)} states_file = Path(__file__).parent / '..' / '..' / '..' / 'common' / 'us' / 'states.csv' print(f'Read csv with states: {states_file}') states = dict([(r[1].rjust(2, '0'), (r[0], r[2])) for r in csv.reader(states_file.open('r'), delimiter=',', quotechar='"')]) # ----------------------------------------------------------------------------- # Load geo location for a county def get_geo_location(county_name, state_id): urlquery = urlparse.quote(f'address={county_name},{state_id},US') url = f'http://www.datasciencetoolkit.org/maps/api/geocode/json?{urlquery}' try: debug(f'Load geolocation from: {url}') response = codecs.decode(request.urlopen(url).read(), 'utf-8') debug(f'Parse data') data = json.loads(response) location = data['results'][0]['geometry']['location'] debug(f'Found location: {location}') return (location['lat'], location['lng']) except Exception as ex: print(f'Error get/parse data from {url}') print(ex) raise ex # ----------------------------------------------------------------------------- # Safety add county information to the main list def add_county_to_the_list(fips, state_id, name, latitude=None, longitude=None): for item in counties: if item[0] == fips: debug(f'{fips}, {state_id}, {name} - Skip. Already exists in the list.') return if latitude is None or longitude is None: (latitude, longitude) = get_geo_location(name, state_id) print(f'{fips}, {state_id}, {name}, {latitude}, {longitude}') counties.append([fips, state_id, name, latitude, longitude]) # ----------------------------------------------------------------------------- # Main method print(f'Load data from {URL}') data = pandas.read_excel(URL, sheet_name=0) print(f'Parsing data line by line') name_replace_patterns = [ re.compile(' city', re.IGNORECASE), re.compile(' town', re.IGNORECASE), re.compile(' county', re.IGNORECASE) ] for row in data.itertuples(): level = str(row._1) state_fips = str(row._2) county_fips = str(row._3) subdiv_fips = str(row._4) place_fips = str(row._5) city_fips = str(row._6) name = str(row._7) if not level.isdigit() or not state_fips.isdigit() or not county_fips.isdigit(): debug(f'Skip header: {row}') continue # Skip headers if county_fips == '000' or not (subdiv_fips == '00000' and place_fips == '00000' and city_fips == '00000'): debug(f'Skip non county: {row}') continue # skip states and country and non county fips = f'{state_fips}{county_fips}' country_id = 'US' state_id = states[state_fips][0] if fips in ['02093', '02261']: # Skip: Valdez–Cordova Census Area (Alaska) - on Jan 2019 debug(f'{fips}, {state_id}, {name} - Skip.') else: add_county_to_the_list(fips, state_id, name) # Correction on 2020 # Jan 2019 update for Valdez–Cordova Census Area (Alaska) add_county_to_the_list('02063', 'AK', 'Chugach Census Area', 61.130833, -146.348333) add_county_to_the_list('02066', 'AK', 'Copper River Census Area', 62.109722, -145.557222) # ----------------------------------------------------------------------------- # Write counties to the csv file found_total_counties = len(counties) with output_file.open('w') as file_writer: csv_writer = csv.writer(file_writer, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) csv_writer.writerow(['fips', 'state_id', 'name', 'latitude', 'longitude']) for county in sorted(counties, key=lambda x: x[0]): csv_writer.writerow(county) # ----------------------------------------------------------------------------- # Show validation result correct_counties_count = CORRECT_US_STATES_COUNTIES_COUNT + CORRECT_US_TERRITORIES_COUNTIES_COUNT if found_total_counties == correct_counties_count: print(f'[OK ] Found {found_total_counties} counties - correct') else: print(f'[ERR] Found {found_total_counties} counties - incorrect (should be {correct_counties_count} <- ' f'{CORRECT_US_STATES_COUNTIES_COUNT} + {CORRECT_US_TERRITORIES_COUNTIES_COUNT})') sys.exit(1)
import os import subprocess import sys environments = [ {"NAME": "latest", "PYTHON_VERSION": "3.9"}, {"NAME": "python3.9-alpine3.13", "PYTHON_VERSION": "3.9"}, {"NAME": "python3.9-slim", "PYTHON_VERSION": "3.9"}, {"NAME": "python3.9", "PYTHON_VERSION": "3.9"}, {"NAME": "mambaforge", "PYTHON_VERSION": "Mambaforge 3.9"}, {"NAME": "miniforge3", "PYTHON_VERSION": "Miniforge3 3.9"}, ] start_with = os.environ.get("START_WITH") build_push = os.environ.get("BUILD_PUSH") def process_tag(*, env: dict): use_env = {**os.environ, **env} script = "scripts/test.sh" if build_push: script = "scripts/build-push.sh" return_code = subprocess.call(["bash", script], env=use_env) if return_code != 0: sys.exit(return_code) def print_version_envs(): env_lines = [] for env in environments: env_vars = [] for key, value in env.items(): env_vars.append(f"{key}='{value}'") env_lines.append(" ".join(env_vars)) for line in env_lines: print(line) def main(): start_at = 0 if start_with: start_at = [ i for i, env in enumerate((environments)) if env["NAME"] == start_with ][0] for i, env in enumerate(environments[start_at:]): print(f"Processing tag: {env["NAME"]}") process_tag(env=env) if __name__ == "__main__": if len(sys.argv) > 1: print_version_envs() else: main()
import os import subprocess import sys environments = [ {"NAME": "latest", "PYTHON_VERSION": "3.9"}, {"NAME": "python3.9-alpine3.13", "PYTHON_VERSION": "3.9"}, {"NAME": "python3.9-slim", "PYTHON_VERSION": "3.9"}, {"NAME": "python3.9", "PYTHON_VERSION": "3.9"}, {"NAME": "mambaforge", "PYTHON_VERSION": "Mambaforge 3.9"}, {"NAME": "miniforge3", "PYTHON_VERSION": "Miniforge3 3.9"}, ] start_with = os.environ.get("START_WITH") build_push = os.environ.get("BUILD_PUSH") def process_tag(*, env: dict): use_env = {**os.environ, **env} script = "scripts/test.sh" if build_push: script = "scripts/build-push.sh" return_code = subprocess.call(["bash", script], env=use_env) if return_code != 0: sys.exit(return_code) def print_version_envs(): env_lines = [] for env in environments: env_vars = [] for key, value in env.items(): env_vars.append(f"{key}='{value}'") env_lines.append(" ".join(env_vars)) for line in env_lines: print(line) def main(): start_at = 0 if start_with: start_at = [ i for i, env in enumerate((environments)) if env["NAME"] == start_with ][0] for i, env in enumerate(environments[start_at:]): print(f"Processing tag: {env['NAME']}") process_tag(env=env) if __name__ == "__main__": if len(sys.argv) > 1: print_version_envs() else: main()
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=invalid-name """Binary IO for circuit objects.""" import io import json import struct import uuid import warnings import numpy as np from qiskit import circuit as circuit_mod from qiskit import extensions from qiskit.circuit import library, controlflow from qiskit.circuit.classicalregister import ClassicalRegister, Clbit from qiskit.circuit.gate import Gate from qiskit.circuit.instruction import Instruction from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit.quantumregister import QuantumRegister, Qubit from qiskit.extensions import quantum_initializer from qiskit.quantum_info.operators import SparsePauliOp from qiskit.synthesis import evolution as evo_synth from .. import common, formats, exceptions from ..binary_io import value def _read_header_v2( # type: ignore[no-untyped-def] file_obj, version, vectors, metadata_deserializer=None ): data = formats.CIRCUIT_HEADER_V2._make( struct.unpack( formats.CIRCUIT_HEADER_V2_PACK, file_obj.read(formats.CIRCUIT_HEADER_V2_SIZE), ) ) name = file_obj.read(data.name_size).decode(common.ENCODE) global_phase = value.loads_value( data.global_phase_type, file_obj.read(data.global_phase_size), version=version, vectors=vectors, ) header = { "global_phase": global_phase, "num_qubits": data.num_qubits, "num_clbits": data.num_clbits, "num_registers": data.num_registers, "num_instructions": data.num_instructions, } metadata_raw = file_obj.read(data.metadata_size) metadata = json.loads(metadata_raw, cls=metadata_deserializer) return header, name, metadata def _read_header(file_obj, metadata_deserializer=None): # type: ignore[no-untyped-def] data = formats.CIRCUIT_HEADER._make( struct.unpack( formats.CIRCUIT_HEADER_PACK, file_obj.read(formats.CIRCUIT_HEADER_SIZE) ) ) name = file_obj.read(data.name_size).decode(common.ENCODE) header = { "global_phase": data.global_phase, "num_qubits": data.num_qubits, "num_clbits": data.num_clbits, "num_registers": data.num_registers, "num_instructions": data.num_instructions, } metadata_raw = file_obj.read(data.metadata_size) metadata = json.loads(metadata_raw, cls=metadata_deserializer) return header, name, metadata def _read_registers_v4(file_obj, num_registers): # type: ignore[no-untyped-def] registers = {"q": {}, "c": {}} for _reg in range(num_registers): data = formats.REGISTER_V4._make( struct.unpack( formats.REGISTER_V4_PACK, file_obj.read(formats.REGISTER_V4_SIZE), ) ) name = file_obj.read(data.name_size).decode("utf8") REGISTER_ARRAY_PACK = "!%sq" % data.size bit_indices_raw = file_obj.read(struct.calcsize(REGISTER_ARRAY_PACK)) bit_indices = list(struct.unpack(REGISTER_ARRAY_PACK, bit_indices_raw)) if data.type.decode("utf8") == "q": registers["q"][name] = (data.standalone, bit_indices, data.in_circuit) else: registers["c"][name] = (data.standalone, bit_indices, data.in_circuit) return registers def _read_registers(file_obj, num_registers): # type: ignore[no-untyped-def] registers = {"q": {}, "c": {}} for _reg in range(num_registers): data = formats.REGISTER._make( struct.unpack( formats.REGISTER_PACK, file_obj.read(formats.REGISTER_SIZE), ) ) name = file_obj.read(data.name_size).decode("utf8") REGISTER_ARRAY_PACK = "!%sI" % data.size bit_indices_raw = file_obj.read(struct.calcsize(REGISTER_ARRAY_PACK)) bit_indices = list(struct.unpack(REGISTER_ARRAY_PACK, bit_indices_raw)) if data.type.decode("utf8") == "q": registers["q"][name] = (data.standalone, bit_indices, True) else: registers["c"][name] = (data.standalone, bit_indices, True) return registers def _read_instruction_parameter(file_obj, version, vectors): # type: ignore[no-untyped-def] type_key, bin_data = common.read_instruction_param(file_obj) if type_key == common.ProgramTypeKey.CIRCUIT: param = common.data_from_binary(bin_data, read_circuit, version=version) elif type_key == common.ContainerTypeKey.RANGE: data = formats.RANGE._make(struct.unpack(formats.RANGE_PACK, bin_data)) param = range(data.start, data.stop, data.step) elif type_key == common.ContainerTypeKey.TUPLE: param = tuple( common.sequence_from_binary( bin_data, _read_instruction_parameter, version=version, vectors=vectors, ) ) elif type_key == common.ValueTypeKey.INTEGER: # TODO This uses little endian. Should be fixed in the next QPY version. param = struct.unpack("<q", bin_data)[0] elif type_key == common.ValueTypeKey.FLOAT: # TODO This uses little endian. Should be fixed in the next QPY version. param = struct.unpack("<d", bin_data)[0] else: param = value.loads_value(type_key, bin_data, version, vectors) return param def _read_instruction( # type: ignore[no-untyped-def] file_obj, circuit, registers, custom_instructions, version, vectors ): instruction = formats.CIRCUIT_INSTRUCTION._make( struct.unpack( formats.CIRCUIT_INSTRUCTION_PACK, file_obj.read(formats.CIRCUIT_INSTRUCTION_SIZE), ) ) gate_name = file_obj.read(instruction.name_size).decode(common.ENCODE) label = file_obj.read(instruction.label_size).decode(common.ENCODE) condition_register = file_obj.read(instruction.condition_register_size).decode( common.ENCODE ) qargs = [] cargs = [] params = [] condition_tuple = None if instruction.has_condition: # If an invalid register name is used assume it's a single bit # condition and treat the register name as a string of the clbit index if ClassicalRegister.name_format.match(condition_register) is None: # If invalid register prefixed with null character it's a clbit # index for single bit condition if condition_register[0] == "\x00": conditional_bit = int(condition_register[1:]) condition_tuple = ( circuit.clbits[conditional_bit], instruction.condition_value, ) else: raise ValueError( f"Invalid register name: {condition_register} for condition register of " f"instruction: {gate_name}" ) else: condition_tuple = ( registers["c"][condition_register], instruction.condition_value, ) qubit_indices = dict(enumerate(circuit.qubits)) clbit_indices = dict(enumerate(circuit.clbits)) # Load Arguments for _qarg in range(instruction.num_qargs): qarg = formats.CIRCUIT_INSTRUCTION_ARG._make( struct.unpack( formats.CIRCUIT_INSTRUCTION_ARG_PACK, file_obj.read(formats.CIRCUIT_INSTRUCTION_ARG_SIZE), ) ) if qarg.type.decode(common.ENCODE) == "c": raise TypeError("Invalid input carg prior to all qargs") qargs.append(qubit_indices[qarg.size]) for _carg in range(instruction.num_cargs): carg = formats.CIRCUIT_INSTRUCTION_ARG._make( struct.unpack( formats.CIRCUIT_INSTRUCTION_ARG_PACK, file_obj.read(formats.CIRCUIT_INSTRUCTION_ARG_SIZE), ) ) if carg.type.decode(common.ENCODE) == "q": raise TypeError("Invalid input qarg after all qargs") cargs.append(clbit_indices[carg.size]) # Load Parameters for _param in range(instruction.num_parameters): param = _read_instruction_parameter(file_obj, version, vectors) params.append(param) # Load Gate object if gate_name in ("Gate", "Instruction"): inst_obj = _parse_custom_instruction(custom_instructions, gate_name, params) inst_obj.condition = condition_tuple if instruction.label_size > 0: inst_obj.label = label circuit._append(inst_obj, qargs, cargs) return elif gate_name in custom_instructions: inst_obj = _parse_custom_instruction(custom_instructions, gate_name, params) inst_obj.condition = condition_tuple if instruction.label_size > 0: inst_obj.label = label circuit._append(inst_obj, qargs, cargs) return elif hasattr(library, gate_name): gate_class = getattr(library, gate_name) elif hasattr(circuit_mod, gate_name): gate_class = getattr(circuit_mod, gate_name) elif hasattr(extensions, gate_name): gate_class = getattr(extensions, gate_name) elif hasattr(quantum_initializer, gate_name): gate_class = getattr(quantum_initializer, gate_name) elif hasattr(controlflow, gate_name): gate_class = getattr(controlflow, gate_name) else: raise AttributeError("Invalid instruction type: %s" % gate_name) if gate_name in {"IfElseOp", "WhileLoopOp"}: gate = gate_class(condition_tuple, *params) else: if gate_name in {"Initialize", "UCRXGate", "UCRYGate", "UCRZGate"}: gate = gate_class(params) else: if gate_name == "Barrier": params = [len(qargs)] elif gate_name in {"BreakLoopOp", "ContinueLoopOp"}: params = [len(qargs), len(cargs)] gate = gate_class(*params) gate.condition = condition_tuple if instruction.label_size > 0: gate.label = label if not isinstance(gate, Instruction): circuit.append(gate, qargs, cargs) else: circuit._append(gate, qargs, cargs) def _parse_custom_instruction( # type: ignore[no-untyped-def] custom_instructions, gate_name, params ): type_str, num_qubits, num_clbits, definition = custom_instructions[gate_name] type_key = common.CircuitInstructionTypeKey(type_str) if type_key == common.CircuitInstructionTypeKey.INSTRUCTION: inst_obj = Instruction(gate_name, num_qubits, num_clbits, params) if definition is not None: inst_obj.definition = definition return inst_obj if type_key == common.CircuitInstructionTypeKey.GATE: inst_obj = Gate(gate_name, num_qubits, params) inst_obj.definition = definition return inst_obj if type_key == common.CircuitInstructionTypeKey.PAULI_EVOL_GATE: return definition raise ValueError("Invalid custom instruction type '%s'" % type_str) def _read_pauli_evolution_gate(file_obj, version, vectors): # type: ignore[no-untyped-def] pauli_evolution_def = formats.PAULI_EVOLUTION_DEF._make( struct.unpack( formats.PAULI_EVOLUTION_DEF_PACK, file_obj.read(formats.PAULI_EVOLUTION_DEF_SIZE), ) ) if pauli_evolution_def.operator_size != 1 and pauli_evolution_def.standalone_op: raise ValueError( "Can't have a standalone operator with {pauli_evolution_raw[0]} operators in the payload" ) operator_list = [] for _ in range(pauli_evolution_def.operator_size): op_elem = formats.SPARSE_PAULI_OP_LIST_ELEM._make( struct.unpack( formats.SPARSE_PAULI_OP_LIST_ELEM_PACK, file_obj.read(formats.SPARSE_PAULI_OP_LIST_ELEM_SIZE), ) ) op_raw_data = common.data_from_binary(file_obj.read(op_elem.size), np.load) operator_list.append(SparsePauliOp.from_list(op_raw_data)) if pauli_evolution_def.standalone_op: pauli_op = operator_list[0] else: pauli_op = operator_list time = value.loads_value( common.ValueTypeKey(pauli_evolution_def.time_type), file_obj.read(pauli_evolution_def.time_size), version=version, vectors=vectors, ) synth_data = json.loads(file_obj.read(pauli_evolution_def.synth_method_size)) synthesis = getattr(evo_synth, synth_data["class"])(**synth_data["settings"]) return_gate = library.PauliEvolutionGate(pauli_op, time=time, synthesis=synthesis) return return_gate def _read_custom_instructions(file_obj, version, vectors): # type: ignore[no-untyped-def] custom_instructions = {} custom_definition_header = formats.CUSTOM_CIRCUIT_DEF_HEADER._make( struct.unpack( formats.CUSTOM_CIRCUIT_DEF_HEADER_PACK, file_obj.read(formats.CUSTOM_CIRCUIT_DEF_HEADER_SIZE), ) ) if custom_definition_header.size > 0: for _ in range(custom_definition_header.size): data = formats.CUSTOM_CIRCUIT_INST_DEF._make( struct.unpack( formats.CUSTOM_CIRCUIT_INST_DEF_PACK, file_obj.read(formats.CUSTOM_CIRCUIT_INST_DEF_SIZE), ) ) name = file_obj.read(data.gate_name_size).decode(common.ENCODE) type_str = data.type definition_circuit = None if data.custom_definition: def_binary = file_obj.read(data.size) if version < 3 or not name.startswith(r"###PauliEvolutionGate_"): definition_circuit = common.data_from_binary( def_binary, read_circuit, version=version ) elif name.startswith(r"###PauliEvolutionGate_"): definition_circuit = common.data_from_binary( def_binary, _read_pauli_evolution_gate, version=version, vectors=vectors, ) custom_instructions[name] = ( type_str, data.num_qubits, data.num_clbits, definition_circuit, ) return custom_instructions def _write_instruction_parameter(file_obj, param): # type: ignore[no-untyped-def] if isinstance(param, QuantumCircuit): type_key = common.ProgramTypeKey.CIRCUIT data = common.data_to_binary(param, write_circuit) elif isinstance(param, range): type_key = common.ContainerTypeKey.RANGE data = struct.pack(formats.RANGE_PACK, param.start, param.stop, param.step) elif isinstance(param, tuple): type_key = common.ContainerTypeKey.TUPLE data = common.sequence_to_binary(param, _write_instruction_parameter) elif isinstance(param, int): # TODO This uses little endian. This should be fixed in next QPY version. type_key = common.ValueTypeKey.INTEGER data = struct.pack("<q", param) elif isinstance(param, float): # TODO This uses little endian. This should be fixed in next QPY version. type_key = common.ValueTypeKey.FLOAT data = struct.pack("<d", param) else: type_key, data = value.dumps_value(param) common.write_instruction_param(file_obj, type_key, data) # pylint: disable=too-many-boolean-expressions def _write_instruction( # type: ignore[no-untyped-def] file_obj, instruction_tuple, custom_instructions, index_map ): gate_class_name = instruction_tuple[0].__class__.__name__ if ( ( not hasattr(library, gate_class_name) and not hasattr(circuit_mod, gate_class_name) and not hasattr(extensions, gate_class_name) and not hasattr(quantum_initializer, gate_class_name) and not hasattr(controlflow, gate_class_name) ) or gate_class_name == "Gate" or gate_class_name == "Instruction" or isinstance(instruction_tuple[0], library.BlueprintCircuit) ): if instruction_tuple[0].name not in custom_instructions: custom_instructions[instruction_tuple[0].name] = instruction_tuple[0] gate_class_name = instruction_tuple[0].name elif isinstance(instruction_tuple[0], library.PauliEvolutionGate): gate_class_name = r"###PauliEvolutionGate_" + str(uuid.uuid4()) custom_instructions[gate_class_name] = instruction_tuple[0] has_condition = False condition_register = b"" condition_value = 0 if instruction_tuple[0].condition: has_condition = True if isinstance(instruction_tuple[0].condition[0], Clbit): bit_index = index_map["c"][instruction_tuple[0].condition[0]] condition_register = b"\x00" + str(bit_index).encode(common.ENCODE) condition_value = int(instruction_tuple[0].condition[1]) else: condition_register = ( instruction_tuple[0].condition[0].name.encode(common.ENCODE) ) condition_value = instruction_tuple[0].condition[1] gate_class_name = gate_class_name.encode(common.ENCODE) label = getattr(instruction_tuple[0], "label") if label: label_raw = label.encode(common.ENCODE) else: label_raw = b"" instruction_raw = struct.pack( formats.CIRCUIT_INSTRUCTION_PACK, len(gate_class_name), len(label_raw), len(instruction_tuple[0].params), instruction_tuple[0].num_qubits, instruction_tuple[0].num_clbits, has_condition, len(condition_register), condition_value, ) file_obj.write(instruction_raw) file_obj.write(gate_class_name) file_obj.write(label_raw) file_obj.write(condition_register) # Encode instruciton args for qbit in instruction_tuple[1]: instruction_arg_raw = struct.pack( formats.CIRCUIT_INSTRUCTION_ARG_PACK, b"q", index_map["q"][qbit] ) file_obj.write(instruction_arg_raw) for clbit in instruction_tuple[2]: instruction_arg_raw = struct.pack( formats.CIRCUIT_INSTRUCTION_ARG_PACK, b"c", index_map["c"][clbit] ) file_obj.write(instruction_arg_raw) # Encode instruction params for param in instruction_tuple[0].params: _write_instruction_parameter(file_obj, param) def _write_pauli_evolution_gate(file_obj, evolution_gate): # type: ignore[no-untyped-def] operator_list = evolution_gate.operator standalone = False if not isinstance(operator_list, list): operator_list = [operator_list] standalone = True num_operators = len(operator_list) def _write_elem(buffer, op): # type: ignore[no-untyped-def] elem_data = common.data_to_binary(op.to_list(array=True), np.save) elem_metadata = struct.pack( formats.SPARSE_PAULI_OP_LIST_ELEM_PACK, len(elem_data) ) buffer.write(elem_metadata) buffer.write(elem_data) pauli_data_buf = io.BytesIO() for operator in operator_list: data = common.data_to_binary(operator, _write_elem) pauli_data_buf.write(data) time_type, time_data = value.dumps_value(evolution_gate.time) time_size = len(time_data) synth_class = str(type(evolution_gate.synthesis).__name__) settings_dict = evolution_gate.synthesis.settings synth_data = json.dumps({"class": synth_class, "settings": settings_dict}).encode( common.ENCODE ) synth_size = len(synth_data) pauli_evolution_raw = struct.pack( formats.PAULI_EVOLUTION_DEF_PACK, num_operators, standalone, time_type, time_size, synth_size, ) file_obj.write(pauli_evolution_raw) file_obj.write(pauli_data_buf.getvalue()) pauli_data_buf.close() file_obj.write(time_data) file_obj.write(synth_data) def _write_custom_instruction(file_obj, name, instruction): # type: ignore[no-untyped-def] type_key = common.CircuitInstructionTypeKey.assign(instruction) has_definition = False size = 0 data = None num_qubits = instruction.num_qubits num_clbits = instruction.num_clbits if type_key == common.CircuitInstructionTypeKey.PAULI_EVOL_GATE: has_definition = True data = common.data_to_binary(instruction, _write_pauli_evolution_gate) size = len(data) elif instruction.definition is not None: has_definition = True data = common.data_to_binary(instruction.definition, write_circuit) size = len(data) name_raw = name.encode(common.ENCODE) custom_instruction_raw = struct.pack( formats.CUSTOM_CIRCUIT_INST_DEF_PACK, len(name_raw), type_key, num_qubits, num_clbits, has_definition, size, ) file_obj.write(custom_instruction_raw) file_obj.write(name_raw) if data: file_obj.write(data) def _write_registers(file_obj, in_circ_regs, full_bits): # type: ignore[no-untyped-def] bitmap = {bit: index for index, bit in enumerate(full_bits)} processed_indices = set() out_circ_regs = set() for bit in full_bits: if bit._register is not None and bit._register not in in_circ_regs: out_circ_regs.add(bit._register) for regs, is_in_circuit in [(in_circ_regs, True), (out_circ_regs, False)]: for reg in regs: standalone = all(bit._register is reg for bit in reg) reg_name = reg.name.encode(common.ENCODE) reg_type = reg.prefix.encode(common.ENCODE) file_obj.write( struct.pack( formats.REGISTER_V4_PACK, reg_type, standalone, reg.size, len(reg_name), is_in_circuit, ) ) file_obj.write(reg_name) REGISTER_ARRAY_PACK = "!%sq" % reg.size bit_indices = [] for bit in reg: bit_index = bitmap.get(bit, -1) if bit_index in processed_indices: bit_index = -1 if bit_index >= 0: processed_indices.add(bit_index) bit_indices.append(bit_index) file_obj.write(struct.pack(REGISTER_ARRAY_PACK, *bit_indices)) return len(in_circ_regs) + len(out_circ_regs) def write_circuit(file_obj, circuit, metadata_serializer=None): # type: ignore[no-untyped-def] """Write a single QuantumCircuit object in the file like object. Args: file_obj (FILE): The file like object to write the circuit data in. circuit (QuantumCircuit): The circuit data to write. metadata_serializer (JSONEncoder): An optional JSONEncoder class that will be passed the :attr:`.QuantumCircuit.metadata` dictionary for each circuit in ``circuits`` and will be used as the ``cls`` kwarg on the ``json.dump()`` call to JSON serialize that dictionary. """ metadata_raw = json.dumps( circuit.metadata, separators=(",", ":"), cls=metadata_serializer ).encode(common.ENCODE) metadata_size = len(metadata_raw) num_instructions = len(circuit) circuit_name = circuit.name.encode(common.ENCODE) global_phase_type, global_phase_data = value.dumps_value(circuit.global_phase) with io.BytesIO() as reg_buf: num_qregs = _write_registers(reg_buf, circuit.qregs, circuit.qubits) num_cregs = _write_registers(reg_buf, circuit.cregs, circuit.clbits) registers_raw = reg_buf.getvalue() num_registers = num_qregs + num_cregs # Write circuit header header_raw = formats.CIRCUIT_HEADER_V2( name_size=len(circuit_name), global_phase_type=global_phase_type, global_phase_size=len(global_phase_data), num_qubits=circuit.num_qubits, num_clbits=circuit.num_clbits, metadata_size=metadata_size, num_registers=num_registers, num_instructions=num_instructions, ) header = struct.pack(formats.CIRCUIT_HEADER_V2_PACK, *header_raw) file_obj.write(header) file_obj.write(circuit_name) file_obj.write(global_phase_data) file_obj.write(metadata_raw) # Write header payload file_obj.write(registers_raw) instruction_buffer = io.BytesIO() custom_instructions = {} index_map = {} index_map["q"] = {bit: index for index, bit in enumerate(circuit.qubits)} index_map["c"] = {bit: index for index, bit in enumerate(circuit.clbits)} for instruction in circuit.data: _write_instruction( instruction_buffer, instruction, custom_instructions, index_map ) file_obj.write( struct.pack(formats.CUSTOM_CIRCUIT_DEF_HEADER_PACK, len(custom_instructions)) ) for name, instruction in custom_instructions.items(): _write_custom_instruction(file_obj, name, instruction) instruction_buffer.seek(0) file_obj.write(instruction_buffer.read()) instruction_buffer.close() def read_circuit(file_obj, version, metadata_deserializer=None): # type: ignore[no-untyped-def] """Read a single QuantumCircuit object from the file like object. Args: file_obj (FILE): The file like object to read the circuit data from. version (int): QPY version. metadata_deserializer (JSONDecoder): An optional JSONDecoder class that will be used for the ``cls`` kwarg on the internal ``json.load`` call used to deserialize the JSON payload used for the :attr:`.QuantumCircuit.metadata` attribute for any circuits in the QPY file. If this is not specified the circuit metadata will be parsed as JSON with the stdlib ``json.load()`` function using the default ``JSONDecoder`` class. Returns: QuantumCircuit: The circuit object from the file. Raises: QpyError: Invalid register. """ vectors = {} if version < 2: header, name, metadata = _read_header( file_obj, metadata_deserializer=metadata_deserializer ) else: header, name, metadata = _read_header_v2( file_obj, version, vectors, metadata_deserializer=metadata_deserializer ) global_phase = header["global_phase"] num_qubits = header["num_qubits"] num_clbits = header["num_clbits"] num_registers = header["num_registers"] num_instructions = header["num_instructions"] out_registers = {"q": {}, "c": {}} if num_registers > 0: circ = QuantumCircuit(name=name, global_phase=global_phase, metadata=metadata) if version < 4: registers = _read_registers(file_obj, num_registers) else: registers = _read_registers_v4(file_obj, num_registers) for bit_type_label, bit_type, reg_type in [ ("q", Qubit, QuantumRegister), ("c", Clbit, ClassicalRegister), ]: register_bits = set() # Add quantum registers and bits for register_name in registers[bit_type_label]: standalone, indices, in_circuit = registers[bit_type_label][ register_name ] indices_defined = [x for x in indices if x >= 0] # If a register has no bits in the circuit skip it if not indices_defined: continue if standalone: start = min(indices_defined) count = start out_of_order = False for index in indices: if index < 0: out_of_order = True continue if not out_of_order and index != count: out_of_order = True count += 1 if index in register_bits: # If we have a bit in the position already it's been # added by an earlier register in the circuit # otherwise it's invalid qpy if not in_circuit: continue raise exceptions.QpyError("Duplicate register bits found") register_bits.add(index) num_reg_bits = len(indices) # Create a standlone register of the appropriate length (from # the number of indices in the qpy data) and add it to the circuit reg = reg_type(num_reg_bits, register_name) # If any bits from qreg are out of order in the circuit handle # is case if out_of_order or not in_circuit: for index, pos in sorted( enumerate(x for x in indices if x >= 0), key=lambda x: x[1] ): if bit_type_label == "q": bit_len = len(circ.qubits) else: bit_len = len(circ.clbits) if pos < bit_len: # If we have a bit in the position already it's been # added by an earlier register in the circuit # otherwise it's invalid qpy if not in_circuit: continue raise exceptions.QpyError( "Duplicate register bits found" ) # Fill any holes between the current register bit and the # next one if pos > bit_len: bits = [bit_type() for _ in range(pos - bit_len)] circ.add_bits(bits) circ.add_bits([reg[index]]) if in_circuit: circ.add_register(reg) else: if bit_type_label == "q": bit_len = len(circ.qubits) else: bit_len = len(circ.clbits) # If there is a hole between the start of the register and the # current bits and standalone bits to fill the gap. if start > len(circ.qubits): bits = [bit_type() for _ in range(start - bit_len)] circ.add_bits(bit_len) if in_circuit: circ.add_register(reg) out_registers[bit_type_label][register_name] = reg else: for index in indices: if bit_type_label == "q": bit_len = len(circ.qubits) else: bit_len = len(circ.clbits) # Add any missing bits bits = [bit_type() for _ in range(index + 1 - bit_len)] circ.add_bits(bits) if index in register_bits: raise exceptions.QpyError("Duplicate register bits found") register_bits.add(index) if bit_type_label == "q": bits = [circ.qubits[i] for i in indices] else: bits = [circ.clbits[i] for i in indices] reg = reg_type(name=register_name, bits=bits) if in_circuit: circ.add_register(reg) out_registers[bit_type_label][register_name] = reg # If we don't have sufficient bits in the circuit after adding # all the registers add more bits to fill the circuit if len(circ.qubits) < num_qubits: qubits = [Qubit() for _ in range(num_qubits - len(circ.qubits))] circ.add_bits(qubits) if len(circ.clbits) < num_clbits: clbits = [Clbit() for _ in range(num_qubits - len(circ.clbits))] circ.add_bits(clbits) else: circ = QuantumCircuit( num_qubits, num_clbits, name=name, global_phase=global_phase, metadata=metadata, ) custom_instructions = _read_custom_instructions(file_obj, version, vectors) for _instruction in range(num_instructions): _read_instruction( file_obj, circ, out_registers, custom_instructions, version, vectors ) for vec_name, (vector, initialized_params) in vectors.items(): if len(initialized_params) != len(vector): warnings.warn( f"The ParameterVector: '{vec_name}' is not fully identical to its " "pre-serialization state. Elements " f"{", ".join([str(x) for x in set(range(len(vector))) - initialized_params])} " "in the ParameterVector will be not equal to the pre-serialized ParameterVector " f"as they weren't used in the circuit: {circ.name}", UserWarning, ) return circ
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=invalid-name """Binary IO for circuit objects.""" import io import json import struct import uuid import warnings import numpy as np from qiskit import circuit as circuit_mod from qiskit import extensions from qiskit.circuit import library, controlflow from qiskit.circuit.classicalregister import ClassicalRegister, Clbit from qiskit.circuit.gate import Gate from qiskit.circuit.instruction import Instruction from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit.quantumregister import QuantumRegister, Qubit from qiskit.extensions import quantum_initializer from qiskit.quantum_info.operators import SparsePauliOp from qiskit.synthesis import evolution as evo_synth from .. import common, formats, exceptions from ..binary_io import value def _read_header_v2( # type: ignore[no-untyped-def] file_obj, version, vectors, metadata_deserializer=None ): data = formats.CIRCUIT_HEADER_V2._make( struct.unpack( formats.CIRCUIT_HEADER_V2_PACK, file_obj.read(formats.CIRCUIT_HEADER_V2_SIZE), ) ) name = file_obj.read(data.name_size).decode(common.ENCODE) global_phase = value.loads_value( data.global_phase_type, file_obj.read(data.global_phase_size), version=version, vectors=vectors, ) header = { "global_phase": global_phase, "num_qubits": data.num_qubits, "num_clbits": data.num_clbits, "num_registers": data.num_registers, "num_instructions": data.num_instructions, } metadata_raw = file_obj.read(data.metadata_size) metadata = json.loads(metadata_raw, cls=metadata_deserializer) return header, name, metadata def _read_header(file_obj, metadata_deserializer=None): # type: ignore[no-untyped-def] data = formats.CIRCUIT_HEADER._make( struct.unpack( formats.CIRCUIT_HEADER_PACK, file_obj.read(formats.CIRCUIT_HEADER_SIZE) ) ) name = file_obj.read(data.name_size).decode(common.ENCODE) header = { "global_phase": data.global_phase, "num_qubits": data.num_qubits, "num_clbits": data.num_clbits, "num_registers": data.num_registers, "num_instructions": data.num_instructions, } metadata_raw = file_obj.read(data.metadata_size) metadata = json.loads(metadata_raw, cls=metadata_deserializer) return header, name, metadata def _read_registers_v4(file_obj, num_registers): # type: ignore[no-untyped-def] registers = {"q": {}, "c": {}} for _reg in range(num_registers): data = formats.REGISTER_V4._make( struct.unpack( formats.REGISTER_V4_PACK, file_obj.read(formats.REGISTER_V4_SIZE), ) ) name = file_obj.read(data.name_size).decode("utf8") REGISTER_ARRAY_PACK = "!%sq" % data.size bit_indices_raw = file_obj.read(struct.calcsize(REGISTER_ARRAY_PACK)) bit_indices = list(struct.unpack(REGISTER_ARRAY_PACK, bit_indices_raw)) if data.type.decode("utf8") == "q": registers["q"][name] = (data.standalone, bit_indices, data.in_circuit) else: registers["c"][name] = (data.standalone, bit_indices, data.in_circuit) return registers def _read_registers(file_obj, num_registers): # type: ignore[no-untyped-def] registers = {"q": {}, "c": {}} for _reg in range(num_registers): data = formats.REGISTER._make( struct.unpack( formats.REGISTER_PACK, file_obj.read(formats.REGISTER_SIZE), ) ) name = file_obj.read(data.name_size).decode("utf8") REGISTER_ARRAY_PACK = "!%sI" % data.size bit_indices_raw = file_obj.read(struct.calcsize(REGISTER_ARRAY_PACK)) bit_indices = list(struct.unpack(REGISTER_ARRAY_PACK, bit_indices_raw)) if data.type.decode("utf8") == "q": registers["q"][name] = (data.standalone, bit_indices, True) else: registers["c"][name] = (data.standalone, bit_indices, True) return registers def _read_instruction_parameter(file_obj, version, vectors): # type: ignore[no-untyped-def] type_key, bin_data = common.read_instruction_param(file_obj) if type_key == common.ProgramTypeKey.CIRCUIT: param = common.data_from_binary(bin_data, read_circuit, version=version) elif type_key == common.ContainerTypeKey.RANGE: data = formats.RANGE._make(struct.unpack(formats.RANGE_PACK, bin_data)) param = range(data.start, data.stop, data.step) elif type_key == common.ContainerTypeKey.TUPLE: param = tuple( common.sequence_from_binary( bin_data, _read_instruction_parameter, version=version, vectors=vectors, ) ) elif type_key == common.ValueTypeKey.INTEGER: # TODO This uses little endian. Should be fixed in the next QPY version. param = struct.unpack("<q", bin_data)[0] elif type_key == common.ValueTypeKey.FLOAT: # TODO This uses little endian. Should be fixed in the next QPY version. param = struct.unpack("<d", bin_data)[0] else: param = value.loads_value(type_key, bin_data, version, vectors) return param def _read_instruction( # type: ignore[no-untyped-def] file_obj, circuit, registers, custom_instructions, version, vectors ): instruction = formats.CIRCUIT_INSTRUCTION._make( struct.unpack( formats.CIRCUIT_INSTRUCTION_PACK, file_obj.read(formats.CIRCUIT_INSTRUCTION_SIZE), ) ) gate_name = file_obj.read(instruction.name_size).decode(common.ENCODE) label = file_obj.read(instruction.label_size).decode(common.ENCODE) condition_register = file_obj.read(instruction.condition_register_size).decode( common.ENCODE ) qargs = [] cargs = [] params = [] condition_tuple = None if instruction.has_condition: # If an invalid register name is used assume it's a single bit # condition and treat the register name as a string of the clbit index if ClassicalRegister.name_format.match(condition_register) is None: # If invalid register prefixed with null character it's a clbit # index for single bit condition if condition_register[0] == "\x00": conditional_bit = int(condition_register[1:]) condition_tuple = ( circuit.clbits[conditional_bit], instruction.condition_value, ) else: raise ValueError( f"Invalid register name: {condition_register} for condition register of " f"instruction: {gate_name}" ) else: condition_tuple = ( registers["c"][condition_register], instruction.condition_value, ) qubit_indices = dict(enumerate(circuit.qubits)) clbit_indices = dict(enumerate(circuit.clbits)) # Load Arguments for _qarg in range(instruction.num_qargs): qarg = formats.CIRCUIT_INSTRUCTION_ARG._make( struct.unpack( formats.CIRCUIT_INSTRUCTION_ARG_PACK, file_obj.read(formats.CIRCUIT_INSTRUCTION_ARG_SIZE), ) ) if qarg.type.decode(common.ENCODE) == "c": raise TypeError("Invalid input carg prior to all qargs") qargs.append(qubit_indices[qarg.size]) for _carg in range(instruction.num_cargs): carg = formats.CIRCUIT_INSTRUCTION_ARG._make( struct.unpack( formats.CIRCUIT_INSTRUCTION_ARG_PACK, file_obj.read(formats.CIRCUIT_INSTRUCTION_ARG_SIZE), ) ) if carg.type.decode(common.ENCODE) == "q": raise TypeError("Invalid input qarg after all qargs") cargs.append(clbit_indices[carg.size]) # Load Parameters for _param in range(instruction.num_parameters): param = _read_instruction_parameter(file_obj, version, vectors) params.append(param) # Load Gate object if gate_name in ("Gate", "Instruction"): inst_obj = _parse_custom_instruction(custom_instructions, gate_name, params) inst_obj.condition = condition_tuple if instruction.label_size > 0: inst_obj.label = label circuit._append(inst_obj, qargs, cargs) return elif gate_name in custom_instructions: inst_obj = _parse_custom_instruction(custom_instructions, gate_name, params) inst_obj.condition = condition_tuple if instruction.label_size > 0: inst_obj.label = label circuit._append(inst_obj, qargs, cargs) return elif hasattr(library, gate_name): gate_class = getattr(library, gate_name) elif hasattr(circuit_mod, gate_name): gate_class = getattr(circuit_mod, gate_name) elif hasattr(extensions, gate_name): gate_class = getattr(extensions, gate_name) elif hasattr(quantum_initializer, gate_name): gate_class = getattr(quantum_initializer, gate_name) elif hasattr(controlflow, gate_name): gate_class = getattr(controlflow, gate_name) else: raise AttributeError("Invalid instruction type: %s" % gate_name) if gate_name in {"IfElseOp", "WhileLoopOp"}: gate = gate_class(condition_tuple, *params) else: if gate_name in {"Initialize", "UCRXGate", "UCRYGate", "UCRZGate"}: gate = gate_class(params) else: if gate_name == "Barrier": params = [len(qargs)] elif gate_name in {"BreakLoopOp", "ContinueLoopOp"}: params = [len(qargs), len(cargs)] gate = gate_class(*params) gate.condition = condition_tuple if instruction.label_size > 0: gate.label = label if not isinstance(gate, Instruction): circuit.append(gate, qargs, cargs) else: circuit._append(gate, qargs, cargs) def _parse_custom_instruction( # type: ignore[no-untyped-def] custom_instructions, gate_name, params ): type_str, num_qubits, num_clbits, definition = custom_instructions[gate_name] type_key = common.CircuitInstructionTypeKey(type_str) if type_key == common.CircuitInstructionTypeKey.INSTRUCTION: inst_obj = Instruction(gate_name, num_qubits, num_clbits, params) if definition is not None: inst_obj.definition = definition return inst_obj if type_key == common.CircuitInstructionTypeKey.GATE: inst_obj = Gate(gate_name, num_qubits, params) inst_obj.definition = definition return inst_obj if type_key == common.CircuitInstructionTypeKey.PAULI_EVOL_GATE: return definition raise ValueError("Invalid custom instruction type '%s'" % type_str) def _read_pauli_evolution_gate(file_obj, version, vectors): # type: ignore[no-untyped-def] pauli_evolution_def = formats.PAULI_EVOLUTION_DEF._make( struct.unpack( formats.PAULI_EVOLUTION_DEF_PACK, file_obj.read(formats.PAULI_EVOLUTION_DEF_SIZE), ) ) if pauli_evolution_def.operator_size != 1 and pauli_evolution_def.standalone_op: raise ValueError( "Can't have a standalone operator with {pauli_evolution_raw[0]} operators in the payload" ) operator_list = [] for _ in range(pauli_evolution_def.operator_size): op_elem = formats.SPARSE_PAULI_OP_LIST_ELEM._make( struct.unpack( formats.SPARSE_PAULI_OP_LIST_ELEM_PACK, file_obj.read(formats.SPARSE_PAULI_OP_LIST_ELEM_SIZE), ) ) op_raw_data = common.data_from_binary(file_obj.read(op_elem.size), np.load) operator_list.append(SparsePauliOp.from_list(op_raw_data)) if pauli_evolution_def.standalone_op: pauli_op = operator_list[0] else: pauli_op = operator_list time = value.loads_value( common.ValueTypeKey(pauli_evolution_def.time_type), file_obj.read(pauli_evolution_def.time_size), version=version, vectors=vectors, ) synth_data = json.loads(file_obj.read(pauli_evolution_def.synth_method_size)) synthesis = getattr(evo_synth, synth_data["class"])(**synth_data["settings"]) return_gate = library.PauliEvolutionGate(pauli_op, time=time, synthesis=synthesis) return return_gate def _read_custom_instructions(file_obj, version, vectors): # type: ignore[no-untyped-def] custom_instructions = {} custom_definition_header = formats.CUSTOM_CIRCUIT_DEF_HEADER._make( struct.unpack( formats.CUSTOM_CIRCUIT_DEF_HEADER_PACK, file_obj.read(formats.CUSTOM_CIRCUIT_DEF_HEADER_SIZE), ) ) if custom_definition_header.size > 0: for _ in range(custom_definition_header.size): data = formats.CUSTOM_CIRCUIT_INST_DEF._make( struct.unpack( formats.CUSTOM_CIRCUIT_INST_DEF_PACK, file_obj.read(formats.CUSTOM_CIRCUIT_INST_DEF_SIZE), ) ) name = file_obj.read(data.gate_name_size).decode(common.ENCODE) type_str = data.type definition_circuit = None if data.custom_definition: def_binary = file_obj.read(data.size) if version < 3 or not name.startswith(r"###PauliEvolutionGate_"): definition_circuit = common.data_from_binary( def_binary, read_circuit, version=version ) elif name.startswith(r"###PauliEvolutionGate_"): definition_circuit = common.data_from_binary( def_binary, _read_pauli_evolution_gate, version=version, vectors=vectors, ) custom_instructions[name] = ( type_str, data.num_qubits, data.num_clbits, definition_circuit, ) return custom_instructions def _write_instruction_parameter(file_obj, param): # type: ignore[no-untyped-def] if isinstance(param, QuantumCircuit): type_key = common.ProgramTypeKey.CIRCUIT data = common.data_to_binary(param, write_circuit) elif isinstance(param, range): type_key = common.ContainerTypeKey.RANGE data = struct.pack(formats.RANGE_PACK, param.start, param.stop, param.step) elif isinstance(param, tuple): type_key = common.ContainerTypeKey.TUPLE data = common.sequence_to_binary(param, _write_instruction_parameter) elif isinstance(param, int): # TODO This uses little endian. This should be fixed in next QPY version. type_key = common.ValueTypeKey.INTEGER data = struct.pack("<q", param) elif isinstance(param, float): # TODO This uses little endian. This should be fixed in next QPY version. type_key = common.ValueTypeKey.FLOAT data = struct.pack("<d", param) else: type_key, data = value.dumps_value(param) common.write_instruction_param(file_obj, type_key, data) # pylint: disable=too-many-boolean-expressions def _write_instruction( # type: ignore[no-untyped-def] file_obj, instruction_tuple, custom_instructions, index_map ): gate_class_name = instruction_tuple[0].__class__.__name__ if ( ( not hasattr(library, gate_class_name) and not hasattr(circuit_mod, gate_class_name) and not hasattr(extensions, gate_class_name) and not hasattr(quantum_initializer, gate_class_name) and not hasattr(controlflow, gate_class_name) ) or gate_class_name == "Gate" or gate_class_name == "Instruction" or isinstance(instruction_tuple[0], library.BlueprintCircuit) ): if instruction_tuple[0].name not in custom_instructions: custom_instructions[instruction_tuple[0].name] = instruction_tuple[0] gate_class_name = instruction_tuple[0].name elif isinstance(instruction_tuple[0], library.PauliEvolutionGate): gate_class_name = r"###PauliEvolutionGate_" + str(uuid.uuid4()) custom_instructions[gate_class_name] = instruction_tuple[0] has_condition = False condition_register = b"" condition_value = 0 if instruction_tuple[0].condition: has_condition = True if isinstance(instruction_tuple[0].condition[0], Clbit): bit_index = index_map["c"][instruction_tuple[0].condition[0]] condition_register = b"\x00" + str(bit_index).encode(common.ENCODE) condition_value = int(instruction_tuple[0].condition[1]) else: condition_register = ( instruction_tuple[0].condition[0].name.encode(common.ENCODE) ) condition_value = instruction_tuple[0].condition[1] gate_class_name = gate_class_name.encode(common.ENCODE) label = getattr(instruction_tuple[0], "label") if label: label_raw = label.encode(common.ENCODE) else: label_raw = b"" instruction_raw = struct.pack( formats.CIRCUIT_INSTRUCTION_PACK, len(gate_class_name), len(label_raw), len(instruction_tuple[0].params), instruction_tuple[0].num_qubits, instruction_tuple[0].num_clbits, has_condition, len(condition_register), condition_value, ) file_obj.write(instruction_raw) file_obj.write(gate_class_name) file_obj.write(label_raw) file_obj.write(condition_register) # Encode instruciton args for qbit in instruction_tuple[1]: instruction_arg_raw = struct.pack( formats.CIRCUIT_INSTRUCTION_ARG_PACK, b"q", index_map["q"][qbit] ) file_obj.write(instruction_arg_raw) for clbit in instruction_tuple[2]: instruction_arg_raw = struct.pack( formats.CIRCUIT_INSTRUCTION_ARG_PACK, b"c", index_map["c"][clbit] ) file_obj.write(instruction_arg_raw) # Encode instruction params for param in instruction_tuple[0].params: _write_instruction_parameter(file_obj, param) def _write_pauli_evolution_gate(file_obj, evolution_gate): # type: ignore[no-untyped-def] operator_list = evolution_gate.operator standalone = False if not isinstance(operator_list, list): operator_list = [operator_list] standalone = True num_operators = len(operator_list) def _write_elem(buffer, op): # type: ignore[no-untyped-def] elem_data = common.data_to_binary(op.to_list(array=True), np.save) elem_metadata = struct.pack( formats.SPARSE_PAULI_OP_LIST_ELEM_PACK, len(elem_data) ) buffer.write(elem_metadata) buffer.write(elem_data) pauli_data_buf = io.BytesIO() for operator in operator_list: data = common.data_to_binary(operator, _write_elem) pauli_data_buf.write(data) time_type, time_data = value.dumps_value(evolution_gate.time) time_size = len(time_data) synth_class = str(type(evolution_gate.synthesis).__name__) settings_dict = evolution_gate.synthesis.settings synth_data = json.dumps({"class": synth_class, "settings": settings_dict}).encode( common.ENCODE ) synth_size = len(synth_data) pauli_evolution_raw = struct.pack( formats.PAULI_EVOLUTION_DEF_PACK, num_operators, standalone, time_type, time_size, synth_size, ) file_obj.write(pauli_evolution_raw) file_obj.write(pauli_data_buf.getvalue()) pauli_data_buf.close() file_obj.write(time_data) file_obj.write(synth_data) def _write_custom_instruction(file_obj, name, instruction): # type: ignore[no-untyped-def] type_key = common.CircuitInstructionTypeKey.assign(instruction) has_definition = False size = 0 data = None num_qubits = instruction.num_qubits num_clbits = instruction.num_clbits if type_key == common.CircuitInstructionTypeKey.PAULI_EVOL_GATE: has_definition = True data = common.data_to_binary(instruction, _write_pauli_evolution_gate) size = len(data) elif instruction.definition is not None: has_definition = True data = common.data_to_binary(instruction.definition, write_circuit) size = len(data) name_raw = name.encode(common.ENCODE) custom_instruction_raw = struct.pack( formats.CUSTOM_CIRCUIT_INST_DEF_PACK, len(name_raw), type_key, num_qubits, num_clbits, has_definition, size, ) file_obj.write(custom_instruction_raw) file_obj.write(name_raw) if data: file_obj.write(data) def _write_registers(file_obj, in_circ_regs, full_bits): # type: ignore[no-untyped-def] bitmap = {bit: index for index, bit in enumerate(full_bits)} processed_indices = set() out_circ_regs = set() for bit in full_bits: if bit._register is not None and bit._register not in in_circ_regs: out_circ_regs.add(bit._register) for regs, is_in_circuit in [(in_circ_regs, True), (out_circ_regs, False)]: for reg in regs: standalone = all(bit._register is reg for bit in reg) reg_name = reg.name.encode(common.ENCODE) reg_type = reg.prefix.encode(common.ENCODE) file_obj.write( struct.pack( formats.REGISTER_V4_PACK, reg_type, standalone, reg.size, len(reg_name), is_in_circuit, ) ) file_obj.write(reg_name) REGISTER_ARRAY_PACK = "!%sq" % reg.size bit_indices = [] for bit in reg: bit_index = bitmap.get(bit, -1) if bit_index in processed_indices: bit_index = -1 if bit_index >= 0: processed_indices.add(bit_index) bit_indices.append(bit_index) file_obj.write(struct.pack(REGISTER_ARRAY_PACK, *bit_indices)) return len(in_circ_regs) + len(out_circ_regs) def write_circuit(file_obj, circuit, metadata_serializer=None): # type: ignore[no-untyped-def] """Write a single QuantumCircuit object in the file like object. Args: file_obj (FILE): The file like object to write the circuit data in. circuit (QuantumCircuit): The circuit data to write. metadata_serializer (JSONEncoder): An optional JSONEncoder class that will be passed the :attr:`.QuantumCircuit.metadata` dictionary for each circuit in ``circuits`` and will be used as the ``cls`` kwarg on the ``json.dump()`` call to JSON serialize that dictionary. """ metadata_raw = json.dumps( circuit.metadata, separators=(",", ":"), cls=metadata_serializer ).encode(common.ENCODE) metadata_size = len(metadata_raw) num_instructions = len(circuit) circuit_name = circuit.name.encode(common.ENCODE) global_phase_type, global_phase_data = value.dumps_value(circuit.global_phase) with io.BytesIO() as reg_buf: num_qregs = _write_registers(reg_buf, circuit.qregs, circuit.qubits) num_cregs = _write_registers(reg_buf, circuit.cregs, circuit.clbits) registers_raw = reg_buf.getvalue() num_registers = num_qregs + num_cregs # Write circuit header header_raw = formats.CIRCUIT_HEADER_V2( name_size=len(circuit_name), global_phase_type=global_phase_type, global_phase_size=len(global_phase_data), num_qubits=circuit.num_qubits, num_clbits=circuit.num_clbits, metadata_size=metadata_size, num_registers=num_registers, num_instructions=num_instructions, ) header = struct.pack(formats.CIRCUIT_HEADER_V2_PACK, *header_raw) file_obj.write(header) file_obj.write(circuit_name) file_obj.write(global_phase_data) file_obj.write(metadata_raw) # Write header payload file_obj.write(registers_raw) instruction_buffer = io.BytesIO() custom_instructions = {} index_map = {} index_map["q"] = {bit: index for index, bit in enumerate(circuit.qubits)} index_map["c"] = {bit: index for index, bit in enumerate(circuit.clbits)} for instruction in circuit.data: _write_instruction( instruction_buffer, instruction, custom_instructions, index_map ) file_obj.write( struct.pack(formats.CUSTOM_CIRCUIT_DEF_HEADER_PACK, len(custom_instructions)) ) for name, instruction in custom_instructions.items(): _write_custom_instruction(file_obj, name, instruction) instruction_buffer.seek(0) file_obj.write(instruction_buffer.read()) instruction_buffer.close() def read_circuit(file_obj, version, metadata_deserializer=None): # type: ignore[no-untyped-def] """Read a single QuantumCircuit object from the file like object. Args: file_obj (FILE): The file like object to read the circuit data from. version (int): QPY version. metadata_deserializer (JSONDecoder): An optional JSONDecoder class that will be used for the ``cls`` kwarg on the internal ``json.load`` call used to deserialize the JSON payload used for the :attr:`.QuantumCircuit.metadata` attribute for any circuits in the QPY file. If this is not specified the circuit metadata will be parsed as JSON with the stdlib ``json.load()`` function using the default ``JSONDecoder`` class. Returns: QuantumCircuit: The circuit object from the file. Raises: QpyError: Invalid register. """ vectors = {} if version < 2: header, name, metadata = _read_header( file_obj, metadata_deserializer=metadata_deserializer ) else: header, name, metadata = _read_header_v2( file_obj, version, vectors, metadata_deserializer=metadata_deserializer ) global_phase = header["global_phase"] num_qubits = header["num_qubits"] num_clbits = header["num_clbits"] num_registers = header["num_registers"] num_instructions = header["num_instructions"] out_registers = {"q": {}, "c": {}} if num_registers > 0: circ = QuantumCircuit(name=name, global_phase=global_phase, metadata=metadata) if version < 4: registers = _read_registers(file_obj, num_registers) else: registers = _read_registers_v4(file_obj, num_registers) for bit_type_label, bit_type, reg_type in [ ("q", Qubit, QuantumRegister), ("c", Clbit, ClassicalRegister), ]: register_bits = set() # Add quantum registers and bits for register_name in registers[bit_type_label]: standalone, indices, in_circuit = registers[bit_type_label][ register_name ] indices_defined = [x for x in indices if x >= 0] # If a register has no bits in the circuit skip it if not indices_defined: continue if standalone: start = min(indices_defined) count = start out_of_order = False for index in indices: if index < 0: out_of_order = True continue if not out_of_order and index != count: out_of_order = True count += 1 if index in register_bits: # If we have a bit in the position already it's been # added by an earlier register in the circuit # otherwise it's invalid qpy if not in_circuit: continue raise exceptions.QpyError("Duplicate register bits found") register_bits.add(index) num_reg_bits = len(indices) # Create a standlone register of the appropriate length (from # the number of indices in the qpy data) and add it to the circuit reg = reg_type(num_reg_bits, register_name) # If any bits from qreg are out of order in the circuit handle # is case if out_of_order or not in_circuit: for index, pos in sorted( enumerate(x for x in indices if x >= 0), key=lambda x: x[1] ): if bit_type_label == "q": bit_len = len(circ.qubits) else: bit_len = len(circ.clbits) if pos < bit_len: # If we have a bit in the position already it's been # added by an earlier register in the circuit # otherwise it's invalid qpy if not in_circuit: continue raise exceptions.QpyError( "Duplicate register bits found" ) # Fill any holes between the current register bit and the # next one if pos > bit_len: bits = [bit_type() for _ in range(pos - bit_len)] circ.add_bits(bits) circ.add_bits([reg[index]]) if in_circuit: circ.add_register(reg) else: if bit_type_label == "q": bit_len = len(circ.qubits) else: bit_len = len(circ.clbits) # If there is a hole between the start of the register and the # current bits and standalone bits to fill the gap. if start > len(circ.qubits): bits = [bit_type() for _ in range(start - bit_len)] circ.add_bits(bit_len) if in_circuit: circ.add_register(reg) out_registers[bit_type_label][register_name] = reg else: for index in indices: if bit_type_label == "q": bit_len = len(circ.qubits) else: bit_len = len(circ.clbits) # Add any missing bits bits = [bit_type() for _ in range(index + 1 - bit_len)] circ.add_bits(bits) if index in register_bits: raise exceptions.QpyError("Duplicate register bits found") register_bits.add(index) if bit_type_label == "q": bits = [circ.qubits[i] for i in indices] else: bits = [circ.clbits[i] for i in indices] reg = reg_type(name=register_name, bits=bits) if in_circuit: circ.add_register(reg) out_registers[bit_type_label][register_name] = reg # If we don't have sufficient bits in the circuit after adding # all the registers add more bits to fill the circuit if len(circ.qubits) < num_qubits: qubits = [Qubit() for _ in range(num_qubits - len(circ.qubits))] circ.add_bits(qubits) if len(circ.clbits) < num_clbits: clbits = [Clbit() for _ in range(num_qubits - len(circ.clbits))] circ.add_bits(clbits) else: circ = QuantumCircuit( num_qubits, num_clbits, name=name, global_phase=global_phase, metadata=metadata, ) custom_instructions = _read_custom_instructions(file_obj, version, vectors) for _instruction in range(num_instructions): _read_instruction( file_obj, circ, out_registers, custom_instructions, version, vectors ) for vec_name, (vector, initialized_params) in vectors.items(): if len(initialized_params) != len(vector): warnings.warn( f"The ParameterVector: '{vec_name}' is not fully identical to its " "pre-serialization state. Elements " f"{', '.join([str(x) for x in set(range(len(vector))) - initialized_params])} " "in the ParameterVector will be not equal to the pre-serialized ParameterVector " f"as they weren't used in the circuit: {circ.name}", UserWarning, ) return circ
import argparse import json import random from collections import defaultdict import deepspeed import torch from torch.utils.data import DataLoader from tqdm.auto import trange from gpt_neox import (GPTNeoX, AutoregressiveWrapper, TextSamplerDataset, download_dataset, cycle, prepare_optimizer_parameters, decode_tokens, prepare_enwik8_data) def get_args(): parser = argparse.ArgumentParser(description='GPTNeox Deepspeed Training Script') # Include DeepSpeed configuration arguments parser.add_argument('--model', type=str, default="base_model") parser.add_argument('--local_rank', type=int, default=-1, help='local rank passed from distributed launcher') parser = deepspeed.add_config_arguments(parser) args = parser.parse_args() return args def get_params(model): model_path = model if model.endswith(".json") else f"./configs/{model}.json" with open(model_path) as f: params = json.load(f) return defaultdict(lambda: None, params) train_args = get_args() params = get_params(train_args.model) # instantiate GPT-like decoder model model = GPTNeoX( num_tokens=params["vocab_size"], dim=params["hidden_dim"], seq_len=params["seq_len"], depth=params["n_layers"], heads=params["n_heads"], dim_head=params["dim_head"] ) model = AutoregressiveWrapper(model) # prepare enwik8 data data_path = download_dataset(dataset="enwiki8") data_train, data_val = prepare_enwik8_data(data_path=data_path) train_dataset = TextSamplerDataset(data_train, params["seq_len"]) val_dataset = TextSamplerDataset(data_val, params["seq_len"]) val_loader = cycle(DataLoader(val_dataset, batch_size=params["batch_size"])) # optimizer optim = torch.optim.Adam(model.parameters(), lr=params["learning_rate"]) # training ds_model_params = prepare_optimizer_parameters(model) # deepspeed loader model_engine, optim, train_loader, _ = deepspeed.initialize(args=train_args, model=model, optimizer=optim, model_parameters=ds_model_params, training_data=train_dataset) pbar = trange(params["num_epochs"], mininterval=10., desc='Training Model', dynamic_ncols=True) for _ in pbar: for i, data in enumerate(train_loader): model_engine.train() is_main = model_engine.local_rank == 0 data = data.to(model_engine.local_rank) loss = model_engine(data) model_engine.backward(loss) model_engine.step() pbar.set_description(f'Training Loss: {loss.item():.4f}') pbar.update() if is_main and i % params["validate_every"] == 0: model.eval() with torch.no_grad(): val_data = next(val_loader).cuda() loss = model(val_data) pbar.write(f'Validation Loss: {loss.item()}') if is_main and i % params["generate_every"] == 0: model.eval() inp = random.choice(val_dataset)[:-1] prime = decode_tokens(inp) pbar.write(f"{prime} \n\n {"*" * 100}") sample = model.generate(inp.cuda(), params["generate_length"]) output_str = decode_tokens(sample) pbar.write(output_str)
import argparse import json import random from collections import defaultdict import deepspeed import torch from torch.utils.data import DataLoader from tqdm.auto import trange from gpt_neox import (GPTNeoX, AutoregressiveWrapper, TextSamplerDataset, download_dataset, cycle, prepare_optimizer_parameters, decode_tokens, prepare_enwik8_data) def get_args(): parser = argparse.ArgumentParser(description='GPTNeox Deepspeed Training Script') # Include DeepSpeed configuration arguments parser.add_argument('--model', type=str, default="base_model") parser.add_argument('--local_rank', type=int, default=-1, help='local rank passed from distributed launcher') parser = deepspeed.add_config_arguments(parser) args = parser.parse_args() return args def get_params(model): model_path = model if model.endswith(".json") else f"./configs/{model}.json" with open(model_path) as f: params = json.load(f) return defaultdict(lambda: None, params) train_args = get_args() params = get_params(train_args.model) # instantiate GPT-like decoder model model = GPTNeoX( num_tokens=params["vocab_size"], dim=params["hidden_dim"], seq_len=params["seq_len"], depth=params["n_layers"], heads=params["n_heads"], dim_head=params["dim_head"] ) model = AutoregressiveWrapper(model) # prepare enwik8 data data_path = download_dataset(dataset="enwiki8") data_train, data_val = prepare_enwik8_data(data_path=data_path) train_dataset = TextSamplerDataset(data_train, params["seq_len"]) val_dataset = TextSamplerDataset(data_val, params["seq_len"]) val_loader = cycle(DataLoader(val_dataset, batch_size=params["batch_size"])) # optimizer optim = torch.optim.Adam(model.parameters(), lr=params["learning_rate"]) # training ds_model_params = prepare_optimizer_parameters(model) # deepspeed loader model_engine, optim, train_loader, _ = deepspeed.initialize(args=train_args, model=model, optimizer=optim, model_parameters=ds_model_params, training_data=train_dataset) pbar = trange(params["num_epochs"], mininterval=10., desc='Training Model', dynamic_ncols=True) for _ in pbar: for i, data in enumerate(train_loader): model_engine.train() is_main = model_engine.local_rank == 0 data = data.to(model_engine.local_rank) loss = model_engine(data) model_engine.backward(loss) model_engine.step() pbar.set_description(f'Training Loss: {loss.item():.4f}') pbar.update() if is_main and i % params["validate_every"] == 0: model.eval() with torch.no_grad(): val_data = next(val_loader).cuda() loss = model(val_data) pbar.write(f'Validation Loss: {loss.item()}') if is_main and i % params["generate_every"] == 0: model.eval() inp = random.choice(val_dataset)[:-1] prime = decode_tokens(inp) pbar.write(f"{prime} \n\n {'*' * 100}") sample = model.generate(inp.cuda(), params["generate_length"]) output_str = decode_tokens(sample) pbar.write(output_str)
import os import time import torch import numpy as np """[ElegantRL.2021.09.18](https://github.com/AI4Finance-LLC/ElegantRL)""" class Evaluator: def __init__(self, cwd, agent_id, device, eval_env, eval_gap, eval_times1, eval_times2, ): self.recorder = list() # total_step, r_avg, r_std, obj_c, ... self.recorder_path = f'{cwd}/recorder.npy' self.cwd = cwd self.device = device self.agent_id = agent_id self.eval_env = eval_env self.eval_gap = eval_gap self.eval_times1 = eval_times1 self.eval_times2 = eval_times2 self.target_return = eval_env.target_return self.r_max = -np.inf self.eval_time = 0 self.used_time = 0 self.total_step = 0 self.start_time = time.time() print(f"{"#" * 80}\n" f"{"ID":<3}{"Step":>8}{"maxR":>8} |" f"{"avgR":>8}{"stdR":>7}{"avgS":>7}{"stdS":>6} |" f"{"expR":>8}{"objC":>7}{"etc.":>7}") def evaluate_and_save(self, act, steps, r_exp, log_tuple) -> (bool, bool): # 2021-09-09 self.total_step += steps # update total training steps if time.time() - self.eval_time < self.eval_gap: if_reach_goal = False if_save = False else: self.eval_time = time.time() '''evaluate first time''' rewards_steps_list = [get_episode_return_and_step(self.eval_env, act, self.device) for _ in range(self.eval_times1)] r_avg, r_std, s_avg, s_std = self.get_r_avg_std_s_avg_std(rewards_steps_list) '''evaluate second time''' if r_avg > self.r_max: # evaluate actor twice to save CPU Usage and keep precision rewards_steps_list += [get_episode_return_and_step(self.eval_env, act, self.device) for _ in range(self.eval_times2 - self.eval_times1)] r_avg, r_std, s_avg, s_std = self.get_r_avg_std_s_avg_std(rewards_steps_list) '''save the policy network''' if_save = r_avg > self.r_max if if_save: # save checkpoint with highest episode return self.r_max = r_avg # update max reward (episode return) act_save_path = f'{self.cwd}/actor.pth' torch.save(act.state_dict(), act_save_path) # save policy network in *.pth print(f"{self.agent_id:<3}{self.total_step:8.2e}{self.r_max:8.2f} |") # save policy and print self.recorder.append((self.total_step, r_avg, r_std, r_exp, *log_tuple)) # update recorder '''print some information to Terminal''' if_reach_goal = bool(self.r_max > self.target_return) # check if_reach_goal if if_reach_goal and self.used_time is None: self.used_time = int(time.time() - self.start_time) print(f"{"ID":<3}{"Step":>8}{"TargetR":>8} |" f"{"avgR":>8}{"stdR":>7}{"avgS":>7}{"stdS":>6} |" f"{"UsedTime":>8} ########\n" f"{self.agent_id:<3}{self.total_step:8.2e}{self.target_return:8.2f} |" f"{r_avg:8.2f}{r_std:7.1f}{s_avg:7.0f}{s_std:6.0f} |" f"{self.used_time:>8} ########") print(f"{self.agent_id:<3}{self.total_step:8.2e}{self.r_max:8.2f} |" f"{r_avg:8.2f}{r_std:7.1f}{s_avg:7.0f}{s_std:6.0f} |" f"{r_exp:8.2f}{"".join(f"{n:7.2f}' for n in log_tuple)}") self.draw_plot() return if_reach_goal, if_save @staticmethod def get_r_avg_std_s_avg_std(rewards_steps_list): rewards_steps_ary = np.array(rewards_steps_list, dtype=np.float32) r_avg, s_avg = rewards_steps_ary.mean(axis=0) # average of episode return and episode step r_std, s_std = rewards_steps_ary.std(axis=0) # standard dev. of episode return and episode step return r_avg, r_std, s_avg, s_std def save_or_load_recoder(self, if_save): if if_save: np.save(self.recorder_path, self.recorder) elif os.path.exists(self.recorder_path): recorder = np.load(self.recorder_path) self.recorder = [tuple(i) for i in recorder] # convert numpy to list self.total_step = self.recorder[-1][0] def draw_plot(self): if len(self.recorder) == 0: print("| save_npy_draw_plot() WARNNING: len(self.recorder)==0") return None np.save(self.recorder_path, self.recorder) '''draw plot and save as png''' train_time = int(time.time() - self.start_time) total_step = int(self.recorder[-1][0]) save_title = f"step_time_maxR_{int(total_step)}_{int(train_time)}_{self.r_max:.3f}" save_learning_curve(self.recorder, self.cwd, save_title) def get_episode_return_and_step(env, act, device) -> (float, int): episode_step = 1 episode_return = 0.0 # sum of rewards in an episode max_step = env.max_step if_discrete = env.if_discrete state = env.reset() for episode_step in range(max_step): s_tensor = torch.as_tensor((state,), device=device) a_tensor = act(s_tensor) if if_discrete: a_tensor = a_tensor.argmax(dim=1) action = a_tensor.detach().cpu().numpy()[0] # not need detach(), because with torch.no_grad() outside state, reward, done, _ = env.step(action) episode_return += reward if done: break episode_return = getattr(env, 'episode_return', episode_return) return episode_return, episode_step def save_learning_curve(recorder=None, cwd='.', save_title='learning curve', fig_name='plot_learning_curve.jpg'): if recorder is None: recorder = np.load(f"{cwd}/recorder.npy") recorder = np.array(recorder) steps = recorder[:, 0] # x-axis is training steps r_avg = recorder[:, 1] r_std = recorder[:, 2] r_exp = recorder[:, 3] obj_c = recorder[:, 4] obj_a = recorder[:, 5] '''plot subplots''' import matplotlib as mpl mpl.use('Agg') """Generating matplotlib graphs without a running X server [duplicate] write `mpl.use('Agg')` before `import matplotlib.pyplot as plt` https://stackoverflow.com/a/4935945/9293137 """ import matplotlib.pyplot as plt fig, axs = plt.subplots(2) '''axs[0]''' ax00 = axs[0] ax00.cla() ax01 = axs[0].twinx() color01 = 'darkcyan' ax01.set_ylabel('Explore AvgReward', color=color01) ax01.plot(steps, r_exp, color=color01, alpha=0.5, ) ax01.tick_params(axis='y', labelcolor=color01) color0 = 'lightcoral' ax00.set_ylabel('Episode Return') ax00.plot(steps, r_avg, label='Episode Return', color=color0) ax00.fill_between(steps, r_avg - r_std, r_avg + r_std, facecolor=color0, alpha=0.3) ax00.grid() '''axs[1]''' ax10 = axs[1] ax10.cla() ax11 = axs[1].twinx() color11 = 'darkcyan' ax11.set_ylabel('objC', color=color11) ax11.fill_between(steps, obj_c, facecolor=color11, alpha=0.2, ) ax11.tick_params(axis='y', labelcolor=color11) color10 = 'royalblue' ax10.set_xlabel('Total Steps') ax10.set_ylabel('objA', color=color10) ax10.plot(steps, obj_a, label='objA', color=color10) ax10.tick_params(axis='y', labelcolor=color10) for plot_i in range(6, recorder.shape[1]): other = recorder[:, plot_i] ax10.plot(steps, other, label=f'{plot_i}', color='grey', alpha=0.5) ax10.legend() ax10.grid() '''plot save''' plt.title(save_title, y=2.3) plt.savefig(f"{cwd}/{fig_name}") plt.close('all') # avoiding warning about too many open figures, rcParam `figure.max_open_warning` # plt.show() # if use `mpl.use('Agg')` to draw figures without GUI, then plt can't plt.show()
import os import time import torch import numpy as np """[ElegantRL.2021.09.18](https://github.com/AI4Finance-LLC/ElegantRL)""" class Evaluator: def __init__(self, cwd, agent_id, device, eval_env, eval_gap, eval_times1, eval_times2, ): self.recorder = list() # total_step, r_avg, r_std, obj_c, ... self.recorder_path = f'{cwd}/recorder.npy' self.cwd = cwd self.device = device self.agent_id = agent_id self.eval_env = eval_env self.eval_gap = eval_gap self.eval_times1 = eval_times1 self.eval_times2 = eval_times2 self.target_return = eval_env.target_return self.r_max = -np.inf self.eval_time = 0 self.used_time = 0 self.total_step = 0 self.start_time = time.time() print(f"{'#' * 80}\n" f"{'ID':<3}{'Step':>8}{'maxR':>8} |" f"{'avgR':>8}{'stdR':>7}{'avgS':>7}{'stdS':>6} |" f"{'expR':>8}{'objC':>7}{'etc.':>7}") def evaluate_and_save(self, act, steps, r_exp, log_tuple) -> (bool, bool): # 2021-09-09 self.total_step += steps # update total training steps if time.time() - self.eval_time < self.eval_gap: if_reach_goal = False if_save = False else: self.eval_time = time.time() '''evaluate first time''' rewards_steps_list = [get_episode_return_and_step(self.eval_env, act, self.device) for _ in range(self.eval_times1)] r_avg, r_std, s_avg, s_std = self.get_r_avg_std_s_avg_std(rewards_steps_list) '''evaluate second time''' if r_avg > self.r_max: # evaluate actor twice to save CPU Usage and keep precision rewards_steps_list += [get_episode_return_and_step(self.eval_env, act, self.device) for _ in range(self.eval_times2 - self.eval_times1)] r_avg, r_std, s_avg, s_std = self.get_r_avg_std_s_avg_std(rewards_steps_list) '''save the policy network''' if_save = r_avg > self.r_max if if_save: # save checkpoint with highest episode return self.r_max = r_avg # update max reward (episode return) act_save_path = f'{self.cwd}/actor.pth' torch.save(act.state_dict(), act_save_path) # save policy network in *.pth print(f"{self.agent_id:<3}{self.total_step:8.2e}{self.r_max:8.2f} |") # save policy and print self.recorder.append((self.total_step, r_avg, r_std, r_exp, *log_tuple)) # update recorder '''print some information to Terminal''' if_reach_goal = bool(self.r_max > self.target_return) # check if_reach_goal if if_reach_goal and self.used_time is None: self.used_time = int(time.time() - self.start_time) print(f"{'ID':<3}{'Step':>8}{'TargetR':>8} |" f"{'avgR':>8}{'stdR':>7}{'avgS':>7}{'stdS':>6} |" f"{'UsedTime':>8} ########\n" f"{self.agent_id:<3}{self.total_step:8.2e}{self.target_return:8.2f} |" f"{r_avg:8.2f}{r_std:7.1f}{s_avg:7.0f}{s_std:6.0f} |" f"{self.used_time:>8} ########") print(f"{self.agent_id:<3}{self.total_step:8.2e}{self.r_max:8.2f} |" f"{r_avg:8.2f}{r_std:7.1f}{s_avg:7.0f}{s_std:6.0f} |" f"{r_exp:8.2f}{''.join(f'{n:7.2f}' for n in log_tuple)}") self.draw_plot() return if_reach_goal, if_save @staticmethod def get_r_avg_std_s_avg_std(rewards_steps_list): rewards_steps_ary = np.array(rewards_steps_list, dtype=np.float32) r_avg, s_avg = rewards_steps_ary.mean(axis=0) # average of episode return and episode step r_std, s_std = rewards_steps_ary.std(axis=0) # standard dev. of episode return and episode step return r_avg, r_std, s_avg, s_std def save_or_load_recoder(self, if_save): if if_save: np.save(self.recorder_path, self.recorder) elif os.path.exists(self.recorder_path): recorder = np.load(self.recorder_path) self.recorder = [tuple(i) for i in recorder] # convert numpy to list self.total_step = self.recorder[-1][0] def draw_plot(self): if len(self.recorder) == 0: print("| save_npy_draw_plot() WARNNING: len(self.recorder)==0") return None np.save(self.recorder_path, self.recorder) '''draw plot and save as png''' train_time = int(time.time() - self.start_time) total_step = int(self.recorder[-1][0]) save_title = f"step_time_maxR_{int(total_step)}_{int(train_time)}_{self.r_max:.3f}" save_learning_curve(self.recorder, self.cwd, save_title) def get_episode_return_and_step(env, act, device) -> (float, int): episode_step = 1 episode_return = 0.0 # sum of rewards in an episode max_step = env.max_step if_discrete = env.if_discrete state = env.reset() for episode_step in range(max_step): s_tensor = torch.as_tensor((state,), device=device) a_tensor = act(s_tensor) if if_discrete: a_tensor = a_tensor.argmax(dim=1) action = a_tensor.detach().cpu().numpy()[0] # not need detach(), because with torch.no_grad() outside state, reward, done, _ = env.step(action) episode_return += reward if done: break episode_return = getattr(env, 'episode_return', episode_return) return episode_return, episode_step def save_learning_curve(recorder=None, cwd='.', save_title='learning curve', fig_name='plot_learning_curve.jpg'): if recorder is None: recorder = np.load(f"{cwd}/recorder.npy") recorder = np.array(recorder) steps = recorder[:, 0] # x-axis is training steps r_avg = recorder[:, 1] r_std = recorder[:, 2] r_exp = recorder[:, 3] obj_c = recorder[:, 4] obj_a = recorder[:, 5] '''plot subplots''' import matplotlib as mpl mpl.use('Agg') """Generating matplotlib graphs without a running X server [duplicate] write `mpl.use('Agg')` before `import matplotlib.pyplot as plt` https://stackoverflow.com/a/4935945/9293137 """ import matplotlib.pyplot as plt fig, axs = plt.subplots(2) '''axs[0]''' ax00 = axs[0] ax00.cla() ax01 = axs[0].twinx() color01 = 'darkcyan' ax01.set_ylabel('Explore AvgReward', color=color01) ax01.plot(steps, r_exp, color=color01, alpha=0.5, ) ax01.tick_params(axis='y', labelcolor=color01) color0 = 'lightcoral' ax00.set_ylabel('Episode Return') ax00.plot(steps, r_avg, label='Episode Return', color=color0) ax00.fill_between(steps, r_avg - r_std, r_avg + r_std, facecolor=color0, alpha=0.3) ax00.grid() '''axs[1]''' ax10 = axs[1] ax10.cla() ax11 = axs[1].twinx() color11 = 'darkcyan' ax11.set_ylabel('objC', color=color11) ax11.fill_between(steps, obj_c, facecolor=color11, alpha=0.2, ) ax11.tick_params(axis='y', labelcolor=color11) color10 = 'royalblue' ax10.set_xlabel('Total Steps') ax10.set_ylabel('objA', color=color10) ax10.plot(steps, obj_a, label='objA', color=color10) ax10.tick_params(axis='y', labelcolor=color10) for plot_i in range(6, recorder.shape[1]): other = recorder[:, plot_i] ax10.plot(steps, other, label=f'{plot_i}', color='grey', alpha=0.5) ax10.legend() ax10.grid() '''plot save''' plt.title(save_title, y=2.3) plt.savefig(f"{cwd}/{fig_name}") plt.close('all') # avoiding warning about too many open figures, rcParam `figure.max_open_warning` # plt.show() # if use `mpl.use('Agg')` to draw figures without GUI, then plt can't plt.show()
""" Typeclass for Account objects Note that this object is primarily intended to store OOC information, not game info! This object represents the actual user (not their character) and has NO actual presence in the game world (this is handled by the associated character object, so you should customize that instead for most things). """ import re import time from django.conf import settings from django.contrib.auth import authenticate, password_validation from django.core.exceptions import ImproperlyConfigured, ValidationError from django.utils import timezone from django.utils.module_loading import import_string from evennia.typeclasses.models import TypeclassBase from evennia.accounts.manager import AccountManager from evennia.accounts.models import AccountDB from evennia.objects.models import ObjectDB from evennia.comms.models import ChannelDB from evennia.commands import cmdhandler from evennia.server.models import ServerConfig from evennia.server.throttle import Throttle from evennia.utils import class_from_module, create, logger from evennia.utils.utils import lazy_property, to_str, make_iter, is_iter, variable_from_module from evennia.server.signals import ( SIGNAL_ACCOUNT_POST_CREATE, SIGNAL_OBJECT_POST_PUPPET, SIGNAL_OBJECT_POST_UNPUPPET, ) from evennia.typeclasses.attributes import NickHandler from evennia.scripts.scripthandler import ScriptHandler from evennia.commands.cmdsethandler import CmdSetHandler from evennia.utils.optionhandler import OptionHandler from django.utils.translation import gettext as _ from random import getrandbits __all__ = ("DefaultAccount",) _SESSIONS = None _AT_SEARCH_RESULT = variable_from_module(*settings.SEARCH_AT_RESULT.rsplit(".", 1)) _MULTISESSION_MODE = settings.MULTISESSION_MODE _MAX_NR_CHARACTERS = settings.MAX_NR_CHARACTERS _CMDSET_ACCOUNT = settings.CMDSET_ACCOUNT _MUDINFO_CHANNEL = None # Create throttles for too many account-creations and login attempts CREATION_THROTTLE = Throttle( limit=settings.CREATION_THROTTLE_LIMIT, timeout=settings.CREATION_THROTTLE_TIMEOUT ) LOGIN_THROTTLE = Throttle( limit=settings.LOGIN_THROTTLE_LIMIT, timeout=settings.LOGIN_THROTTLE_TIMEOUT ) class AccountSessionHandler(object): """ Manages the session(s) attached to an account. """ def __init__(self, account): """ Initializes the handler. Args: account (Account): The Account on which this handler is defined. """ self.account = account def get(self, sessid=None): """ Get the sessions linked to this object. Args: sessid (int, optional): Specify a given session by session id. Returns: sessions (list): A list of Session objects. If `sessid` is given, this is a list with one (or zero) elements. """ global _SESSIONS if not _SESSIONS: from evennia.server.sessionhandler import SESSIONS as _SESSIONS if sessid: return make_iter(_SESSIONS.session_from_account(self.account, sessid)) else: return _SESSIONS.sessions_from_account(self.account) def all(self): """ Alias to get(), returning all sessions. Returns: sessions (list): All sessions. """ return self.get() def count(self): """ Get amount of sessions connected. Returns: sesslen (int): Number of sessions handled. """ return len(self.get()) class DefaultAccount(AccountDB, metaclass=TypeclassBase): """ This is the base Typeclass for all Accounts. Accounts represent the person playing the game and tracks account info, password etc. They are OOC entities without presence in-game. An Account can connect to a Character Object in order to "enter" the game. Account Typeclass API: * Available properties (only available on initiated typeclass objects) - key (string) - name of account - name (string)- wrapper for user.username - aliases (list of strings) - aliases to the object. Will be saved to database as AliasDB entries but returned as strings. - dbref (int, read-only) - unique #id-number. Also "id" can be used. - date_created (string) - time stamp of object creation - permissions (list of strings) - list of permission strings - user (User, read-only) - django User authorization object - obj (Object) - game object controlled by account. 'character' can also be used. - sessions (list of Sessions) - sessions connected to this account - is_superuser (bool, read-only) - if the connected user is a superuser * Handlers - locks - lock-handler: use locks.add() to add new lock strings - db - attribute-handler: store/retrieve database attributes on this self.db.myattr=val, val=self.db.myattr - ndb - non-persistent attribute handler: same as db but does not create a database entry when storing data - scripts - script-handler. Add new scripts to object with scripts.add() - cmdset - cmdset-handler. Use cmdset.add() to add new cmdsets to object - nicks - nick-handler. New nicks with nicks.add(). * Helper methods - msg(text=None, from_obj=None, session=None, options=None, **kwargs) - execute_cmd(raw_string) - search(ostring, global_search=False, attribute_name=None, use_nicks=False, location=None, ignore_errors=False, account=False) - is_typeclass(typeclass, exact=False) - swap_typeclass(new_typeclass, clean_attributes=False, no_default=True) - access(accessing_obj, access_type='read', default=False, no_superuser_bypass=False) - check_permstring(permstring) * Hook methods basetype_setup() at_account_creation() > note that the following hooks are also found on Objects and are usually handled on the character level: - at_init() - at_access() - at_cmdset_get(**kwargs) - at_first_login() - at_post_login(session=None) - at_disconnect() - at_message_receive() - at_message_send() - at_server_reload() - at_server_shutdown() """ objects = AccountManager() # properties @lazy_property def cmdset(self): return CmdSetHandler(self, True) @lazy_property def scripts(self): return ScriptHandler(self) @lazy_property def nicks(self): return NickHandler(self) @lazy_property def sessions(self): return AccountSessionHandler(self) @lazy_property def options(self): return OptionHandler( self, options_dict=settings.OPTIONS_ACCOUNT_DEFAULT, savefunc=self.attributes.add, loadfunc=self.attributes.get, save_kwargs={"category": "option"}, load_kwargs={"category": "option"}, ) # Do not make this a lazy property; the web UI will not refresh it! @property def characters(self): # Get playable characters list objs = self.db._playable_characters or [] # Rebuild the list if legacy code left null values after deletion try: if None in objs: objs = [x for x in self.db._playable_characters if x] self.db._playable_characters = objs except Exception as e: logger.log_trace(e) logger.log_err(e) return objs # session-related methods def disconnect_session_from_account(self, session, reason=None): """ Access method for disconnecting a given session from the account (connection happens automatically in the sessionhandler) Args: session (Session): Session to disconnect. reason (str, optional): Eventual reason for the disconnect. """ global _SESSIONS if not _SESSIONS: from evennia.server.sessionhandler import SESSIONS as _SESSIONS _SESSIONS.disconnect(session, reason) # puppeting operations def puppet_object(self, session, obj): """ Use the given session to control (puppet) the given object (usually a Character type). Args: session (Session): session to use for puppeting obj (Object): the object to start puppeting Raises: RuntimeError: If puppeting is not possible, the `exception.msg` will contain the reason. """ # safety checks if not obj: raise RuntimeError("Object not found") if not session: raise RuntimeError("Session not found") if self.get_puppet(session) == obj: # already puppeting this object self.msg(_("You are already puppeting this object.")) return if not obj.access(self, "puppet"): # no access self.msg(_("You don't have permission to puppet '{key}'.").format(key=obj.key)) return if obj.account: # object already puppeted if obj.account == self: if obj.sessions.count(): # we may take over another of our sessions # output messages to the affected sessions if _MULTISESSION_MODE in (1, 3): txt1 = f"Sharing |c{obj.name}|n with another of your sessions." txt2 = f"|c{obj.name}|n|G is now shared from another of your sessions.|n" self.msg(txt1, session=session) self.msg(txt2, session=obj.sessions.all()) else: txt1 = f"Taking over |c{obj.name}|n from another of your sessions." txt2 = f"|c{obj.name}|n|R is now acted from another of your sessions.|n" self.msg(_(txt1), session=session) self.msg(_(txt2), session=obj.sessions.all()) self.unpuppet_object(obj.sessions.get()) elif obj.account.is_connected: # controlled by another account self.msg(_("|c{key}|R is already puppeted by another Account.").format(key=obj.key)) return # do the puppeting if session.puppet: # cleanly unpuppet eventual previous object puppeted by this session self.unpuppet_object(session) # if we get to this point the character is ready to puppet or it # was left with a lingering account/session reference from an unclean # server kill or similar obj.at_pre_puppet(self, session=session) # do the connection obj.sessions.add(session) obj.account = self session.puid = obj.id session.puppet = obj # validate/start persistent scripts on object obj.scripts.validate() # re-cache locks to make sure superuser bypass is updated obj.locks.cache_lock_bypass(obj) # final hook obj.at_post_puppet() SIGNAL_OBJECT_POST_PUPPET.send(sender=obj, account=self, session=session) def unpuppet_object(self, session): """ Disengage control over an object. Args: session (Session or list): The session or a list of sessions to disengage from their puppets. Raises: RuntimeError With message about error. """ for session in make_iter(session): obj = session.puppet if obj: # do the disconnect, but only if we are the last session to puppet obj.at_pre_unpuppet() obj.sessions.remove(session) if not obj.sessions.count(): del obj.account obj.at_post_unpuppet(self, session=session) SIGNAL_OBJECT_POST_UNPUPPET.send(sender=obj, session=session, account=self) # Just to be sure we're always clear. session.puppet = None session.puid = None def unpuppet_all(self): """ Disconnect all puppets. This is called by server before a reset/shutdown. """ self.unpuppet_object(self.sessions.all()) def get_puppet(self, session): """ Get an object puppeted by this session through this account. This is the main method for retrieving the puppeted object from the account's end. Args: session (Session): Find puppeted object based on this session Returns: puppet (Object): The matching puppeted object, if any. """ return session.puppet if session else None def get_all_puppets(self): """ Get all currently puppeted objects. Returns: puppets (list): All puppeted objects currently controlled by this Account. """ return list(set(session.puppet for session in self.sessions.all() if session.puppet)) def __get_single_puppet(self): """ This is a legacy convenience link for use with `MULTISESSION_MODE`. Returns: puppets (Object or list): Users of `MULTISESSION_MODE` 0 or 1 will always get the first puppet back. Users of higher `MULTISESSION_MODE`s will get a list of all puppeted objects. """ puppets = self.get_all_puppets() if _MULTISESSION_MODE in (0, 1): return puppets and puppets[0] or None return puppets character = property(__get_single_puppet) puppet = property(__get_single_puppet) # utility methods @classmethod def is_banned(cls, **kwargs): """ Checks if a given username or IP is banned. Keyword Args: ip (str, optional): IP address. username (str, optional): Username. Returns: is_banned (bool): Whether either is banned or not. """ ip = kwargs.get("ip", "").strip() username = kwargs.get("username", "").lower().strip() # Check IP and/or name bans bans = ServerConfig.objects.conf("server_bans") if bans and ( any(tup[0] == username for tup in bans if username) or any(tup[2].match(ip) for tup in bans if ip and tup[2]) ): return True return False @classmethod def get_username_validators( cls, validator_config=getattr(settings, "AUTH_USERNAME_VALIDATORS", []) ): """ Retrieves and instantiates validators for usernames. Args: validator_config (list): List of dicts comprising the battery of validators to apply to a username. Returns: validators (list): List of instantiated Validator objects. """ objs = [] for validator in validator_config: try: klass = import_string(validator["NAME"]) except ImportError: msg = ( f"The module in NAME could not be imported: {validator["NAME"]}. " "Check your AUTH_USERNAME_VALIDATORS setting." ) raise ImproperlyConfigured(msg) objs.append(klass(**validator.get("OPTIONS", {}))) return objs @classmethod def authenticate(cls, username, password, ip="", **kwargs): """ Checks the given username/password against the database to see if the credentials are valid. Note that this simply checks credentials and returns a valid reference to the user-- it does not log them in! To finish the job: After calling this from a Command, associate the account with a Session: - session.sessionhandler.login(session, account) ...or after calling this from a View, associate it with an HttpRequest: - django.contrib.auth.login(account, request) Args: username (str): Username of account password (str): Password of account ip (str, optional): IP address of client Keyword Args: session (Session, optional): Session requesting authentication Returns: account (DefaultAccount, None): Account whose credentials were provided if not banned. errors (list): Error messages of any failures. """ errors = [] if ip: ip = str(ip) # See if authentication is currently being throttled if ip and LOGIN_THROTTLE.check(ip): errors.append(_("Too many login failures; please try again in a few minutes.")) # With throttle active, do not log continued hits-- it is a # waste of storage and can be abused to make your logs harder to # read and/or fill up your disk. return None, errors # Check IP and/or name bans banned = cls.is_banned(username=username, ip=ip) if banned: # this is a banned IP or name! errors.append( _( "|rYou have been banned and cannot continue from here." "\nIf you feel this ban is in error, please email an admin.|x" ) ) logger.log_sec(f"Authentication Denied (Banned): {username} (IP: {ip}).") LOGIN_THROTTLE.update(ip, "Too many sightings of banned artifact.") return None, errors # Authenticate and get Account object account = authenticate(username=username, password=password) if not account: # User-facing message errors.append(_("Username and/or password is incorrect.")) # Log auth failures while throttle is inactive logger.log_sec(f"Authentication Failure: {username} (IP: {ip}).") # Update throttle if ip: LOGIN_THROTTLE.update(ip, "Too many authentication failures.") # Try to call post-failure hook session = kwargs.get("session", None) if session: account = AccountDB.objects.get_account_from_name(username) if account: account.at_failed_login(session) return None, errors # Account successfully authenticated logger.log_sec(f"Authentication Success: {account} (IP: {ip}).") return account, errors @classmethod def normalize_username(cls, username): """ Django: Applies NFKC Unicode normalization to usernames so that visually identical characters with different Unicode code points are considered identical. (This deals with the Turkish "i" problem and similar annoyances. Only relevant if you go out of your way to allow Unicode usernames though-- Evennia accepts ASCII by default.) In this case we're simply piggybacking on this feature to apply additional normalization per Evennia's standards. """ username = super(DefaultAccount, cls).normalize_username(username) # strip excessive spaces in accountname username = re.sub(r"\s+", " ", username).strip() return username @classmethod def validate_username(cls, username): """ Checks the given username against the username validator associated with Account objects, and also checks the database to make sure it is unique. Args: username (str): Username to validate Returns: valid (bool): Whether or not the password passed validation errors (list): Error messages of any failures """ valid = [] errors = [] # Make sure we're at least using the default validator validators = cls.get_username_validators() if not validators: validators = [cls.username_validator] # Try username against all enabled validators for validator in validators: try: valid.append(not validator(username)) except ValidationError as e: valid.append(False) errors.extend(e.messages) # Disqualify if any check failed if False in valid: valid = False else: valid = True return valid, errors @classmethod def validate_password(cls, password, account=None): """ Checks the given password against the list of Django validators enabled in the server.conf file. Args: password (str): Password to validate Keyword Args: account (DefaultAccount, optional): Account object to validate the password for. Optional, but Django includes some validators to do things like making sure users aren't setting passwords to the same value as their username. If left blank, these user-specific checks are skipped. Returns: valid (bool): Whether or not the password passed validation error (ValidationError, None): Any validation error(s) raised. Multiple errors can be nested within a single object. """ valid = False error = None # Validation returns None on success; invert it and return a more sensible bool try: valid = not password_validation.validate_password(password, user=account) except ValidationError as e: error = e return valid, error def set_password(self, password, **kwargs): """ Applies the given password to the account. Logs and triggers the `at_password_change` hook. Args: password (str): Password to set. Notes: This is called by Django also when logging in; it should not be mixed up with validation, since that would mean old passwords in the database (pre validation checks) could get invalidated. """ super(DefaultAccount, self).set_password(password) logger.log_sec(f"Password successfully changed for {self}.") self.at_password_change() def create_character(self, *args, **kwargs): """ Create a character linked to this account. Args: key (str, optional): If not given, use the same name as the account. typeclass (str, optional): Typeclass to use for this character. If not given, use settings.BASE_CHARACTER_TYPECLASS. permissions (list, optional): If not given, use the account's permissions. ip (str, optiona): The client IP creating this character. Will fall back to the one stored for the account if not given. kwargs (any): Other kwargs will be used in the create_call. Returns: Object: A new character of the `character_typeclass` type. None on an error. list or None: A list of errors, or None. """ # parse inputs character_key = kwargs.pop("key", self.key) character_ip = kwargs.pop("ip", self.db.creator_ip) character_permissions = kwargs.pop("permissions", self.permissions) # Load the appropriate Character class character_typeclass = kwargs.pop("typeclass", None) character_typeclass = ( character_typeclass if character_typeclass else settings.BASE_CHARACTER_TYPECLASS ) Character = class_from_module(character_typeclass) # Create the character character, errs = Character.create( character_key, self, ip=character_ip, typeclass=character_typeclass, permissions=character_permissions, **kwargs, ) if character: # Update playable character list if character not in self.characters: self.db._playable_characters.append(character) # We need to set this to have @ic auto-connect to this character self.db._last_puppet = character return character, errs @classmethod def create(cls, *args, **kwargs): """ Creates an Account (or Account/Character pair for MULTISESSION_MODE<2) with default (or overridden) permissions and having joined them to the appropriate default channels. Keyword Args: username (str): Username of Account owner password (str): Password of Account owner email (str, optional): Email address of Account owner ip (str, optional): IP address of requesting connection guest (bool, optional): Whether or not this is to be a Guest account permissions (str, optional): Default permissions for the Account typeclass (str, optional): Typeclass to use for new Account character_typeclass (str, optional): Typeclass to use for new char when applicable. Returns: account (Account): Account if successfully created; None if not errors (list): List of error messages in string form """ account = None errors = [] username = kwargs.get("username") password = kwargs.get("password") email = kwargs.get("email", "").strip() guest = kwargs.get("guest", False) permissions = kwargs.get("permissions", settings.PERMISSION_ACCOUNT_DEFAULT) typeclass = kwargs.get("typeclass", cls) ip = kwargs.get("ip", "") if ip and CREATION_THROTTLE.check(ip): errors.append( _("You are creating too many accounts. Please log into an existing account.") ) return None, errors # Normalize username username = cls.normalize_username(username) # Validate username if not guest: valid, errs = cls.validate_username(username) if not valid: # this echoes the restrictions made by django's auth # module (except not allowing spaces, for convenience of # logging in). errors.extend(errs) return None, errors # Validate password # Have to create a dummy Account object to check username similarity valid, errs = cls.validate_password(password, account=cls(username=username)) if not valid: errors.extend(errs) return None, errors # Check IP and/or name bans banned = cls.is_banned(username=username, ip=ip) if banned: # this is a banned IP or name! string = _( "|rYou have been banned and cannot continue from here." "\nIf you feel this ban is in error, please email an admin.|x" ) errors.append(string) return None, errors # everything's ok. Create the new account. try: try: account = create.create_account( username, email, password, permissions=permissions, typeclass=typeclass ) logger.log_sec(f"Account Created: {account} (IP: {ip}).") except Exception as e: errors.append( _( "There was an error creating the Account. If this problem persists, contact an admin." ) ) logger.log_trace() return None, errors # This needs to be set so the engine knows this account is # logging in for the first time. (so it knows to call the right # hooks during login later) account.db.FIRST_LOGIN = True # Record IP address of creation, if available if ip: account.db.creator_ip = ip # join the new account to the public channel pchannel = ChannelDB.objects.get_channel(settings.DEFAULT_CHANNELS[0]["key"]) if not pchannel or not pchannel.connect(account): string = f"New account '{account.key}' could not connect to public channel!" errors.append(string) logger.log_err(string) if account and settings.MULTISESSION_MODE < 2: # Auto-create a character to go with this account character, errs = account.create_character( typeclass=kwargs.get("character_typeclass") ) if errs: errors.extend(errs) except Exception: # We are in the middle between logged in and -not, so we have # to handle tracebacks ourselves at this point. If we don't, # we won't see any errors at all. errors.append(_("An error occurred. Please e-mail an admin if the problem persists.")) logger.log_trace() # Update the throttle to indicate a new account was created from this IP if ip and not guest: CREATION_THROTTLE.update(ip, "Too many accounts being created.") SIGNAL_ACCOUNT_POST_CREATE.send(sender=account, ip=ip) return account, errors def delete(self, *args, **kwargs): """ Deletes the account permanently. Notes: `*args` and `**kwargs` are passed on to the base delete mechanism (these are usually not used). """ for session in self.sessions.all(): # unpuppeting all objects and disconnecting the user, if any # sessions remain (should usually be handled from the # deleting command) try: self.unpuppet_object(session) except RuntimeError: # no puppet to disconnect from pass session.sessionhandler.disconnect(session, reason=_("Account being deleted.")) self.scripts.stop() self.attributes.clear() self.nicks.clear() self.aliases.clear() super().delete(*args, **kwargs) # methods inherited from database model def msg(self, text=None, from_obj=None, session=None, options=None, **kwargs): """ Evennia -> User This is the main route for sending data back to the user from the server. Args: text (str or tuple, optional): The message to send. This is treated internally like any send-command, so its value can be a tuple if sending multiple arguments to the `text` oob command. from_obj (Object or Account or list, optional): Object sending. If given, its at_msg_send() hook will be called. If iterable, call on all entities. session (Session or list, optional): Session object or a list of Sessions to receive this send. If given, overrules the default send behavior for the current MULTISESSION_MODE. options (list): Protocol-specific options. Passed on to the protocol. Keyword Args: any (dict): All other keywords are passed on to the protocol. """ if from_obj: # call hook for obj in make_iter(from_obj): try: obj.at_msg_send(text=text, to_obj=self, **kwargs) except Exception: # this may not be assigned. logger.log_trace() try: if not self.at_msg_receive(text=text, **kwargs): # abort message to this account return except Exception: # this may not be assigned. pass kwargs["options"] = options if text is not None: if not (isinstance(text, str) or isinstance(text, tuple)): # sanitize text before sending across the wire try: text = to_str(text) except Exception: text = repr(text) kwargs["text"] = text # session relay sessions = make_iter(session) if session else self.sessions.all() for session in sessions: session.data_out(**kwargs) def execute_cmd(self, raw_string, session=None, **kwargs): """ Do something as this account. This method is never called normally, but only when the account object itself is supposed to execute the command. It takes account nicks into account, but not nicks of eventual puppets. Args: raw_string (str): Raw command input coming from the command line. session (Session, optional): The session to be responsible for the command-send Keyword Args: kwargs (any): Other keyword arguments will be added to the found command object instance as variables before it executes. This is unused by default Evennia but may be used to set flags and change operating paramaters for commands at run-time. """ raw_string = self.nicks.nickreplace( raw_string, categories=("inputline", "channel"), include_account=False ) if not session and _MULTISESSION_MODE in (0, 1): # for these modes we use the first/only session sessions = self.sessions.get() session = sessions[0] if sessions else None return cmdhandler.cmdhandler( self, raw_string, callertype="account", session=session, **kwargs ) def search( self, searchdata, return_puppet=False, search_object=False, typeclass=None, nofound_string=None, multimatch_string=None, use_nicks=True, quiet=False, **kwargs, ): """ This is similar to `DefaultObject.search` but defaults to searching for Accounts only. Args: searchdata (str or int): Search criterion, the Account's key or dbref to search for. return_puppet (bool, optional): Instructs the method to return matches as the object the Account controls rather than the Account itself (or None) if nothing is puppeted). search_object (bool, optional): Search for Objects instead of Accounts. This is used by e.g. the @examine command when wanting to examine Objects while OOC. typeclass (Account typeclass, optional): Limit the search only to this particular typeclass. This can be used to limit to specific account typeclasses or to limit the search to a particular Object typeclass if `search_object` is True. nofound_string (str, optional): A one-time error message to echo if `searchdata` leads to no matches. If not given, will fall back to the default handler. multimatch_string (str, optional): A one-time error message to echo if `searchdata` leads to multiple matches. If not given, will fall back to the default handler. use_nicks (bool, optional): Use account-level nick replacement. quiet (bool, optional): If set, will not show any error to the user, and will also lead to returning a list of matches. Return: match (Account, Object or None): A single Account or Object match. list: If `quiet=True` this is a list of 0, 1 or more Account or Object matches. Notes: Extra keywords are ignored, but are allowed in call in order to make API more consistent with objects.objects.DefaultObject.search. """ # handle me, self and *me, *self if isinstance(searchdata, str): # handle wrapping of common terms if searchdata.lower() in ("me", "*me", "self", "*self"): return self searchdata = self.nicks.nickreplace( searchdata, categories=("account",), include_account=False ) if search_object: matches = ObjectDB.objects.object_search(searchdata, typeclass=typeclass) else: matches = AccountDB.objects.account_search(searchdata, typeclass=typeclass) if quiet: matches = list(matches) if return_puppet: matches = [match.puppet for match in matches] else: matches = _AT_SEARCH_RESULT( matches, self, query=searchdata, nofound_string=nofound_string, multimatch_string=multimatch_string, ) if matches and return_puppet: try: matches = matches.puppet except AttributeError: return None return matches def access( self, accessing_obj, access_type="read", default=False, no_superuser_bypass=False, **kwargs ): """ Determines if another object has permission to access this object in whatever way. Args: accessing_obj (Object): Object trying to access this one. access_type (str, optional): Type of access sought. default (bool, optional): What to return if no lock of access_type was found no_superuser_bypass (bool, optional): Turn off superuser lock bypassing. Be careful with this one. Keyword Args: kwargs (any): Passed to the at_access hook along with the result. Returns: result (bool): Result of access check. """ result = super().access( accessing_obj, access_type=access_type, default=default, no_superuser_bypass=no_superuser_bypass, ) self.at_access(result, accessing_obj, access_type, **kwargs) return result @property def idle_time(self): """ Returns the idle time of the least idle session in seconds. If no sessions are connected it returns nothing. """ idle = [session.cmd_last_visible for session in self.sessions.all()] if idle: return time.time() - float(max(idle)) return None @property def connection_time(self): """ Returns the maximum connection time of all connected sessions in seconds. Returns nothing if there are no sessions. """ conn = [session.conn_time for session in self.sessions.all()] if conn: return time.time() - float(min(conn)) return None # account hooks def basetype_setup(self): """ This sets up the basic properties for an account. Overload this with at_account_creation rather than changing this method. """ # A basic security setup lockstring = ( "examine:perm(Admin);edit:perm(Admin);" "delete:perm(Admin);boot:perm(Admin);msg:all();" "noidletimeout:perm(Builder) or perm(noidletimeout)" ) self.locks.add(lockstring) # The ooc account cmdset self.cmdset.add_default(_CMDSET_ACCOUNT, permanent=True) def at_account_creation(self): """ This is called once, the very first time the account is created (i.e. first time they register with the game). It's a good place to store attributes all accounts should have, like configuration values etc. """ # set an (empty) attribute holding the characters this account has lockstring = "attrread:perm(Admins);attredit:perm(Admins);" "attrcreate:perm(Admins);" self.attributes.add("_playable_characters", [], lockstring=lockstring) self.attributes.add("_saved_protocol_flags", {}, lockstring=lockstring) def at_init(self): """ This is always called whenever this object is initiated -- that is, whenever it its typeclass is cached from memory. This happens on-demand first time the object is used or activated in some way after being created but also after each server restart or reload. In the case of account objects, this usually happens the moment the account logs in or reconnects after a reload. """ pass # Note that the hooks below also exist in the character object's # typeclass. You can often ignore these and rely on the character # ones instead, unless you are implementing a multi-character game # and have some things that should be done regardless of which # character is currently connected to this account. def at_first_save(self): """ This is a generic hook called by Evennia when this object is saved to the database the very first time. You generally don't override this method but the hooks called by it. """ self.basetype_setup() self.at_account_creation() permissions = [settings.PERMISSION_ACCOUNT_DEFAULT] if hasattr(self, "_createdict"): # this will only be set if the utils.create_account # function was used to create the object. cdict = self._createdict updates = [] if not cdict.get("key"): if not self.db_key: self.db_key = f"#{self.dbid}" updates.append("db_key") elif self.key != cdict.get("key"): updates.append("db_key") self.db_key = cdict["key"] if updates: self.save(update_fields=updates) if cdict.get("locks"): self.locks.add(cdict["locks"]) if cdict.get("permissions"): permissions = cdict["permissions"] if cdict.get("tags"): # this should be a list of tags, tuples (key, category) or (key, category, data) self.tags.batch_add(*cdict["tags"]) if cdict.get("attributes"): # this should be tuples (key, val, ...) self.attributes.batch_add(*cdict["attributes"]) if cdict.get("nattributes"): # this should be a dict of nattrname:value for key, value in cdict["nattributes"]: self.nattributes.add(key, value) del self._createdict self.permissions.batch_add(*permissions) def at_access(self, result, accessing_obj, access_type, **kwargs): """ This is triggered after an access-call on this Account has completed. Args: result (bool): The result of the access check. accessing_obj (any): The object requesting the access check. access_type (str): The type of access checked. Keyword Args: kwargs (any): These are passed on from the access check and can be used to relay custom instructions from the check mechanism. Notes: This method cannot affect the result of the lock check and its return value is not used in any way. It can be used e.g. to customize error messages in a central location or create other effects based on the access result. """ pass def at_cmdset_get(self, **kwargs): """ Called just *before* cmdsets on this account are requested by the command handler. The cmdsets are available as `self.cmdset`. If changes need to be done on the fly to the cmdset before passing them on to the cmdhandler, this is the place to do it. This is called also if the account currently have no cmdsets. kwargs are usually not used unless the cmdset is generated dynamically. """ pass def at_first_login(self, **kwargs): """ Called the very first time this account logs into the game. Note that this is called *before* at_pre_login, so no session is established and usually no character is yet assigned at this point. This hook is intended for account-specific setup like configurations. Args: **kwargs (dict): Arbitrary, optional arguments for users overriding the call (unused by default). """ pass def at_password_change(self, **kwargs): """ Called after a successful password set/modify. Args: **kwargs (dict): Arbitrary, optional arguments for users overriding the call (unused by default). """ pass def at_pre_login(self, **kwargs): """ Called every time the user logs in, just before the actual login-state is set. Args: **kwargs (dict): Arbitrary, optional arguments for users overriding the call (unused by default). """ pass def _send_to_connect_channel(self, message): """ Helper method for loading and sending to the comm channel dedicated to connection messages. Args: message (str): A message to send to the connect channel. """ global _MUDINFO_CHANNEL if not _MUDINFO_CHANNEL: try: _MUDINFO_CHANNEL = ChannelDB.objects.filter(db_key=settings.CHANNEL_MUDINFO["key"])[ 0 ] except Exception: logger.log_trace() if settings.USE_TZ: now = timezone.localtime() else: now = timezone.now() now = "%02i-%02i-%02i(%02i:%02i)" % (now.year, now.month, now.day, now.hour, now.minute) if _MUDINFO_CHANNEL: _MUDINFO_CHANNEL.tempmsg(f"[{_MUDINFO_CHANNEL.key}, {now}]: {message}") else: logger.log_info(f"[{now}]: {message}") def at_post_login(self, session=None, **kwargs): """ Called at the end of the login process, just before letting the account loose. Args: session (Session, optional): Session logging in, if any. **kwargs (dict): Arbitrary, optional arguments for users overriding the call (unused by default). Notes: This is called *before* an eventual Character's `at_post_login` hook. By default it is used to set up auto-puppeting based on `MULTISESSION_MODE`. """ # if we have saved protocol flags on ourselves, load them here. protocol_flags = self.attributes.get("_saved_protocol_flags", {}) if session and protocol_flags: session.update_flags(**protocol_flags) # inform the client that we logged in through an OOB message if session: session.msg(logged_in={}) self._send_to_connect_channel(_("|G{key} connected|n").format(key=self.key)) if _MULTISESSION_MODE == 0: # in this mode we should have only one character available. We # try to auto-connect to our last conneted object, if any try: self.puppet_object(session, self.db._last_puppet) except RuntimeError: self.msg(_("The Character does not exist.")) return elif _MULTISESSION_MODE == 1: # in this mode all sessions connect to the same puppet. try: self.puppet_object(session, self.db._last_puppet) except RuntimeError: self.msg(_("The Character does not exist.")) return elif _MULTISESSION_MODE in (2, 3): # In this mode we by default end up at a character selection # screen. We execute look on the account. # we make sure to clean up the _playable_characters list in case # any was deleted in the interim. self.db._playable_characters = [char for char in self.db._playable_characters if char] self.msg( self.at_look(target=self.db._playable_characters, session=session), session=session ) def at_failed_login(self, session, **kwargs): """ Called by the login process if a user account is targeted correctly but provided with an invalid password. By default it does nothing, but exists to be overriden. Args: session (session): Session logging in. **kwargs (dict): Arbitrary, optional arguments for users overriding the call (unused by default). """ pass def at_disconnect(self, reason=None, **kwargs): """ Called just before user is disconnected. Args: reason (str, optional): The reason given for the disconnect, (echoed to the connection channel by default). **kwargs (dict): Arbitrary, optional arguments for users overriding the call (unused by default). """ reason = f" ({reason if reason else ""})" self._send_to_connect_channel( _("|R{key} disconnected{reason}|n").format(key=self.key, reason=reason) ) def at_post_disconnect(self, **kwargs): """ This is called *after* disconnection is complete. No messages can be relayed to the account from here. After this call, the account should not be accessed any more, making this a good spot for deleting it (in the case of a guest account account, for example). Args: **kwargs (dict): Arbitrary, optional arguments for users overriding the call (unused by default). """ pass def at_msg_receive(self, text=None, from_obj=None, **kwargs): """ This hook is called whenever someone sends a message to this object using the `msg` method. Note that from_obj may be None if the sender did not include itself as an argument to the obj.msg() call - so you have to check for this. . Consider this a pre-processing method before msg is passed on to the user session. If this method returns False, the msg will not be passed on. Args: text (str, optional): The message received. from_obj (any, optional): The object sending the message. Keyword Args: This includes any keywords sent to the `msg` method. Returns: receive (bool): If this message should be received. Notes: If this method returns False, the `msg` operation will abort without sending the message. """ return True def at_msg_send(self, text=None, to_obj=None, **kwargs): """ This is a hook that is called when *this* object sends a message to another object with `obj.msg(text, to_obj=obj)`. Args: text (str, optional): Text to send. to_obj (any, optional): The object to send to. Keyword Args: Keywords passed from msg() Notes: Since this method is executed by `from_obj`, if no `from_obj` was passed to `DefaultCharacter.msg` this hook will never get called. """ pass def at_server_reload(self): """ This hook is called whenever the server is shutting down for restart/reboot. If you want to, for example, save non-persistent properties across a restart, this is the place to do it. """ pass def at_server_shutdown(self): """ This hook is called whenever the server is shutting down fully (i.e. not for a restart). """ pass def at_look(self, target=None, session=None, **kwargs): """ Called when this object executes a look. It allows to customize just what this means. Args: target (Object or list, optional): An object or a list objects to inspect. session (Session, optional): The session doing this look. **kwargs (dict): Arbitrary, optional arguments for users overriding the call (unused by default). Returns: look_string (str): A prepared look string, ready to send off to any recipient (usually to ourselves) """ if target and not is_iter(target): # single target - just show it if hasattr(target, "return_appearance"): return target.return_appearance(self) else: return _("{target} has no in-game appearance.").format(target=target) else: # list of targets - make list to disconnect from db characters = list(tar for tar in target if tar) if target else [] sessions = self.sessions.all() if not sessions: # no sessions, nothing to report return "" is_su = self.is_superuser # text shown when looking in the ooc area result = [f"Account |g{self.key}|n (you are Out-of-Character)"] nsess = len(sessions) result.append( nsess == 1 and "\n\n|wConnected session:|n" or f"\n\n|wConnected sessions ({nsess}):|n" ) for isess, sess in enumerate(sessions): csessid = sess.sessid addr = "%s (%s)" % ( sess.protocol_key, isinstance(sess.address, tuple) and str(sess.address[0]) or str(sess.address), ) result.append( "\n %s %s" % ( session and session.sessid == csessid and "|w* %s|n" % (isess + 1) or " %s" % (isess + 1), addr, ) ) result.append("\n\n |whelp|n - more commands") result.append("\n |wooc <Text>|n - talk on public channel") charmax = _MAX_NR_CHARACTERS if is_su or len(characters) < charmax: if not characters: result.append( _( "\n\n You don't have any characters yet. See |whelp @charcreate|n for creating one." ) ) else: result.append("\n |w@charcreate <name> [=description]|n - create new character") result.append( "\n |w@chardelete <name>|n - delete a character (cannot be undone!)" ) if characters: string_s_ending = len(characters) > 1 and "s" or "" result.append("\n |w@ic <character>|n - enter the game (|w@ooc|n to get back here)") if is_su: result.append( f"\n\nAvailable character{string_s_ending} ({len(characters)}/unlimited):" ) else: result.append( "\n\nAvailable character%s%s:" % ( string_s_ending, charmax > 1 and " (%i/%i)" % (len(characters), charmax) or "", ) ) for char in characters: csessions = char.sessions.all() if csessions: for sess in csessions: # character is already puppeted sid = sess in sessions and sessions.index(sess) + 1 if sess and sid: result.append( f"\n - |G{char.key}|n [{", ".join(char.permissions.all())}] (played by you in session {sid})" ) else: result.append( f"\n - |R{char.key}|n [{", ".join(char.permissions.all())}] (played by someone else)" ) else: # character is "free to puppet" result.append(f"\n - {char.key} [{", ".join(char.permissions.all())}]") look_string = ("-" * 68) + "\n" + "".join(result) + "\n" + ("-" * 68) return look_string class DefaultGuest(DefaultAccount): """ This class is used for guest logins. Unlike Accounts, Guests and their characters are deleted after disconnection. """ @classmethod def create(cls, **kwargs): """ Forwards request to cls.authenticate(); returns a DefaultGuest object if one is available for use. """ return cls.authenticate(**kwargs) @classmethod def authenticate(cls, **kwargs): """ Gets or creates a Guest account object. Keyword Args: ip (str, optional): IP address of requestor; used for ban checking, throttling and logging Returns: account (Object): Guest account object, if available errors (list): List of error messages accrued during this request. """ errors = [] account = None username = None ip = kwargs.get("ip", "").strip() # check if guests are enabled. if not settings.GUEST_ENABLED: errors.append(_("Guest accounts are not enabled on this server.")) return None, errors try: # Find an available guest name. for name in settings.GUEST_LIST: if not AccountDB.objects.filter(username__iexact=name).exists(): username = name break if not username: errors.append(_("All guest accounts are in use. Please try again later.")) if ip: LOGIN_THROTTLE.update(ip, "Too many requests for Guest access.") return None, errors else: # build a new account with the found guest username password = "%016x" % getrandbits(64) home = settings.GUEST_HOME permissions = settings.PERMISSION_GUEST_DEFAULT typeclass = settings.BASE_GUEST_TYPECLASS # Call parent class creator account, errs = super(DefaultGuest, cls).create( guest=True, username=username, password=password, permissions=permissions, typeclass=typeclass, home=home, ip=ip, ) errors.extend(errs) if not account.characters: # this can happen for multisession_mode > 1. For guests we # always auto-create a character, regardless of multi-session-mode. character, errs = account.create_character() if errs: errors.extend(errs) return account, errors except Exception as e: # We are in the middle between logged in and -not, so we have # to handle tracebacks ourselves at this point. If we don't, # we won't see any errors at all. errors.append(_("An error occurred. Please e-mail an admin if the problem persists.")) logger.log_trace() return None, errors return account, errors def at_post_login(self, session=None, **kwargs): """ In theory, guests only have one character regardless of which MULTISESSION_MODE we're in. They don't get a choice. Args: session (Session, optional): Session connecting. **kwargs (dict): Arbitrary, optional arguments for users overriding the call (unused by default). """ self._send_to_connect_channel(_("|G{key} connected|n").format(key=self.key)) self.puppet_object(session, self.db._last_puppet) def at_server_shutdown(self): """ We repeat the functionality of `at_disconnect()` here just to be on the safe side. """ super().at_server_shutdown() characters = self.db._playable_characters for character in characters: if character: character.delete() def at_post_disconnect(self, **kwargs): """ Once having disconnected, destroy the guest's characters and Args: **kwargs (dict): Arbitrary, optional arguments for users overriding the call (unused by default). """ super().at_post_disconnect() characters = self.db._playable_characters for character in characters: if character: character.delete() self.delete()
""" Typeclass for Account objects Note that this object is primarily intended to store OOC information, not game info! This object represents the actual user (not their character) and has NO actual presence in the game world (this is handled by the associated character object, so you should customize that instead for most things). """ import re import time from django.conf import settings from django.contrib.auth import authenticate, password_validation from django.core.exceptions import ImproperlyConfigured, ValidationError from django.utils import timezone from django.utils.module_loading import import_string from evennia.typeclasses.models import TypeclassBase from evennia.accounts.manager import AccountManager from evennia.accounts.models import AccountDB from evennia.objects.models import ObjectDB from evennia.comms.models import ChannelDB from evennia.commands import cmdhandler from evennia.server.models import ServerConfig from evennia.server.throttle import Throttle from evennia.utils import class_from_module, create, logger from evennia.utils.utils import lazy_property, to_str, make_iter, is_iter, variable_from_module from evennia.server.signals import ( SIGNAL_ACCOUNT_POST_CREATE, SIGNAL_OBJECT_POST_PUPPET, SIGNAL_OBJECT_POST_UNPUPPET, ) from evennia.typeclasses.attributes import NickHandler from evennia.scripts.scripthandler import ScriptHandler from evennia.commands.cmdsethandler import CmdSetHandler from evennia.utils.optionhandler import OptionHandler from django.utils.translation import gettext as _ from random import getrandbits __all__ = ("DefaultAccount",) _SESSIONS = None _AT_SEARCH_RESULT = variable_from_module(*settings.SEARCH_AT_RESULT.rsplit(".", 1)) _MULTISESSION_MODE = settings.MULTISESSION_MODE _MAX_NR_CHARACTERS = settings.MAX_NR_CHARACTERS _CMDSET_ACCOUNT = settings.CMDSET_ACCOUNT _MUDINFO_CHANNEL = None # Create throttles for too many account-creations and login attempts CREATION_THROTTLE = Throttle( limit=settings.CREATION_THROTTLE_LIMIT, timeout=settings.CREATION_THROTTLE_TIMEOUT ) LOGIN_THROTTLE = Throttle( limit=settings.LOGIN_THROTTLE_LIMIT, timeout=settings.LOGIN_THROTTLE_TIMEOUT ) class AccountSessionHandler(object): """ Manages the session(s) attached to an account. """ def __init__(self, account): """ Initializes the handler. Args: account (Account): The Account on which this handler is defined. """ self.account = account def get(self, sessid=None): """ Get the sessions linked to this object. Args: sessid (int, optional): Specify a given session by session id. Returns: sessions (list): A list of Session objects. If `sessid` is given, this is a list with one (or zero) elements. """ global _SESSIONS if not _SESSIONS: from evennia.server.sessionhandler import SESSIONS as _SESSIONS if sessid: return make_iter(_SESSIONS.session_from_account(self.account, sessid)) else: return _SESSIONS.sessions_from_account(self.account) def all(self): """ Alias to get(), returning all sessions. Returns: sessions (list): All sessions. """ return self.get() def count(self): """ Get amount of sessions connected. Returns: sesslen (int): Number of sessions handled. """ return len(self.get()) class DefaultAccount(AccountDB, metaclass=TypeclassBase): """ This is the base Typeclass for all Accounts. Accounts represent the person playing the game and tracks account info, password etc. They are OOC entities without presence in-game. An Account can connect to a Character Object in order to "enter" the game. Account Typeclass API: * Available properties (only available on initiated typeclass objects) - key (string) - name of account - name (string)- wrapper for user.username - aliases (list of strings) - aliases to the object. Will be saved to database as AliasDB entries but returned as strings. - dbref (int, read-only) - unique #id-number. Also "id" can be used. - date_created (string) - time stamp of object creation - permissions (list of strings) - list of permission strings - user (User, read-only) - django User authorization object - obj (Object) - game object controlled by account. 'character' can also be used. - sessions (list of Sessions) - sessions connected to this account - is_superuser (bool, read-only) - if the connected user is a superuser * Handlers - locks - lock-handler: use locks.add() to add new lock strings - db - attribute-handler: store/retrieve database attributes on this self.db.myattr=val, val=self.db.myattr - ndb - non-persistent attribute handler: same as db but does not create a database entry when storing data - scripts - script-handler. Add new scripts to object with scripts.add() - cmdset - cmdset-handler. Use cmdset.add() to add new cmdsets to object - nicks - nick-handler. New nicks with nicks.add(). * Helper methods - msg(text=None, from_obj=None, session=None, options=None, **kwargs) - execute_cmd(raw_string) - search(ostring, global_search=False, attribute_name=None, use_nicks=False, location=None, ignore_errors=False, account=False) - is_typeclass(typeclass, exact=False) - swap_typeclass(new_typeclass, clean_attributes=False, no_default=True) - access(accessing_obj, access_type='read', default=False, no_superuser_bypass=False) - check_permstring(permstring) * Hook methods basetype_setup() at_account_creation() > note that the following hooks are also found on Objects and are usually handled on the character level: - at_init() - at_access() - at_cmdset_get(**kwargs) - at_first_login() - at_post_login(session=None) - at_disconnect() - at_message_receive() - at_message_send() - at_server_reload() - at_server_shutdown() """ objects = AccountManager() # properties @lazy_property def cmdset(self): return CmdSetHandler(self, True) @lazy_property def scripts(self): return ScriptHandler(self) @lazy_property def nicks(self): return NickHandler(self) @lazy_property def sessions(self): return AccountSessionHandler(self) @lazy_property def options(self): return OptionHandler( self, options_dict=settings.OPTIONS_ACCOUNT_DEFAULT, savefunc=self.attributes.add, loadfunc=self.attributes.get, save_kwargs={"category": "option"}, load_kwargs={"category": "option"}, ) # Do not make this a lazy property; the web UI will not refresh it! @property def characters(self): # Get playable characters list objs = self.db._playable_characters or [] # Rebuild the list if legacy code left null values after deletion try: if None in objs: objs = [x for x in self.db._playable_characters if x] self.db._playable_characters = objs except Exception as e: logger.log_trace(e) logger.log_err(e) return objs # session-related methods def disconnect_session_from_account(self, session, reason=None): """ Access method for disconnecting a given session from the account (connection happens automatically in the sessionhandler) Args: session (Session): Session to disconnect. reason (str, optional): Eventual reason for the disconnect. """ global _SESSIONS if not _SESSIONS: from evennia.server.sessionhandler import SESSIONS as _SESSIONS _SESSIONS.disconnect(session, reason) # puppeting operations def puppet_object(self, session, obj): """ Use the given session to control (puppet) the given object (usually a Character type). Args: session (Session): session to use for puppeting obj (Object): the object to start puppeting Raises: RuntimeError: If puppeting is not possible, the `exception.msg` will contain the reason. """ # safety checks if not obj: raise RuntimeError("Object not found") if not session: raise RuntimeError("Session not found") if self.get_puppet(session) == obj: # already puppeting this object self.msg(_("You are already puppeting this object.")) return if not obj.access(self, "puppet"): # no access self.msg(_("You don't have permission to puppet '{key}'.").format(key=obj.key)) return if obj.account: # object already puppeted if obj.account == self: if obj.sessions.count(): # we may take over another of our sessions # output messages to the affected sessions if _MULTISESSION_MODE in (1, 3): txt1 = f"Sharing |c{obj.name}|n with another of your sessions." txt2 = f"|c{obj.name}|n|G is now shared from another of your sessions.|n" self.msg(txt1, session=session) self.msg(txt2, session=obj.sessions.all()) else: txt1 = f"Taking over |c{obj.name}|n from another of your sessions." txt2 = f"|c{obj.name}|n|R is now acted from another of your sessions.|n" self.msg(_(txt1), session=session) self.msg(_(txt2), session=obj.sessions.all()) self.unpuppet_object(obj.sessions.get()) elif obj.account.is_connected: # controlled by another account self.msg(_("|c{key}|R is already puppeted by another Account.").format(key=obj.key)) return # do the puppeting if session.puppet: # cleanly unpuppet eventual previous object puppeted by this session self.unpuppet_object(session) # if we get to this point the character is ready to puppet or it # was left with a lingering account/session reference from an unclean # server kill or similar obj.at_pre_puppet(self, session=session) # do the connection obj.sessions.add(session) obj.account = self session.puid = obj.id session.puppet = obj # validate/start persistent scripts on object obj.scripts.validate() # re-cache locks to make sure superuser bypass is updated obj.locks.cache_lock_bypass(obj) # final hook obj.at_post_puppet() SIGNAL_OBJECT_POST_PUPPET.send(sender=obj, account=self, session=session) def unpuppet_object(self, session): """ Disengage control over an object. Args: session (Session or list): The session or a list of sessions to disengage from their puppets. Raises: RuntimeError With message about error. """ for session in make_iter(session): obj = session.puppet if obj: # do the disconnect, but only if we are the last session to puppet obj.at_pre_unpuppet() obj.sessions.remove(session) if not obj.sessions.count(): del obj.account obj.at_post_unpuppet(self, session=session) SIGNAL_OBJECT_POST_UNPUPPET.send(sender=obj, session=session, account=self) # Just to be sure we're always clear. session.puppet = None session.puid = None def unpuppet_all(self): """ Disconnect all puppets. This is called by server before a reset/shutdown. """ self.unpuppet_object(self.sessions.all()) def get_puppet(self, session): """ Get an object puppeted by this session through this account. This is the main method for retrieving the puppeted object from the account's end. Args: session (Session): Find puppeted object based on this session Returns: puppet (Object): The matching puppeted object, if any. """ return session.puppet if session else None def get_all_puppets(self): """ Get all currently puppeted objects. Returns: puppets (list): All puppeted objects currently controlled by this Account. """ return list(set(session.puppet for session in self.sessions.all() if session.puppet)) def __get_single_puppet(self): """ This is a legacy convenience link for use with `MULTISESSION_MODE`. Returns: puppets (Object or list): Users of `MULTISESSION_MODE` 0 or 1 will always get the first puppet back. Users of higher `MULTISESSION_MODE`s will get a list of all puppeted objects. """ puppets = self.get_all_puppets() if _MULTISESSION_MODE in (0, 1): return puppets and puppets[0] or None return puppets character = property(__get_single_puppet) puppet = property(__get_single_puppet) # utility methods @classmethod def is_banned(cls, **kwargs): """ Checks if a given username or IP is banned. Keyword Args: ip (str, optional): IP address. username (str, optional): Username. Returns: is_banned (bool): Whether either is banned or not. """ ip = kwargs.get("ip", "").strip() username = kwargs.get("username", "").lower().strip() # Check IP and/or name bans bans = ServerConfig.objects.conf("server_bans") if bans and ( any(tup[0] == username for tup in bans if username) or any(tup[2].match(ip) for tup in bans if ip and tup[2]) ): return True return False @classmethod def get_username_validators( cls, validator_config=getattr(settings, "AUTH_USERNAME_VALIDATORS", []) ): """ Retrieves and instantiates validators for usernames. Args: validator_config (list): List of dicts comprising the battery of validators to apply to a username. Returns: validators (list): List of instantiated Validator objects. """ objs = [] for validator in validator_config: try: klass = import_string(validator["NAME"]) except ImportError: msg = ( f"The module in NAME could not be imported: {validator['NAME']}. " "Check your AUTH_USERNAME_VALIDATORS setting." ) raise ImproperlyConfigured(msg) objs.append(klass(**validator.get("OPTIONS", {}))) return objs @classmethod def authenticate(cls, username, password, ip="", **kwargs): """ Checks the given username/password against the database to see if the credentials are valid. Note that this simply checks credentials and returns a valid reference to the user-- it does not log them in! To finish the job: After calling this from a Command, associate the account with a Session: - session.sessionhandler.login(session, account) ...or after calling this from a View, associate it with an HttpRequest: - django.contrib.auth.login(account, request) Args: username (str): Username of account password (str): Password of account ip (str, optional): IP address of client Keyword Args: session (Session, optional): Session requesting authentication Returns: account (DefaultAccount, None): Account whose credentials were provided if not banned. errors (list): Error messages of any failures. """ errors = [] if ip: ip = str(ip) # See if authentication is currently being throttled if ip and LOGIN_THROTTLE.check(ip): errors.append(_("Too many login failures; please try again in a few minutes.")) # With throttle active, do not log continued hits-- it is a # waste of storage and can be abused to make your logs harder to # read and/or fill up your disk. return None, errors # Check IP and/or name bans banned = cls.is_banned(username=username, ip=ip) if banned: # this is a banned IP or name! errors.append( _( "|rYou have been banned and cannot continue from here." "\nIf you feel this ban is in error, please email an admin.|x" ) ) logger.log_sec(f"Authentication Denied (Banned): {username} (IP: {ip}).") LOGIN_THROTTLE.update(ip, "Too many sightings of banned artifact.") return None, errors # Authenticate and get Account object account = authenticate(username=username, password=password) if not account: # User-facing message errors.append(_("Username and/or password is incorrect.")) # Log auth failures while throttle is inactive logger.log_sec(f"Authentication Failure: {username} (IP: {ip}).") # Update throttle if ip: LOGIN_THROTTLE.update(ip, "Too many authentication failures.") # Try to call post-failure hook session = kwargs.get("session", None) if session: account = AccountDB.objects.get_account_from_name(username) if account: account.at_failed_login(session) return None, errors # Account successfully authenticated logger.log_sec(f"Authentication Success: {account} (IP: {ip}).") return account, errors @classmethod def normalize_username(cls, username): """ Django: Applies NFKC Unicode normalization to usernames so that visually identical characters with different Unicode code points are considered identical. (This deals with the Turkish "i" problem and similar annoyances. Only relevant if you go out of your way to allow Unicode usernames though-- Evennia accepts ASCII by default.) In this case we're simply piggybacking on this feature to apply additional normalization per Evennia's standards. """ username = super(DefaultAccount, cls).normalize_username(username) # strip excessive spaces in accountname username = re.sub(r"\s+", " ", username).strip() return username @classmethod def validate_username(cls, username): """ Checks the given username against the username validator associated with Account objects, and also checks the database to make sure it is unique. Args: username (str): Username to validate Returns: valid (bool): Whether or not the password passed validation errors (list): Error messages of any failures """ valid = [] errors = [] # Make sure we're at least using the default validator validators = cls.get_username_validators() if not validators: validators = [cls.username_validator] # Try username against all enabled validators for validator in validators: try: valid.append(not validator(username)) except ValidationError as e: valid.append(False) errors.extend(e.messages) # Disqualify if any check failed if False in valid: valid = False else: valid = True return valid, errors @classmethod def validate_password(cls, password, account=None): """ Checks the given password against the list of Django validators enabled in the server.conf file. Args: password (str): Password to validate Keyword Args: account (DefaultAccount, optional): Account object to validate the password for. Optional, but Django includes some validators to do things like making sure users aren't setting passwords to the same value as their username. If left blank, these user-specific checks are skipped. Returns: valid (bool): Whether or not the password passed validation error (ValidationError, None): Any validation error(s) raised. Multiple errors can be nested within a single object. """ valid = False error = None # Validation returns None on success; invert it and return a more sensible bool try: valid = not password_validation.validate_password(password, user=account) except ValidationError as e: error = e return valid, error def set_password(self, password, **kwargs): """ Applies the given password to the account. Logs and triggers the `at_password_change` hook. Args: password (str): Password to set. Notes: This is called by Django also when logging in; it should not be mixed up with validation, since that would mean old passwords in the database (pre validation checks) could get invalidated. """ super(DefaultAccount, self).set_password(password) logger.log_sec(f"Password successfully changed for {self}.") self.at_password_change() def create_character(self, *args, **kwargs): """ Create a character linked to this account. Args: key (str, optional): If not given, use the same name as the account. typeclass (str, optional): Typeclass to use for this character. If not given, use settings.BASE_CHARACTER_TYPECLASS. permissions (list, optional): If not given, use the account's permissions. ip (str, optiona): The client IP creating this character. Will fall back to the one stored for the account if not given. kwargs (any): Other kwargs will be used in the create_call. Returns: Object: A new character of the `character_typeclass` type. None on an error. list or None: A list of errors, or None. """ # parse inputs character_key = kwargs.pop("key", self.key) character_ip = kwargs.pop("ip", self.db.creator_ip) character_permissions = kwargs.pop("permissions", self.permissions) # Load the appropriate Character class character_typeclass = kwargs.pop("typeclass", None) character_typeclass = ( character_typeclass if character_typeclass else settings.BASE_CHARACTER_TYPECLASS ) Character = class_from_module(character_typeclass) # Create the character character, errs = Character.create( character_key, self, ip=character_ip, typeclass=character_typeclass, permissions=character_permissions, **kwargs, ) if character: # Update playable character list if character not in self.characters: self.db._playable_characters.append(character) # We need to set this to have @ic auto-connect to this character self.db._last_puppet = character return character, errs @classmethod def create(cls, *args, **kwargs): """ Creates an Account (or Account/Character pair for MULTISESSION_MODE<2) with default (or overridden) permissions and having joined them to the appropriate default channels. Keyword Args: username (str): Username of Account owner password (str): Password of Account owner email (str, optional): Email address of Account owner ip (str, optional): IP address of requesting connection guest (bool, optional): Whether or not this is to be a Guest account permissions (str, optional): Default permissions for the Account typeclass (str, optional): Typeclass to use for new Account character_typeclass (str, optional): Typeclass to use for new char when applicable. Returns: account (Account): Account if successfully created; None if not errors (list): List of error messages in string form """ account = None errors = [] username = kwargs.get("username") password = kwargs.get("password") email = kwargs.get("email", "").strip() guest = kwargs.get("guest", False) permissions = kwargs.get("permissions", settings.PERMISSION_ACCOUNT_DEFAULT) typeclass = kwargs.get("typeclass", cls) ip = kwargs.get("ip", "") if ip and CREATION_THROTTLE.check(ip): errors.append( _("You are creating too many accounts. Please log into an existing account.") ) return None, errors # Normalize username username = cls.normalize_username(username) # Validate username if not guest: valid, errs = cls.validate_username(username) if not valid: # this echoes the restrictions made by django's auth # module (except not allowing spaces, for convenience of # logging in). errors.extend(errs) return None, errors # Validate password # Have to create a dummy Account object to check username similarity valid, errs = cls.validate_password(password, account=cls(username=username)) if not valid: errors.extend(errs) return None, errors # Check IP and/or name bans banned = cls.is_banned(username=username, ip=ip) if banned: # this is a banned IP or name! string = _( "|rYou have been banned and cannot continue from here." "\nIf you feel this ban is in error, please email an admin.|x" ) errors.append(string) return None, errors # everything's ok. Create the new account. try: try: account = create.create_account( username, email, password, permissions=permissions, typeclass=typeclass ) logger.log_sec(f"Account Created: {account} (IP: {ip}).") except Exception as e: errors.append( _( "There was an error creating the Account. If this problem persists, contact an admin." ) ) logger.log_trace() return None, errors # This needs to be set so the engine knows this account is # logging in for the first time. (so it knows to call the right # hooks during login later) account.db.FIRST_LOGIN = True # Record IP address of creation, if available if ip: account.db.creator_ip = ip # join the new account to the public channel pchannel = ChannelDB.objects.get_channel(settings.DEFAULT_CHANNELS[0]["key"]) if not pchannel or not pchannel.connect(account): string = f"New account '{account.key}' could not connect to public channel!" errors.append(string) logger.log_err(string) if account and settings.MULTISESSION_MODE < 2: # Auto-create a character to go with this account character, errs = account.create_character( typeclass=kwargs.get("character_typeclass") ) if errs: errors.extend(errs) except Exception: # We are in the middle between logged in and -not, so we have # to handle tracebacks ourselves at this point. If we don't, # we won't see any errors at all. errors.append(_("An error occurred. Please e-mail an admin if the problem persists.")) logger.log_trace() # Update the throttle to indicate a new account was created from this IP if ip and not guest: CREATION_THROTTLE.update(ip, "Too many accounts being created.") SIGNAL_ACCOUNT_POST_CREATE.send(sender=account, ip=ip) return account, errors def delete(self, *args, **kwargs): """ Deletes the account permanently. Notes: `*args` and `**kwargs` are passed on to the base delete mechanism (these are usually not used). """ for session in self.sessions.all(): # unpuppeting all objects and disconnecting the user, if any # sessions remain (should usually be handled from the # deleting command) try: self.unpuppet_object(session) except RuntimeError: # no puppet to disconnect from pass session.sessionhandler.disconnect(session, reason=_("Account being deleted.")) self.scripts.stop() self.attributes.clear() self.nicks.clear() self.aliases.clear() super().delete(*args, **kwargs) # methods inherited from database model def msg(self, text=None, from_obj=None, session=None, options=None, **kwargs): """ Evennia -> User This is the main route for sending data back to the user from the server. Args: text (str or tuple, optional): The message to send. This is treated internally like any send-command, so its value can be a tuple if sending multiple arguments to the `text` oob command. from_obj (Object or Account or list, optional): Object sending. If given, its at_msg_send() hook will be called. If iterable, call on all entities. session (Session or list, optional): Session object or a list of Sessions to receive this send. If given, overrules the default send behavior for the current MULTISESSION_MODE. options (list): Protocol-specific options. Passed on to the protocol. Keyword Args: any (dict): All other keywords are passed on to the protocol. """ if from_obj: # call hook for obj in make_iter(from_obj): try: obj.at_msg_send(text=text, to_obj=self, **kwargs) except Exception: # this may not be assigned. logger.log_trace() try: if not self.at_msg_receive(text=text, **kwargs): # abort message to this account return except Exception: # this may not be assigned. pass kwargs["options"] = options if text is not None: if not (isinstance(text, str) or isinstance(text, tuple)): # sanitize text before sending across the wire try: text = to_str(text) except Exception: text = repr(text) kwargs["text"] = text # session relay sessions = make_iter(session) if session else self.sessions.all() for session in sessions: session.data_out(**kwargs) def execute_cmd(self, raw_string, session=None, **kwargs): """ Do something as this account. This method is never called normally, but only when the account object itself is supposed to execute the command. It takes account nicks into account, but not nicks of eventual puppets. Args: raw_string (str): Raw command input coming from the command line. session (Session, optional): The session to be responsible for the command-send Keyword Args: kwargs (any): Other keyword arguments will be added to the found command object instance as variables before it executes. This is unused by default Evennia but may be used to set flags and change operating paramaters for commands at run-time. """ raw_string = self.nicks.nickreplace( raw_string, categories=("inputline", "channel"), include_account=False ) if not session and _MULTISESSION_MODE in (0, 1): # for these modes we use the first/only session sessions = self.sessions.get() session = sessions[0] if sessions else None return cmdhandler.cmdhandler( self, raw_string, callertype="account", session=session, **kwargs ) def search( self, searchdata, return_puppet=False, search_object=False, typeclass=None, nofound_string=None, multimatch_string=None, use_nicks=True, quiet=False, **kwargs, ): """ This is similar to `DefaultObject.search` but defaults to searching for Accounts only. Args: searchdata (str or int): Search criterion, the Account's key or dbref to search for. return_puppet (bool, optional): Instructs the method to return matches as the object the Account controls rather than the Account itself (or None) if nothing is puppeted). search_object (bool, optional): Search for Objects instead of Accounts. This is used by e.g. the @examine command when wanting to examine Objects while OOC. typeclass (Account typeclass, optional): Limit the search only to this particular typeclass. This can be used to limit to specific account typeclasses or to limit the search to a particular Object typeclass if `search_object` is True. nofound_string (str, optional): A one-time error message to echo if `searchdata` leads to no matches. If not given, will fall back to the default handler. multimatch_string (str, optional): A one-time error message to echo if `searchdata` leads to multiple matches. If not given, will fall back to the default handler. use_nicks (bool, optional): Use account-level nick replacement. quiet (bool, optional): If set, will not show any error to the user, and will also lead to returning a list of matches. Return: match (Account, Object or None): A single Account or Object match. list: If `quiet=True` this is a list of 0, 1 or more Account or Object matches. Notes: Extra keywords are ignored, but are allowed in call in order to make API more consistent with objects.objects.DefaultObject.search. """ # handle me, self and *me, *self if isinstance(searchdata, str): # handle wrapping of common terms if searchdata.lower() in ("me", "*me", "self", "*self"): return self searchdata = self.nicks.nickreplace( searchdata, categories=("account",), include_account=False ) if search_object: matches = ObjectDB.objects.object_search(searchdata, typeclass=typeclass) else: matches = AccountDB.objects.account_search(searchdata, typeclass=typeclass) if quiet: matches = list(matches) if return_puppet: matches = [match.puppet for match in matches] else: matches = _AT_SEARCH_RESULT( matches, self, query=searchdata, nofound_string=nofound_string, multimatch_string=multimatch_string, ) if matches and return_puppet: try: matches = matches.puppet except AttributeError: return None return matches def access( self, accessing_obj, access_type="read", default=False, no_superuser_bypass=False, **kwargs ): """ Determines if another object has permission to access this object in whatever way. Args: accessing_obj (Object): Object trying to access this one. access_type (str, optional): Type of access sought. default (bool, optional): What to return if no lock of access_type was found no_superuser_bypass (bool, optional): Turn off superuser lock bypassing. Be careful with this one. Keyword Args: kwargs (any): Passed to the at_access hook along with the result. Returns: result (bool): Result of access check. """ result = super().access( accessing_obj, access_type=access_type, default=default, no_superuser_bypass=no_superuser_bypass, ) self.at_access(result, accessing_obj, access_type, **kwargs) return result @property def idle_time(self): """ Returns the idle time of the least idle session in seconds. If no sessions are connected it returns nothing. """ idle = [session.cmd_last_visible for session in self.sessions.all()] if idle: return time.time() - float(max(idle)) return None @property def connection_time(self): """ Returns the maximum connection time of all connected sessions in seconds. Returns nothing if there are no sessions. """ conn = [session.conn_time for session in self.sessions.all()] if conn: return time.time() - float(min(conn)) return None # account hooks def basetype_setup(self): """ This sets up the basic properties for an account. Overload this with at_account_creation rather than changing this method. """ # A basic security setup lockstring = ( "examine:perm(Admin);edit:perm(Admin);" "delete:perm(Admin);boot:perm(Admin);msg:all();" "noidletimeout:perm(Builder) or perm(noidletimeout)" ) self.locks.add(lockstring) # The ooc account cmdset self.cmdset.add_default(_CMDSET_ACCOUNT, permanent=True) def at_account_creation(self): """ This is called once, the very first time the account is created (i.e. first time they register with the game). It's a good place to store attributes all accounts should have, like configuration values etc. """ # set an (empty) attribute holding the characters this account has lockstring = "attrread:perm(Admins);attredit:perm(Admins);" "attrcreate:perm(Admins);" self.attributes.add("_playable_characters", [], lockstring=lockstring) self.attributes.add("_saved_protocol_flags", {}, lockstring=lockstring) def at_init(self): """ This is always called whenever this object is initiated -- that is, whenever it its typeclass is cached from memory. This happens on-demand first time the object is used or activated in some way after being created but also after each server restart or reload. In the case of account objects, this usually happens the moment the account logs in or reconnects after a reload. """ pass # Note that the hooks below also exist in the character object's # typeclass. You can often ignore these and rely on the character # ones instead, unless you are implementing a multi-character game # and have some things that should be done regardless of which # character is currently connected to this account. def at_first_save(self): """ This is a generic hook called by Evennia when this object is saved to the database the very first time. You generally don't override this method but the hooks called by it. """ self.basetype_setup() self.at_account_creation() permissions = [settings.PERMISSION_ACCOUNT_DEFAULT] if hasattr(self, "_createdict"): # this will only be set if the utils.create_account # function was used to create the object. cdict = self._createdict updates = [] if not cdict.get("key"): if not self.db_key: self.db_key = f"#{self.dbid}" updates.append("db_key") elif self.key != cdict.get("key"): updates.append("db_key") self.db_key = cdict["key"] if updates: self.save(update_fields=updates) if cdict.get("locks"): self.locks.add(cdict["locks"]) if cdict.get("permissions"): permissions = cdict["permissions"] if cdict.get("tags"): # this should be a list of tags, tuples (key, category) or (key, category, data) self.tags.batch_add(*cdict["tags"]) if cdict.get("attributes"): # this should be tuples (key, val, ...) self.attributes.batch_add(*cdict["attributes"]) if cdict.get("nattributes"): # this should be a dict of nattrname:value for key, value in cdict["nattributes"]: self.nattributes.add(key, value) del self._createdict self.permissions.batch_add(*permissions) def at_access(self, result, accessing_obj, access_type, **kwargs): """ This is triggered after an access-call on this Account has completed. Args: result (bool): The result of the access check. accessing_obj (any): The object requesting the access check. access_type (str): The type of access checked. Keyword Args: kwargs (any): These are passed on from the access check and can be used to relay custom instructions from the check mechanism. Notes: This method cannot affect the result of the lock check and its return value is not used in any way. It can be used e.g. to customize error messages in a central location or create other effects based on the access result. """ pass def at_cmdset_get(self, **kwargs): """ Called just *before* cmdsets on this account are requested by the command handler. The cmdsets are available as `self.cmdset`. If changes need to be done on the fly to the cmdset before passing them on to the cmdhandler, this is the place to do it. This is called also if the account currently have no cmdsets. kwargs are usually not used unless the cmdset is generated dynamically. """ pass def at_first_login(self, **kwargs): """ Called the very first time this account logs into the game. Note that this is called *before* at_pre_login, so no session is established and usually no character is yet assigned at this point. This hook is intended for account-specific setup like configurations. Args: **kwargs (dict): Arbitrary, optional arguments for users overriding the call (unused by default). """ pass def at_password_change(self, **kwargs): """ Called after a successful password set/modify. Args: **kwargs (dict): Arbitrary, optional arguments for users overriding the call (unused by default). """ pass def at_pre_login(self, **kwargs): """ Called every time the user logs in, just before the actual login-state is set. Args: **kwargs (dict): Arbitrary, optional arguments for users overriding the call (unused by default). """ pass def _send_to_connect_channel(self, message): """ Helper method for loading and sending to the comm channel dedicated to connection messages. Args: message (str): A message to send to the connect channel. """ global _MUDINFO_CHANNEL if not _MUDINFO_CHANNEL: try: _MUDINFO_CHANNEL = ChannelDB.objects.filter(db_key=settings.CHANNEL_MUDINFO["key"])[ 0 ] except Exception: logger.log_trace() if settings.USE_TZ: now = timezone.localtime() else: now = timezone.now() now = "%02i-%02i-%02i(%02i:%02i)" % (now.year, now.month, now.day, now.hour, now.minute) if _MUDINFO_CHANNEL: _MUDINFO_CHANNEL.tempmsg(f"[{_MUDINFO_CHANNEL.key}, {now}]: {message}") else: logger.log_info(f"[{now}]: {message}") def at_post_login(self, session=None, **kwargs): """ Called at the end of the login process, just before letting the account loose. Args: session (Session, optional): Session logging in, if any. **kwargs (dict): Arbitrary, optional arguments for users overriding the call (unused by default). Notes: This is called *before* an eventual Character's `at_post_login` hook. By default it is used to set up auto-puppeting based on `MULTISESSION_MODE`. """ # if we have saved protocol flags on ourselves, load them here. protocol_flags = self.attributes.get("_saved_protocol_flags", {}) if session and protocol_flags: session.update_flags(**protocol_flags) # inform the client that we logged in through an OOB message if session: session.msg(logged_in={}) self._send_to_connect_channel(_("|G{key} connected|n").format(key=self.key)) if _MULTISESSION_MODE == 0: # in this mode we should have only one character available. We # try to auto-connect to our last conneted object, if any try: self.puppet_object(session, self.db._last_puppet) except RuntimeError: self.msg(_("The Character does not exist.")) return elif _MULTISESSION_MODE == 1: # in this mode all sessions connect to the same puppet. try: self.puppet_object(session, self.db._last_puppet) except RuntimeError: self.msg(_("The Character does not exist.")) return elif _MULTISESSION_MODE in (2, 3): # In this mode we by default end up at a character selection # screen. We execute look on the account. # we make sure to clean up the _playable_characters list in case # any was deleted in the interim. self.db._playable_characters = [char for char in self.db._playable_characters if char] self.msg( self.at_look(target=self.db._playable_characters, session=session), session=session ) def at_failed_login(self, session, **kwargs): """ Called by the login process if a user account is targeted correctly but provided with an invalid password. By default it does nothing, but exists to be overriden. Args: session (session): Session logging in. **kwargs (dict): Arbitrary, optional arguments for users overriding the call (unused by default). """ pass def at_disconnect(self, reason=None, **kwargs): """ Called just before user is disconnected. Args: reason (str, optional): The reason given for the disconnect, (echoed to the connection channel by default). **kwargs (dict): Arbitrary, optional arguments for users overriding the call (unused by default). """ reason = f" ({reason if reason else ''})" self._send_to_connect_channel( _("|R{key} disconnected{reason}|n").format(key=self.key, reason=reason) ) def at_post_disconnect(self, **kwargs): """ This is called *after* disconnection is complete. No messages can be relayed to the account from here. After this call, the account should not be accessed any more, making this a good spot for deleting it (in the case of a guest account account, for example). Args: **kwargs (dict): Arbitrary, optional arguments for users overriding the call (unused by default). """ pass def at_msg_receive(self, text=None, from_obj=None, **kwargs): """ This hook is called whenever someone sends a message to this object using the `msg` method. Note that from_obj may be None if the sender did not include itself as an argument to the obj.msg() call - so you have to check for this. . Consider this a pre-processing method before msg is passed on to the user session. If this method returns False, the msg will not be passed on. Args: text (str, optional): The message received. from_obj (any, optional): The object sending the message. Keyword Args: This includes any keywords sent to the `msg` method. Returns: receive (bool): If this message should be received. Notes: If this method returns False, the `msg` operation will abort without sending the message. """ return True def at_msg_send(self, text=None, to_obj=None, **kwargs): """ This is a hook that is called when *this* object sends a message to another object with `obj.msg(text, to_obj=obj)`. Args: text (str, optional): Text to send. to_obj (any, optional): The object to send to. Keyword Args: Keywords passed from msg() Notes: Since this method is executed by `from_obj`, if no `from_obj` was passed to `DefaultCharacter.msg` this hook will never get called. """ pass def at_server_reload(self): """ This hook is called whenever the server is shutting down for restart/reboot. If you want to, for example, save non-persistent properties across a restart, this is the place to do it. """ pass def at_server_shutdown(self): """ This hook is called whenever the server is shutting down fully (i.e. not for a restart). """ pass def at_look(self, target=None, session=None, **kwargs): """ Called when this object executes a look. It allows to customize just what this means. Args: target (Object or list, optional): An object or a list objects to inspect. session (Session, optional): The session doing this look. **kwargs (dict): Arbitrary, optional arguments for users overriding the call (unused by default). Returns: look_string (str): A prepared look string, ready to send off to any recipient (usually to ourselves) """ if target and not is_iter(target): # single target - just show it if hasattr(target, "return_appearance"): return target.return_appearance(self) else: return _("{target} has no in-game appearance.").format(target=target) else: # list of targets - make list to disconnect from db characters = list(tar for tar in target if tar) if target else [] sessions = self.sessions.all() if not sessions: # no sessions, nothing to report return "" is_su = self.is_superuser # text shown when looking in the ooc area result = [f"Account |g{self.key}|n (you are Out-of-Character)"] nsess = len(sessions) result.append( nsess == 1 and "\n\n|wConnected session:|n" or f"\n\n|wConnected sessions ({nsess}):|n" ) for isess, sess in enumerate(sessions): csessid = sess.sessid addr = "%s (%s)" % ( sess.protocol_key, isinstance(sess.address, tuple) and str(sess.address[0]) or str(sess.address), ) result.append( "\n %s %s" % ( session and session.sessid == csessid and "|w* %s|n" % (isess + 1) or " %s" % (isess + 1), addr, ) ) result.append("\n\n |whelp|n - more commands") result.append("\n |wooc <Text>|n - talk on public channel") charmax = _MAX_NR_CHARACTERS if is_su or len(characters) < charmax: if not characters: result.append( _( "\n\n You don't have any characters yet. See |whelp @charcreate|n for creating one." ) ) else: result.append("\n |w@charcreate <name> [=description]|n - create new character") result.append( "\n |w@chardelete <name>|n - delete a character (cannot be undone!)" ) if characters: string_s_ending = len(characters) > 1 and "s" or "" result.append("\n |w@ic <character>|n - enter the game (|w@ooc|n to get back here)") if is_su: result.append( f"\n\nAvailable character{string_s_ending} ({len(characters)}/unlimited):" ) else: result.append( "\n\nAvailable character%s%s:" % ( string_s_ending, charmax > 1 and " (%i/%i)" % (len(characters), charmax) or "", ) ) for char in characters: csessions = char.sessions.all() if csessions: for sess in csessions: # character is already puppeted sid = sess in sessions and sessions.index(sess) + 1 if sess and sid: result.append( f"\n - |G{char.key}|n [{', '.join(char.permissions.all())}] (played by you in session {sid})" ) else: result.append( f"\n - |R{char.key}|n [{', '.join(char.permissions.all())}] (played by someone else)" ) else: # character is "free to puppet" result.append(f"\n - {char.key} [{', '.join(char.permissions.all())}]") look_string = ("-" * 68) + "\n" + "".join(result) + "\n" + ("-" * 68) return look_string class DefaultGuest(DefaultAccount): """ This class is used for guest logins. Unlike Accounts, Guests and their characters are deleted after disconnection. """ @classmethod def create(cls, **kwargs): """ Forwards request to cls.authenticate(); returns a DefaultGuest object if one is available for use. """ return cls.authenticate(**kwargs) @classmethod def authenticate(cls, **kwargs): """ Gets or creates a Guest account object. Keyword Args: ip (str, optional): IP address of requestor; used for ban checking, throttling and logging Returns: account (Object): Guest account object, if available errors (list): List of error messages accrued during this request. """ errors = [] account = None username = None ip = kwargs.get("ip", "").strip() # check if guests are enabled. if not settings.GUEST_ENABLED: errors.append(_("Guest accounts are not enabled on this server.")) return None, errors try: # Find an available guest name. for name in settings.GUEST_LIST: if not AccountDB.objects.filter(username__iexact=name).exists(): username = name break if not username: errors.append(_("All guest accounts are in use. Please try again later.")) if ip: LOGIN_THROTTLE.update(ip, "Too many requests for Guest access.") return None, errors else: # build a new account with the found guest username password = "%016x" % getrandbits(64) home = settings.GUEST_HOME permissions = settings.PERMISSION_GUEST_DEFAULT typeclass = settings.BASE_GUEST_TYPECLASS # Call parent class creator account, errs = super(DefaultGuest, cls).create( guest=True, username=username, password=password, permissions=permissions, typeclass=typeclass, home=home, ip=ip, ) errors.extend(errs) if not account.characters: # this can happen for multisession_mode > 1. For guests we # always auto-create a character, regardless of multi-session-mode. character, errs = account.create_character() if errs: errors.extend(errs) return account, errors except Exception as e: # We are in the middle between logged in and -not, so we have # to handle tracebacks ourselves at this point. If we don't, # we won't see any errors at all. errors.append(_("An error occurred. Please e-mail an admin if the problem persists.")) logger.log_trace() return None, errors return account, errors def at_post_login(self, session=None, **kwargs): """ In theory, guests only have one character regardless of which MULTISESSION_MODE we're in. They don't get a choice. Args: session (Session, optional): Session connecting. **kwargs (dict): Arbitrary, optional arguments for users overriding the call (unused by default). """ self._send_to_connect_channel(_("|G{key} connected|n").format(key=self.key)) self.puppet_object(session, self.db._last_puppet) def at_server_shutdown(self): """ We repeat the functionality of `at_disconnect()` here just to be on the safe side. """ super().at_server_shutdown() characters = self.db._playable_characters for character in characters: if character: character.delete() def at_post_disconnect(self, **kwargs): """ Once having disconnected, destroy the guest's characters and Args: **kwargs (dict): Arbitrary, optional arguments for users overriding the call (unused by default). """ super().at_post_disconnect() characters = self.db._playable_characters for character in characters: if character: character.delete() self.delete()
import enum import logging import os import re import subprocess import sys import typing as t import unicodedata from typing import TYPE_CHECKING import pynvim from gkeep.config import KEEP_FT, Config, State from gkeepapi.node import List, NodeType, Note, TopLevelNode from pynvim.api import Buffer if sys.version_info < (3, 8): from typing_extensions import Literal else: from typing import Literal if TYPE_CHECKING: from gkeep.api import KeepApi logger = logging.getLogger(__name__) NoteType = t.Union[List, Note] class NoteUrl: def __init__( self, id: t.Optional[str], title: t.Optional[str] = None, ): self.id = id or None self.title = title or None @classmethod def from_note(cls, note: TopLevelNode) -> "NoteUrl": return cls(note.id, note.title) @classmethod def from_ephemeral_bufname(cls, bufname: str) -> "NoteUrl": assert cls.is_ephemeral(bufname) id, name = bufname.split("/", 3)[2:] name = os.path.splitext(name)[0] return cls(id, name) @staticmethod def is_ephemeral(bufname: str) -> bool: return bufname.startswith("gkeep://") def filepath( self, api: "KeepApi", config: Config, note: TopLevelNode ) -> t.Optional[str]: if note.trashed or config.sync_dir is None: return None elif note.archived and not config.sync_archived_notes: return None filename = self._get_filename(api, config, note) if note.archived: assert config.archive_sync_dir is not None return os.path.join(config.archive_sync_dir, filename) else: return os.path.join(config.sync_dir, filename) def bufname(self, api: "KeepApi", config: Config, note: TopLevelNode) -> str: filepath = self.filepath(api, config, note) if filepath is not None: return filepath return self.ephemeral_bufname(config, note) def _get_filename(self, api: "KeepApi", config: Config, note: TopLevelNode) -> str: from gkeep import parser ext = parser.get_ext(config, note) if api.has_unique_title(note): return escape(f"{self.title}.{ext}") else: return escape(f"{self.title}:{self.id}.{ext}") def ephemeral_bufname( self, config: Config, note: t.Union[TopLevelNode, str] ) -> str: from gkeep import parser title = normalize_title(self.title or "") return f"gkeep://{self.id or ""}/{title or ""}.{parser.get_ext(config, note)}" def __str__(self) -> str: return f"gkeep://{self.id or ""}/{self.title or ""}" def __hash__(self) -> int: return hash(self.id) def __eq__(self, other: t.Any) -> bool: if isinstance(other, NoteUrl): return self.id == other.id return False def dispatch(vim: pynvim.Nvim, config: Config, func: str, *args: t.Any) -> None: if config.state != State.ShuttingDown: vim.async_call(vim.exec_lua, "require'gkeep'.dispatch(...)", func, *args) def echoerr(vim: pynvim.Nvim, message: str) -> None: vim.api.echo( [(message, "Error")], True, {}, ) def checkbox(checked: t.Union[bool, Literal["partial"]]) -> str: if checked == "partial": return "[-] " elif checked: return "[x] " else: return "[ ] " class NoteEnum(enum.Enum): NOTE = "note" LIST = "list" class NoteFormat(enum.Enum): NOTE = "note" LIST = "list" NEORG = "neorg" def get_type(note: TopLevelNode) -> NoteEnum: if note.type == NodeType.Note: return NoteEnum.NOTE elif note.type == NodeType.List: return NoteEnum.LIST else: raise TypeError(f"Unknown note type: {note.type}") def get_link(note: TopLevelNode) -> str: return f"https://keep.google.com/#NOTE/{note.server_id}" def escape(title: str) -> str: normalized = unicodedata.normalize("NFKC", title) # Replace all whitespace with a space character normalized = re.sub(r"\s", " ", normalized) return re.sub(r"[^\w\s\.-]", "", normalized) def normalize_title(title: str) -> str: return re.sub(r"\s", " ", title) def get_ext(filename: str) -> str: name, ext = os.path.splitext(filename) # Handle the case of an empty title if not ext: basename = os.path.basename(filename) if basename.startswith("."): ext = basename return ext.lower() def set_note_opts_and_vars(note: NoteType, bufnr: Buffer) -> None: nt = get_type(note) bufnr.vars["note_type"] = nt.value if bufnr.options["filetype"] == KEEP_FT: shiftwidth = 2 if nt == NoteEnum.NOTE else 4 bufnr.options["shiftwidth"] = shiftwidth def open_url(vim: pynvim.Nvim, url: str) -> None: cmd = None if vim.funcs.executable("open"): cmd = "open" elif vim.funcs.executable("xdg-open"): cmd = "xdg-open" else: cmd = os.getenv("BROWSER") if cmd is None: echoerr( vim, "Could not find web browser. Set the BROWSER environment variable and restart", ) else: subprocess.call([cmd, url])
import enum import logging import os import re import subprocess import sys import typing as t import unicodedata from typing import TYPE_CHECKING import pynvim from gkeep.config import KEEP_FT, Config, State from gkeepapi.node import List, NodeType, Note, TopLevelNode from pynvim.api import Buffer if sys.version_info < (3, 8): from typing_extensions import Literal else: from typing import Literal if TYPE_CHECKING: from gkeep.api import KeepApi logger = logging.getLogger(__name__) NoteType = t.Union[List, Note] class NoteUrl: def __init__( self, id: t.Optional[str], title: t.Optional[str] = None, ): self.id = id or None self.title = title or None @classmethod def from_note(cls, note: TopLevelNode) -> "NoteUrl": return cls(note.id, note.title) @classmethod def from_ephemeral_bufname(cls, bufname: str) -> "NoteUrl": assert cls.is_ephemeral(bufname) id, name = bufname.split("/", 3)[2:] name = os.path.splitext(name)[0] return cls(id, name) @staticmethod def is_ephemeral(bufname: str) -> bool: return bufname.startswith("gkeep://") def filepath( self, api: "KeepApi", config: Config, note: TopLevelNode ) -> t.Optional[str]: if note.trashed or config.sync_dir is None: return None elif note.archived and not config.sync_archived_notes: return None filename = self._get_filename(api, config, note) if note.archived: assert config.archive_sync_dir is not None return os.path.join(config.archive_sync_dir, filename) else: return os.path.join(config.sync_dir, filename) def bufname(self, api: "KeepApi", config: Config, note: TopLevelNode) -> str: filepath = self.filepath(api, config, note) if filepath is not None: return filepath return self.ephemeral_bufname(config, note) def _get_filename(self, api: "KeepApi", config: Config, note: TopLevelNode) -> str: from gkeep import parser ext = parser.get_ext(config, note) if api.has_unique_title(note): return escape(f"{self.title}.{ext}") else: return escape(f"{self.title}:{self.id}.{ext}") def ephemeral_bufname( self, config: Config, note: t.Union[TopLevelNode, str] ) -> str: from gkeep import parser title = normalize_title(self.title or "") return f"gkeep://{self.id or ''}/{title or ''}.{parser.get_ext(config, note)}" def __str__(self) -> str: return f"gkeep://{self.id or ''}/{self.title or ''}" def __hash__(self) -> int: return hash(self.id) def __eq__(self, other: t.Any) -> bool: if isinstance(other, NoteUrl): return self.id == other.id return False def dispatch(vim: pynvim.Nvim, config: Config, func: str, *args: t.Any) -> None: if config.state != State.ShuttingDown: vim.async_call(vim.exec_lua, "require'gkeep'.dispatch(...)", func, *args) def echoerr(vim: pynvim.Nvim, message: str) -> None: vim.api.echo( [(message, "Error")], True, {}, ) def checkbox(checked: t.Union[bool, Literal["partial"]]) -> str: if checked == "partial": return "[-] " elif checked: return "[x] " else: return "[ ] " class NoteEnum(enum.Enum): NOTE = "note" LIST = "list" class NoteFormat(enum.Enum): NOTE = "note" LIST = "list" NEORG = "neorg" def get_type(note: TopLevelNode) -> NoteEnum: if note.type == NodeType.Note: return NoteEnum.NOTE elif note.type == NodeType.List: return NoteEnum.LIST else: raise TypeError(f"Unknown note type: {note.type}") def get_link(note: TopLevelNode) -> str: return f"https://keep.google.com/#NOTE/{note.server_id}" def escape(title: str) -> str: normalized = unicodedata.normalize("NFKC", title) # Replace all whitespace with a space character normalized = re.sub(r"\s", " ", normalized) return re.sub(r"[^\w\s\.-]", "", normalized) def normalize_title(title: str) -> str: return re.sub(r"\s", " ", title) def get_ext(filename: str) -> str: name, ext = os.path.splitext(filename) # Handle the case of an empty title if not ext: basename = os.path.basename(filename) if basename.startswith("."): ext = basename return ext.lower() def set_note_opts_and_vars(note: NoteType, bufnr: Buffer) -> None: nt = get_type(note) bufnr.vars["note_type"] = nt.value if bufnr.options["filetype"] == KEEP_FT: shiftwidth = 2 if nt == NoteEnum.NOTE else 4 bufnr.options["shiftwidth"] = shiftwidth def open_url(vim: pynvim.Nvim, url: str) -> None: cmd = None if vim.funcs.executable("open"): cmd = "open" elif vim.funcs.executable("xdg-open"): cmd = "xdg-open" else: cmd = os.getenv("BROWSER") if cmd is None: echoerr( vim, "Could not find web browser. Set the BROWSER environment variable and restart", ) else: subprocess.call([cmd, url])
"""CrowdStrike Falcon Discover Account registration utility Leverages the FalconPy uber class to perform check, update, register and delete operations within a customer Falcon Discover environment. """ ############################################################################## # fd_accounts - Creation date - 2020.11.14 # # # # PLEASE NOTE: This solution requires the falconpy SDK, version 0.7.0+ # # This project can be accessed here: https://github.com/CrowdStrike/falconpy # # # # Modified 2021.10.13, Version 2 - Add support for all CrowdStrike clouds # # Modified 2022.03.16, Version 3 - Add support to retrieve individual # # account details via get # ############################################################################## import argparse import json # Falcon SDK - All in one uber-class try: from falconpy import APIHarness except ImportError as no_falconpy: raise SystemExit( "The CrowdStrike FalconPy library must be installed to run this utility." ) from no_falconpy # ############## FORMAT API PAYLOAD def format_api_payload(rate_limit_reqs=0, rate_limit_time=0): """Generates a properly formatted JSON payload for POST and PATCH requests.""" data = { "resources": [ { "cloudtrail_bucket_owner_id": cloudtrail_bucket_owner_id, "cloudtrail_bucket_region": cloudtrail_bucket_region, "external_id": external_id, "iam_role_arn": iam_role_arn, "id": local_account, "rate_limit_reqs": rate_limit_reqs, "rate_limit_time": rate_limit_time } ] } return data # ############## CHECK ACCOUNTS def check_account(): # pylint: disable=R0914 """Retrieves all registered accounts and checks their status.""" # Retrieve the account list account_list = falcon.command(action="QueryAWSAccounts", parameters={"limit": f"{str(QUERY_LIMIT)}"} )["body"]["resources"] # Log the results of the account query to a file if logging is enabled if log_enabled: with open('falcon-discover-accounts.json', 'w+', encoding="utf-8") as file_output: json.dump(account_list, file_output) # Create a list of our account IDs out of account_list id_items = [] for acct in account_list: id_items.append(acct["id"]) # Returns the specified value for a specific account id within account_list account_value = lambda i, v: [a[v] for a in account_list if a["id"] == i][0] # noqa: E731 q_max = 10 # VerifyAWSAccountAccess has a ID max count of 10 for index in range(0, len(id_items), q_max): sub_acct_list = id_items[index:index + q_max] temp_list = list(sub_acct_list) # Check our AWS account access against the list of accounts returned in our query access_response = falcon.command(action="VerifyAWSAccountAccess", ids=temp_list) if access_response['status_code'] == 200 or access_response['status_code'] == 409: # Loop through each ID we verified resource_list = access_response["body"]["resources"] for result in resource_list: if result["successful"]: # This account is correctly configured print(f'Account {result['id']} is ok!') else: # This account is incorrectly configured. We'll use our account_value function to # retrieve configuration values from the account list we've already ingested. account_values_to_check = { 'id': result["id"], 'iam_role_arn': account_value(result["id"], "iam_role_arn"), 'external_id': account_value(result["id"], "external_id"), 'cloudtrail_bucket_owner_id': account_value(result["id"], "cloudtrail_bucket_owner_id"), 'cloudtrail_bucket_region': account_value(result["id"], "cloudtrail_bucket_region"), } # Use the account_value function to retrieve the # access_health branch, which contains our api failure reason try: problem = account_value(result["id"], "access_health")["api"]["reason"] print(f'Account {result['id']} has a problem: {problem}') except: # noqa: E722 pylint: disable=W0702 # The above call will produce an error if we're running # check immediately after registering an account as # the access_health branch hasn't been populated yet. # Requery the API for the account_list when this happens. account_list = falcon.command(action="QueryAWSAccounts", parameters={"limit": f"{str(QUERY_LIMIT)}"} )["body"]["resources"] issue = account_value(result["id"], "access_health")["api"]["reason"] print(f'Account {result['id']} has a problem: {issue}') # Output the account details to the user to assist with troubleshooting the account print(f'Current settings {json.dumps(account_values_to_check, indent=4)}\n') for status in [status for status in (access_response["body"]["errors"] or [])]: # pylint: disable=R1721 # This account has an issue print(f'Account {status['id']} has an error: {status['message']}!') else: try: # An error has occurred print(f"Got response error code {access_response["status_code"]}") except: # noqa: E722 pylint: disable=W0702 # Handle any egregious errors that break our return error payload print(f"Got response error code {access_response["status_code"]} message {access_response["body"]}") # ############## REGISTER ACCOUNT def register_account(): """Call the API to update the requested account.""" register_response = falcon.command(action="ProvisionAWSAccounts", parameters={}, body=format_api_payload()) if register_response["status_code"] == 201: print("Successfully registered account.") else: reg_status = register_response["status_code"] reg_message = register_response["body"]["errors"][0]["message"] print(f"Registration failed with response: {reg_status} {reg_message}") # ############## UPDATE ACCOUNT def update_account(): """Call the API to update the requested account.""" update_response = falcon.command(action="UpdateAWSAccounts", body=format_api_payload()) if update_response["status_code"] == 200: print("Successfully updated account.") else: up_status = update_response["status_code"] up_message = update_response["body"]["errors"][0]["message"] print(f"Update failed with response: {up_status} {up_message}") # ############## VERIFY ACCOUNT def get_account(): """Call the API to get the requested account.""" # VerifyAWSAccountAccess(self, parameters, body, ids): get_response = falcon.command(action="GetAWSAccounts", ids=local_account) if get_response["status_code"] == 200: print(json.dumps(get_response["body"]["resources"][0], indent=4, sort_keys=True)) else: get_status = get_response["status_code"] get_message = get_response["body"]["errors"][0]["message"] print(f"Update failed with response: {get_status} {get_message}") # ############## DELETE ACCOUNT def delete_account(): """Call the API to delete the requested account, multiple IDs can be deleted by passing in a comma-delimited list """ delete_response = falcon.command(action="DeleteAWSAccounts", ids=local_account) if delete_response["status_code"] == 200: print("Successfully deleted account.") else: del_status = delete_response["status_code"] del_message = delete_response["body"]["errors"][0]["message"] print(f"Delete failed with response: {del_status} {del_message}") # ############## MAIN if __name__ == "__main__": # Configure argument parsing parser = argparse.ArgumentParser(description="Get Params to send notification to CRWD topic") # Fully optional parser.add_argument('-q', '--query_limit', help='The query limit used for check account commands', required=False) parser.add_argument('-l', '--log_enabled', help='Save results to a file?', required=False, action="store_true") # Optionally required parser.add_argument('-r', '--cloudtrail_bucket_region', help='AWS Region where the S3 bucket is hosted', required=False) parser.add_argument('-o', '--cloudtrail_bucket_owner_id', help='Account where the S3 bucket is hosted', required=False) parser.add_argument("-u", "--crowdstrike_cloud", help="US1, US2, EU, USGOV1", required=False) parser.add_argument('-a', '--local_account', help='This AWS Account', required=False) parser.add_argument('-e', '--external_id', help='External ID used to assume role in account', required=False) parser.add_argument('-i', '--iam_role_arn', help='IAM AWS IAM Role ARN that grants access to resources for Crowdstrike', required=False) # Always required parser.add_argument('-c', '--command', help='Troubleshooting action to perform options are check, update, register, delete, get ', required=True ) parser.add_argument("-f", "--falcon_client_id", help="Falcon Client ID", required=True) parser.add_argument("-s", "--falcon_client_secret", help="Falcon Client Secret", required=True) args = parser.parse_args() # ############## SET GLOBALS command = args.command # Only execute our defined commands if command.lower() in "check,update,register,delete,get".split(","): if command.lower() in "update,register".split(","): # All fields required for update and register if (args.local_account is None or args.external_id is None or args.iam_role_arn is None): parser.error(f"The {command} command requires the -r, -o, -a, -e, -i arguments to also be specified.") else: cloudtrail_bucket_region = args.cloudtrail_bucket_region cloudtrail_bucket_owner_id = args.cloudtrail_bucket_owner_id local_account = args.local_account external_id = args.external_id iam_role_arn = args.iam_role_arn elif command.lower() in ["delete", "get"]: # Delete or verify only requires the local account ID if args.local_account is None: parser.error(f"The {command} command requires the -a argument to also be specified.") else: local_account = args.local_account else: parser.error(f"The {command} command is not recognized.") # These globals exist for all requests falcon_client_id = args.falcon_client_id falcon_client_secret = args.falcon_client_secret if not args.crowdstrike_cloud: CLOUD_URL = "US1" else: CLOUD_URL = args.crowdstrike_cloud log_enabled = args.log_enabled if not args.query_limit: QUERY_LIMIT = 100 else: QUERY_LIMIT = args.query_limit # ############## MAIN ROUTINE # Connect to the API using our provided falcon client_id and client_secret try: falcon = APIHarness(client_id=falcon_client_id, client_secret=falcon_client_secret, base_url=CLOUD_URL ) except Exception as err: # noqa: E722 pylint: disable=W0703 # We can't communicate with the endpoint print(f'Unable to communicate with API {str(err)}') # Authenticate if falcon.authenticate(): try: # Execute the command by calling the named function if command.lower() == "check": check_account() if command.lower() == "update": update_account() if command.lower() == "register": register_account() if command.lower() == "delete": delete_account() if command.lower() == "get": get_account() except Exception as err: # pylint: disable=W0703 # Handle any previously unhandled errors print(f"Command failed with error: {str(err)}.") # Discard our token before we exit falcon.deauthenticate() else: # Report that authentication failed and stop processing print("Authentication Failure.")
"""CrowdStrike Falcon Discover Account registration utility Leverages the FalconPy uber class to perform check, update, register and delete operations within a customer Falcon Discover environment. """ ############################################################################## # fd_accounts - Creation date - 2020.11.14 # # # # PLEASE NOTE: This solution requires the falconpy SDK, version 0.7.0+ # # This project can be accessed here: https://github.com/CrowdStrike/falconpy # # # # Modified 2021.10.13, Version 2 - Add support for all CrowdStrike clouds # # Modified 2022.03.16, Version 3 - Add support to retrieve individual # # account details via get # ############################################################################## import argparse import json # Falcon SDK - All in one uber-class try: from falconpy import APIHarness except ImportError as no_falconpy: raise SystemExit( "The CrowdStrike FalconPy library must be installed to run this utility." ) from no_falconpy # ############## FORMAT API PAYLOAD def format_api_payload(rate_limit_reqs=0, rate_limit_time=0): """Generates a properly formatted JSON payload for POST and PATCH requests.""" data = { "resources": [ { "cloudtrail_bucket_owner_id": cloudtrail_bucket_owner_id, "cloudtrail_bucket_region": cloudtrail_bucket_region, "external_id": external_id, "iam_role_arn": iam_role_arn, "id": local_account, "rate_limit_reqs": rate_limit_reqs, "rate_limit_time": rate_limit_time } ] } return data # ############## CHECK ACCOUNTS def check_account(): # pylint: disable=R0914 """Retrieves all registered accounts and checks their status.""" # Retrieve the account list account_list = falcon.command(action="QueryAWSAccounts", parameters={"limit": f"{str(QUERY_LIMIT)}"} )["body"]["resources"] # Log the results of the account query to a file if logging is enabled if log_enabled: with open('falcon-discover-accounts.json', 'w+', encoding="utf-8") as file_output: json.dump(account_list, file_output) # Create a list of our account IDs out of account_list id_items = [] for acct in account_list: id_items.append(acct["id"]) # Returns the specified value for a specific account id within account_list account_value = lambda i, v: [a[v] for a in account_list if a["id"] == i][0] # noqa: E731 q_max = 10 # VerifyAWSAccountAccess has a ID max count of 10 for index in range(0, len(id_items), q_max): sub_acct_list = id_items[index:index + q_max] temp_list = list(sub_acct_list) # Check our AWS account access against the list of accounts returned in our query access_response = falcon.command(action="VerifyAWSAccountAccess", ids=temp_list) if access_response['status_code'] == 200 or access_response['status_code'] == 409: # Loop through each ID we verified resource_list = access_response["body"]["resources"] for result in resource_list: if result["successful"]: # This account is correctly configured print(f'Account {result["id"]} is ok!') else: # This account is incorrectly configured. We'll use our account_value function to # retrieve configuration values from the account list we've already ingested. account_values_to_check = { 'id': result["id"], 'iam_role_arn': account_value(result["id"], "iam_role_arn"), 'external_id': account_value(result["id"], "external_id"), 'cloudtrail_bucket_owner_id': account_value(result["id"], "cloudtrail_bucket_owner_id"), 'cloudtrail_bucket_region': account_value(result["id"], "cloudtrail_bucket_region"), } # Use the account_value function to retrieve the # access_health branch, which contains our api failure reason try: problem = account_value(result["id"], "access_health")["api"]["reason"] print(f'Account {result["id"]} has a problem: {problem}') except: # noqa: E722 pylint: disable=W0702 # The above call will produce an error if we're running # check immediately after registering an account as # the access_health branch hasn't been populated yet. # Requery the API for the account_list when this happens. account_list = falcon.command(action="QueryAWSAccounts", parameters={"limit": f"{str(QUERY_LIMIT)}"} )["body"]["resources"] issue = account_value(result["id"], "access_health")["api"]["reason"] print(f'Account {result["id"]} has a problem: {issue}') # Output the account details to the user to assist with troubleshooting the account print(f'Current settings {json.dumps(account_values_to_check, indent=4)}\n') for status in [status for status in (access_response["body"]["errors"] or [])]: # pylint: disable=R1721 # This account has an issue print(f'Account {status["id"]} has an error: {status["message"]}!') else: try: # An error has occurred print(f"Got response error code {access_response['status_code']}") except: # noqa: E722 pylint: disable=W0702 # Handle any egregious errors that break our return error payload print(f"Got response error code {access_response['status_code']} message {access_response['body']}") # ############## REGISTER ACCOUNT def register_account(): """Call the API to update the requested account.""" register_response = falcon.command(action="ProvisionAWSAccounts", parameters={}, body=format_api_payload()) if register_response["status_code"] == 201: print("Successfully registered account.") else: reg_status = register_response["status_code"] reg_message = register_response["body"]["errors"][0]["message"] print(f"Registration failed with response: {reg_status} {reg_message}") # ############## UPDATE ACCOUNT def update_account(): """Call the API to update the requested account.""" update_response = falcon.command(action="UpdateAWSAccounts", body=format_api_payload()) if update_response["status_code"] == 200: print("Successfully updated account.") else: up_status = update_response["status_code"] up_message = update_response["body"]["errors"][0]["message"] print(f"Update failed with response: {up_status} {up_message}") # ############## VERIFY ACCOUNT def get_account(): """Call the API to get the requested account.""" # VerifyAWSAccountAccess(self, parameters, body, ids): get_response = falcon.command(action="GetAWSAccounts", ids=local_account) if get_response["status_code"] == 200: print(json.dumps(get_response["body"]["resources"][0], indent=4, sort_keys=True)) else: get_status = get_response["status_code"] get_message = get_response["body"]["errors"][0]["message"] print(f"Update failed with response: {get_status} {get_message}") # ############## DELETE ACCOUNT def delete_account(): """Call the API to delete the requested account, multiple IDs can be deleted by passing in a comma-delimited list """ delete_response = falcon.command(action="DeleteAWSAccounts", ids=local_account) if delete_response["status_code"] == 200: print("Successfully deleted account.") else: del_status = delete_response["status_code"] del_message = delete_response["body"]["errors"][0]["message"] print(f"Delete failed with response: {del_status} {del_message}") # ############## MAIN if __name__ == "__main__": # Configure argument parsing parser = argparse.ArgumentParser(description="Get Params to send notification to CRWD topic") # Fully optional parser.add_argument('-q', '--query_limit', help='The query limit used for check account commands', required=False) parser.add_argument('-l', '--log_enabled', help='Save results to a file?', required=False, action="store_true") # Optionally required parser.add_argument('-r', '--cloudtrail_bucket_region', help='AWS Region where the S3 bucket is hosted', required=False) parser.add_argument('-o', '--cloudtrail_bucket_owner_id', help='Account where the S3 bucket is hosted', required=False) parser.add_argument("-u", "--crowdstrike_cloud", help="US1, US2, EU, USGOV1", required=False) parser.add_argument('-a', '--local_account', help='This AWS Account', required=False) parser.add_argument('-e', '--external_id', help='External ID used to assume role in account', required=False) parser.add_argument('-i', '--iam_role_arn', help='IAM AWS IAM Role ARN that grants access to resources for Crowdstrike', required=False) # Always required parser.add_argument('-c', '--command', help='Troubleshooting action to perform options are check, update, register, delete, get ', required=True ) parser.add_argument("-f", "--falcon_client_id", help="Falcon Client ID", required=True) parser.add_argument("-s", "--falcon_client_secret", help="Falcon Client Secret", required=True) args = parser.parse_args() # ############## SET GLOBALS command = args.command # Only execute our defined commands if command.lower() in "check,update,register,delete,get".split(","): if command.lower() in "update,register".split(","): # All fields required for update and register if (args.local_account is None or args.external_id is None or args.iam_role_arn is None): parser.error(f"The {command} command requires the -r, -o, -a, -e, -i arguments to also be specified.") else: cloudtrail_bucket_region = args.cloudtrail_bucket_region cloudtrail_bucket_owner_id = args.cloudtrail_bucket_owner_id local_account = args.local_account external_id = args.external_id iam_role_arn = args.iam_role_arn elif command.lower() in ["delete", "get"]: # Delete or verify only requires the local account ID if args.local_account is None: parser.error(f"The {command} command requires the -a argument to also be specified.") else: local_account = args.local_account else: parser.error(f"The {command} command is not recognized.") # These globals exist for all requests falcon_client_id = args.falcon_client_id falcon_client_secret = args.falcon_client_secret if not args.crowdstrike_cloud: CLOUD_URL = "US1" else: CLOUD_URL = args.crowdstrike_cloud log_enabled = args.log_enabled if not args.query_limit: QUERY_LIMIT = 100 else: QUERY_LIMIT = args.query_limit # ############## MAIN ROUTINE # Connect to the API using our provided falcon client_id and client_secret try: falcon = APIHarness(client_id=falcon_client_id, client_secret=falcon_client_secret, base_url=CLOUD_URL ) except Exception as err: # noqa: E722 pylint: disable=W0703 # We can't communicate with the endpoint print(f'Unable to communicate with API {str(err)}') # Authenticate if falcon.authenticate(): try: # Execute the command by calling the named function if command.lower() == "check": check_account() if command.lower() == "update": update_account() if command.lower() == "register": register_account() if command.lower() == "delete": delete_account() if command.lower() == "get": get_account() except Exception as err: # pylint: disable=W0703 # Handle any previously unhandled errors print(f"Command failed with error: {str(err)}.") # Discard our token before we exit falcon.deauthenticate() else: # Report that authentication failed and stop processing print("Authentication Failure.")
import pdb from .types import Type, Atom, Functor, Box, Diamond, Proof, T from typing import NamedTuple class Leaf(NamedTuple): atom: Atom polarity: bool index: int def __repr__(self) -> str: return f'{self.atom}({'+' if self.polarity else '-'},{self.index})' class Unary(NamedTuple): polarity: bool modality: str decoration: str content: 'Tree' def __repr__(self) -> str: return f'Unary({'+' if self.polarity else '-'}, {self.modality}{self.decoration}, {self.content})' class Binary(NamedTuple): polarity: bool left: 'Tree' right: 'Tree' def __repr__(self) -> str: return f'Binary({'+' if self.polarity else '-'}, {self.left}, {self.right})' Tree = Leaf | Unary | Binary def type_to_tree(_type: Type, polarity: bool = True, index: int = 0, step: int = 1) -> tuple[Tree, int]: match _type: case Atom(_): return Leaf(_type, polarity, index), index + step # type: ignore case Functor(argument, result): left_tree, index = type_to_tree(argument, not polarity, index, step) right_tree, index = type_to_tree(result, polarity, index, step) return Binary(polarity, left_tree, right_tree), index case Box(decoration, content): content_tree, index = type_to_tree(content, polarity, index, step) return Unary(polarity, '□', decoration, content_tree), index case Diamond(decoration, content): content_tree, index = type_to_tree(content, polarity, index, step) return Unary(polarity, '◇', decoration, content_tree), index def match_trees(left: Tree, right: Tree) -> dict[Leaf, Leaf]: match left, right: case Leaf(latom, lpolarity, _), Leaf(ratom, rpolarity, _): assert latom == ratom and lpolarity != rpolarity return {right: left} if lpolarity else {left: right} case Unary(lpolarity, lmodality, ldecoration, lcontent), Unary(rpolarity, rmodality, rdecoration, rcontent): assert lmodality == rmodality and ldecoration == rdecoration and lpolarity != rpolarity return match_trees(lcontent, rcontent) case Binary(lpolarity, lleft, lright), Binary(rpolarity, rleft, rright): assert lpolarity != rpolarity left_mapping = match_trees(lleft, rleft) right_mapping = match_trees(lright, rright) return left_mapping | right_mapping case _: raise ValueError(f'Cannot match trees: {left} and {right}') def flip_polarity(tree: Tree) -> Tree: match tree: case Leaf(atom, polarity, index): return Leaf(atom, not polarity, index) case Unary(polarity, modality, decoration, content): return Unary(not polarity, modality, decoration, flip_polarity(content)) case Binary(polarity, left, right): return Binary(not polarity, flip_polarity(left), flip_polarity(right)) def term_to_links(proof: T) -> tuple[dict[Leaf, Leaf], dict[int, Tree]]: constants, (conclusion, index), lex_trees = proof.constants(), type_to_tree(type(proof), False), {} for term in constants: formula_tree, index = type_to_tree(type(term), True, index, 1) lex_trees[term.constant] = formula_tree def f(_proof: Proof, _index: int, _vars: dict[int, Tree]) -> tuple[dict[Leaf, Leaf], Tree, int, dict[int, Tree]]: match _proof.rule: case Proof.Rule.Lexicon: return {}, lex_trees[_proof.constant], _index, _vars case Proof.Rule.Axiom: return {}, _vars.pop(_proof.variable), _index, _vars case Proof.Rule.ArrowElimination: left_links, (_, left_match, rem), _index, _vars = f(_proof.function, _index, _vars) right_links, right_match, _index, _vars = f(_proof.argument, _index, _vars) return left_links | right_links | match_trees(left_match, right_match), rem, _index, _vars case Proof.Rule.ArrowIntroduction: var_tree, _index = type_to_tree(type(_proof.abstraction), True, _index, -1) # type: ignore _vars[_proof.abstraction.variable] = var_tree _links, tree, _index, _vars = f(_proof.body, _index, _vars) return _links, Binary(tree.polarity, flip_polarity(var_tree), tree), _index, _vars case Proof.Rule.BoxElimination | Proof.Rule.DiamondElimination: _links, tree, _index, _vars = f(_proof.body, _index, _vars) return _links, tree.content, _index, _vars case Proof.Rule.BoxIntroduction: _links, tree, _index, _vars = f(_proof.body, _index, _vars) return _links, Unary(tree.polarity, '□', _proof.decoration, tree), _index, _vars case Proof.Rule.DiamondIntroduction: _links, tree, _index, _vars = f(_proof.body, _index, _vars) return _links, Unary(tree.polarity, '◇', _proof.decoration, tree), _index, _vars links, output_tree, _, _ = f(proof, -1, {}) links |= match_trees(output_tree, conclusion) def beta_norm(_links: dict[Leaf, Leaf]) -> dict[Leaf, Leaf]: detours = {(x, y) for x in _links.items() for y in _links.items() if x[0].index == y[1].index and x[1].index > 0} beta_long_links = {x for x, _ in detours} | {y for _, y in detours} beta_norm_links = {y[0]: x[1] for x, y in detours} return (beta_norm({x: y for x, y in _links.items() if (x, y) not in beta_long_links} | beta_norm_links) if beta_long_links else _links) return beta_norm(links), lex_trees def reachable_positives(tree: Tree) -> set[int]: match tree: case Leaf(_, _, index): return {index} case Unary(_, _, _, content): return reachable_positives(content) case Binary(True, _, right): return reachable_positives(right) case Binary(False, _, _): return set() case _: raise ValueError(f'{tree} must be a formula Tree') def par_trees(tree: Tree, par: bool = False) -> list[Tree]: match tree: case Leaf(_, _, _): return [tree] if par else [] case Unary(_, _, _, content): return ([tree] if par else []) + par_trees(content, False) case Binary(polarity, left, right): return ([tree] if par else []) + par_trees(left, not polarity) + par_trees(right, False) case _: raise ValueError(f'{tree} must be a formula Tree') def tree_to_type(tree: Tree) -> T: match tree: case Leaf(atom, _, _): return atom case Unary(_, '□', decoration, content): return Box(decoration, tree_to_type(content)) case Unary(_, '◇', decoration, content): return Diamond(decoration, tree_to_type(content)) case Binary(_, left, right): return Functor(tree_to_type(left), tree_to_type(right)) case _: raise ValueError(f'{tree} must be a formula Tree') def rooting_branch(container: Tree, subtree: Tree) -> Tree | None: match container: case Unary(_, _, _, content): return container if content == subtree else rooting_branch(content, subtree) case Binary(_, left, right): return (container if left == subtree or right == subtree else rooting_branch(left, subtree) or rooting_branch(right, subtree)) def links_to_term( links: dict[Leaf, Leaf], formula_assignments: dict[int, Tree]) -> T: i = -1 hypotheses = {(i := i-1): par for key in sorted(formula_assignments) for par in par_trees(formula_assignments[key])} atom_to_word = {atom_idx: w_idx for w_idx, tree in formula_assignments.items() for atom_idx in reachable_positives(tree)} atom_to_var = {atom_idx: var_idx for var_idx, tree in hypotheses.items() for atom_idx in reachable_positives(tree)} def negative_traversal(negative_tree: Tree) -> T: assert not negative_tree.polarity match negative_tree: case Leaf(_, _, _): return positive_traversal(links[negative_tree]) case Unary(_, '□', decoration, content): return Proof.box(decoration, negative_traversal(content)) case Unary(_, '◇', decoration, content): return Proof.diamond(decoration, negative_traversal(content)) case Binary(_, left, right): abstraction = tree_to_type(left).var(abs(next(k for k in hypotheses if hypotheses[k] == left))) return Proof.abstract(abstraction, negative_traversal(right)) def positive_traversal(positive_tree: Tree, grounding: tuple[int, Tree] | None = None) -> T: assert positive_tree.polarity if grounding is None: atom_idx = positive_tree.index index = atom_to_word[atom_idx] if atom_idx in atom_to_word else atom_to_var[atom_idx] container = formula_assignments[index] if index > 0 else hypotheses[index] grounding = (index, container) else: index, container = grounding if positive_tree == container: proof_type = tree_to_type(positive_tree) return proof_type.con(index) if index > 0 else proof_type.var(abs(index)) rooted_in = rooting_branch(container, positive_tree) match rooted_in: case Unary(_, '□', _, _): return Proof.unbox(positive_traversal(rooted_in, grounding)) case Unary(_, '◇', _, _): return Proof.undiamond(positive_traversal(rooted_in, grounding)) case Binary(True, left, _): return Proof.apply(positive_traversal(rooted_in, grounding), negative_traversal(left)) case Binary(False, _, right): return Proof.apply(positive_traversal(rooted_in, grounding), negative_traversal(right)) pdb.set_trace() raise NotImplementedError return negative_traversal(next(iter(leaf for leaf in links if leaf.index == 0)))
import pdb from .types import Type, Atom, Functor, Box, Diamond, Proof, T from typing import NamedTuple class Leaf(NamedTuple): atom: Atom polarity: bool index: int def __repr__(self) -> str: return f'{self.atom}({"+" if self.polarity else "-"},{self.index})' class Unary(NamedTuple): polarity: bool modality: str decoration: str content: 'Tree' def __repr__(self) -> str: return f'Unary({"+" if self.polarity else "-"}, {self.modality}{self.decoration}, {self.content})' class Binary(NamedTuple): polarity: bool left: 'Tree' right: 'Tree' def __repr__(self) -> str: return f'Binary({"+" if self.polarity else "-"}, {self.left}, {self.right})' Tree = Leaf | Unary | Binary def type_to_tree(_type: Type, polarity: bool = True, index: int = 0, step: int = 1) -> tuple[Tree, int]: match _type: case Atom(_): return Leaf(_type, polarity, index), index + step # type: ignore case Functor(argument, result): left_tree, index = type_to_tree(argument, not polarity, index, step) right_tree, index = type_to_tree(result, polarity, index, step) return Binary(polarity, left_tree, right_tree), index case Box(decoration, content): content_tree, index = type_to_tree(content, polarity, index, step) return Unary(polarity, '□', decoration, content_tree), index case Diamond(decoration, content): content_tree, index = type_to_tree(content, polarity, index, step) return Unary(polarity, '◇', decoration, content_tree), index def match_trees(left: Tree, right: Tree) -> dict[Leaf, Leaf]: match left, right: case Leaf(latom, lpolarity, _), Leaf(ratom, rpolarity, _): assert latom == ratom and lpolarity != rpolarity return {right: left} if lpolarity else {left: right} case Unary(lpolarity, lmodality, ldecoration, lcontent), Unary(rpolarity, rmodality, rdecoration, rcontent): assert lmodality == rmodality and ldecoration == rdecoration and lpolarity != rpolarity return match_trees(lcontent, rcontent) case Binary(lpolarity, lleft, lright), Binary(rpolarity, rleft, rright): assert lpolarity != rpolarity left_mapping = match_trees(lleft, rleft) right_mapping = match_trees(lright, rright) return left_mapping | right_mapping case _: raise ValueError(f'Cannot match trees: {left} and {right}') def flip_polarity(tree: Tree) -> Tree: match tree: case Leaf(atom, polarity, index): return Leaf(atom, not polarity, index) case Unary(polarity, modality, decoration, content): return Unary(not polarity, modality, decoration, flip_polarity(content)) case Binary(polarity, left, right): return Binary(not polarity, flip_polarity(left), flip_polarity(right)) def term_to_links(proof: T) -> tuple[dict[Leaf, Leaf], dict[int, Tree]]: constants, (conclusion, index), lex_trees = proof.constants(), type_to_tree(type(proof), False), {} for term in constants: formula_tree, index = type_to_tree(type(term), True, index, 1) lex_trees[term.constant] = formula_tree def f(_proof: Proof, _index: int, _vars: dict[int, Tree]) -> tuple[dict[Leaf, Leaf], Tree, int, dict[int, Tree]]: match _proof.rule: case Proof.Rule.Lexicon: return {}, lex_trees[_proof.constant], _index, _vars case Proof.Rule.Axiom: return {}, _vars.pop(_proof.variable), _index, _vars case Proof.Rule.ArrowElimination: left_links, (_, left_match, rem), _index, _vars = f(_proof.function, _index, _vars) right_links, right_match, _index, _vars = f(_proof.argument, _index, _vars) return left_links | right_links | match_trees(left_match, right_match), rem, _index, _vars case Proof.Rule.ArrowIntroduction: var_tree, _index = type_to_tree(type(_proof.abstraction), True, _index, -1) # type: ignore _vars[_proof.abstraction.variable] = var_tree _links, tree, _index, _vars = f(_proof.body, _index, _vars) return _links, Binary(tree.polarity, flip_polarity(var_tree), tree), _index, _vars case Proof.Rule.BoxElimination | Proof.Rule.DiamondElimination: _links, tree, _index, _vars = f(_proof.body, _index, _vars) return _links, tree.content, _index, _vars case Proof.Rule.BoxIntroduction: _links, tree, _index, _vars = f(_proof.body, _index, _vars) return _links, Unary(tree.polarity, '□', _proof.decoration, tree), _index, _vars case Proof.Rule.DiamondIntroduction: _links, tree, _index, _vars = f(_proof.body, _index, _vars) return _links, Unary(tree.polarity, '◇', _proof.decoration, tree), _index, _vars links, output_tree, _, _ = f(proof, -1, {}) links |= match_trees(output_tree, conclusion) def beta_norm(_links: dict[Leaf, Leaf]) -> dict[Leaf, Leaf]: detours = {(x, y) for x in _links.items() for y in _links.items() if x[0].index == y[1].index and x[1].index > 0} beta_long_links = {x for x, _ in detours} | {y for _, y in detours} beta_norm_links = {y[0]: x[1] for x, y in detours} return (beta_norm({x: y for x, y in _links.items() if (x, y) not in beta_long_links} | beta_norm_links) if beta_long_links else _links) return beta_norm(links), lex_trees def reachable_positives(tree: Tree) -> set[int]: match tree: case Leaf(_, _, index): return {index} case Unary(_, _, _, content): return reachable_positives(content) case Binary(True, _, right): return reachable_positives(right) case Binary(False, _, _): return set() case _: raise ValueError(f'{tree} must be a formula Tree') def par_trees(tree: Tree, par: bool = False) -> list[Tree]: match tree: case Leaf(_, _, _): return [tree] if par else [] case Unary(_, _, _, content): return ([tree] if par else []) + par_trees(content, False) case Binary(polarity, left, right): return ([tree] if par else []) + par_trees(left, not polarity) + par_trees(right, False) case _: raise ValueError(f'{tree} must be a formula Tree') def tree_to_type(tree: Tree) -> T: match tree: case Leaf(atom, _, _): return atom case Unary(_, '□', decoration, content): return Box(decoration, tree_to_type(content)) case Unary(_, '◇', decoration, content): return Diamond(decoration, tree_to_type(content)) case Binary(_, left, right): return Functor(tree_to_type(left), tree_to_type(right)) case _: raise ValueError(f'{tree} must be a formula Tree') def rooting_branch(container: Tree, subtree: Tree) -> Tree | None: match container: case Unary(_, _, _, content): return container if content == subtree else rooting_branch(content, subtree) case Binary(_, left, right): return (container if left == subtree or right == subtree else rooting_branch(left, subtree) or rooting_branch(right, subtree)) def links_to_term( links: dict[Leaf, Leaf], formula_assignments: dict[int, Tree]) -> T: i = -1 hypotheses = {(i := i-1): par for key in sorted(formula_assignments) for par in par_trees(formula_assignments[key])} atom_to_word = {atom_idx: w_idx for w_idx, tree in formula_assignments.items() for atom_idx in reachable_positives(tree)} atom_to_var = {atom_idx: var_idx for var_idx, tree in hypotheses.items() for atom_idx in reachable_positives(tree)} def negative_traversal(negative_tree: Tree) -> T: assert not negative_tree.polarity match negative_tree: case Leaf(_, _, _): return positive_traversal(links[negative_tree]) case Unary(_, '□', decoration, content): return Proof.box(decoration, negative_traversal(content)) case Unary(_, '◇', decoration, content): return Proof.diamond(decoration, negative_traversal(content)) case Binary(_, left, right): abstraction = tree_to_type(left).var(abs(next(k for k in hypotheses if hypotheses[k] == left))) return Proof.abstract(abstraction, negative_traversal(right)) def positive_traversal(positive_tree: Tree, grounding: tuple[int, Tree] | None = None) -> T: assert positive_tree.polarity if grounding is None: atom_idx = positive_tree.index index = atom_to_word[atom_idx] if atom_idx in atom_to_word else atom_to_var[atom_idx] container = formula_assignments[index] if index > 0 else hypotheses[index] grounding = (index, container) else: index, container = grounding if positive_tree == container: proof_type = tree_to_type(positive_tree) return proof_type.con(index) if index > 0 else proof_type.var(abs(index)) rooted_in = rooting_branch(container, positive_tree) match rooted_in: case Unary(_, '□', _, _): return Proof.unbox(positive_traversal(rooted_in, grounding)) case Unary(_, '◇', _, _): return Proof.undiamond(positive_traversal(rooted_in, grounding)) case Binary(True, left, _): return Proof.apply(positive_traversal(rooted_in, grounding), negative_traversal(left)) case Binary(False, _, right): return Proof.apply(positive_traversal(rooted_in, grounding), negative_traversal(right)) pdb.set_trace() raise NotImplementedError return negative_traversal(next(iter(leaf for leaf in links if leaf.index == 0)))
""" Module implementing a client for the v2 docker registry API. See https://docs.docker.com/registry/spec/api/ """ import asyncio import hashlib import json import logging import ssl import urllib.parse from typing import AsyncIterable, Dict, List, Optional, Tuple, Union import aiohttp from .auth import CredentialStore, DictCredentialStore from .exceptions import RegistryException from .models import ( MANIFEST_TYPE_MAP, Descriptor, Manifest, Registry, RegistryBlobRef, RegistryManifestRef, ) from .parsing import split_quote from .utils import ReleaseableAsyncContextManager, async_generator_buffer LOGGER = logging.getLogger(__name__) class AsyncRegistryClient: """ Class that holds network session and context information. """ _ACCEPT_HEADER = ",".join(MANIFEST_TYPE_MAP) + ", */*" _DEFAULT_REGISTRY = Registry( host="registry-1.docker.io", host_alias="docker.io", ) _DEFAULT_TIMEOUT = aiohttp.ClientTimeout( total=None, connect=None, sock_connect=10, sock_read=10, ) def __init__( self, *, session: Optional[aiohttp.ClientSession] = None, creds: Optional[CredentialStore] = None, timeout: Optional[aiohttp.ClientTimeout] = None, default_registry: Optional[Registry] = None, ssl_context: Optional[ssl.SSLContext] = None, ) -> None: self.custom_session = bool(session) self.session = session or aiohttp.ClientSession() self.timeout = timeout or self._DEFAULT_TIMEOUT self.default_registry = default_registry or self._DEFAULT_REGISTRY self.ssl_context = ssl_context self.access_tokens: Dict[Tuple[str, str], str] = {} self.creds = creds or DictCredentialStore({}) async def __aenter__(self) -> "AsyncRegistryClient": return self async def __aexit__(self, exc_type, exc_value, exc_traceback) -> None: if not self.custom_session: await self.session.close() async def _request( self, method: str, registry: Registry, path: str, *, headers: Optional[Dict[str, str]] = None, data: Optional[Union[str, bytes]] = None, has_host: bool = False, ): """ Make a request to a registry, applying the appropriate credentials. Returns an async context manager that yields an aiohttp response. """ # Parse URL and determine the the authentication key for any # authentication tokens. url = path if has_host else f"{registry.url}/{path}" url_data = urllib.parse.urlparse(url) path_parts = url_data.path.split("/") auth_key = (url_data.hostname or "", "/".join(path_parts[0:4])) # Lookup any basic auth credentials to supply. if not registry and url_data.hostname is None: raise ValueError("No registry or hostname provided") auth = None creds = await self.creds.get( registry.host_alias or registry.host if registry else url_data.hostname # type: ignore ) if creds is not None: auth = aiohttp.BasicAuth(creds[0], password=creds[1]) # Attempt to make the request twice. If the first attempt fails with a # 401 try to get an authentication token and then try again. first_attempt = True while True: all_headers = dict(headers or {}) all_headers["Accept"] = self._ACCEPT_HEADER basic_auth = None auth_token = self.access_tokens.get(auth_key) if auth_token is None: basic_auth = auth else: all_headers["Authorization"] = "Bearer " + auth_token acm = ReleaseableAsyncContextManager( self.session.request( method, url, auth=basic_auth, headers=all_headers, data=data, timeout=self.timeout, ssl=self.ssl_context, ) ) async with acm as response: if not first_attempt or response.status != 401: return acm.release() www_auth = response.headers.get("WWW-Authenticate", "") if not www_auth.startswith("Bearer "): raise RegistryException("Failed to make request, unauthorized") auth_parts = split_quote(www_auth[7:], "=,") auth_args = { auth_parts[i]: auth_parts[i + 2] for i in range(0, len(auth_parts) - 2, 4) } realm = auth_args.pop("realm", "") if realm is None: raise RegistryException("Expected authentication realm") query_parts = [] if service := auth_args.get("service"): query_parts.append(("service", service)) query_parts.extend( ("scope", scope) for scope in auth_args.get("scope", "").split(" ") if scope ) async with self.session.get( realm + "?" + urllib.parse.urlencode(query_parts), auth=auth, timeout=self.timeout, ssl=self.ssl_context, ) as auth_resp: if auth_resp.status != 200: raise RegistryException("Failed to generate authentication token") self.access_tokens[auth_key] = (await auth_resp.json())["access_token"] first_attempt = False async def ref_delete(self, ref: RegistryBlobRef) -> bool: """ Attempts to delete a reference from the registry. This is only supported for non-digest manifest references. Returns True if the delete succeeded. If permission is denied or the ref does not exist returns False. Other failures will raise an exception. """ registry = ref.registry or self.default_registry try: async with await self._request("DELETE", registry, ref.url) as response: if response.status in (401, 404): return False if response.status != 202: raise RegistryException("Delete failed") return True except aiohttp.ClientError as exc: raise RegistryException("failed to contact registry") from exc async def ref_lookup(self, ref: RegistryBlobRef) -> Optional[Descriptor]: """ Attempts to lookup the requested ref and return a :class:`Descriptor` representation. The descriptor includes the media type, digest, and size information of the object. If the registry returns a 404 Not Found or 401 Unauthorized this method will return None. Any other failure to retrieve metadata about the object will raise an exception. """ registry = ref.registry or self.default_registry try: async with await self._request("HEAD", registry, ref.url) as response: if response.status in (401, 404): return None if response.status != 200: print(response.status, await response.content.read()) raise RegistryException("Unexpected response from registry") # Extract digest if ref.is_digest_ref(): digest = ref.ref else: digest = response.headers.get("Docker-Content-Digest") if digest is None: raise RegistryException("No digest given by server for tag ref") # Extract media type media_type = response.headers.get("Content-Type") if media_type is None: raise RegistryException("No content type given by server") # Extract size size = response.headers.get("Content-Length") if size is None: raise RegistryException("No content length given by server") try: isize = int(size) except ValueError as exc: raise RegistryException( "Invalid content length given by server" ) from exc return Descriptor( mediaType=media_type, size=isize, digest=digest, ) except aiohttp.ClientError as exc: raise RegistryException("failed to contact registry") from exc async def ref_content_stream( self, ref: RegistryBlobRef, chunk_size: int = 2**20, ) -> AsyncIterable[bytes]: """ Stream the contents of `ref` as an async iterable of `chunk_size` bytes objects. The last chunk may be smaller than `chunk_size`. """ registry = ref.registry or self.default_registry try: async with await self._request("GET", registry, ref.url) as response: if response.status != 200: raise RegistryException( f"Unexpected response from registry HTTP {response.status}" ) cur_chunk: List[bytes] = [] cur_chunk_size = 0 async for chunk in response.content.iter_chunked(chunk_size): need = chunk_size - cur_chunk_size cur_chunk_size += len(chunk) if len(chunk) >= need: yield b"".join(cur_chunk) + chunk[:need] cur_chunk.clear() if need < len(chunk): cur_chunk.append(chunk[need:]) cur_chunk_size -= chunk_size else: cur_chunk.append(chunk) except aiohttp.ClientError as exc: raise RegistryException("failed to contact registry") from exc if cur_chunk: yield b"".join(cur_chunk) async def manifest_download(self, ref: RegistryManifestRef) -> Manifest: """ Attempt to download a manifest. """ registry = ref.registry or self.default_registry try: async with await self._request("GET", registry, ref.url) as response: if response.status != 200: raise RegistryException( f"Unexpected response from registry HTTP {response.status}" ) try: manifest_data = json.loads(await response.text(encoding="utf-8")) except ValueError as exc: raise RegistryException( "Failed decoding JSON response from registry" ) from exc except aiohttp.ClientError as exc: raise RegistryException("failed to contact registry") from exc return Manifest.parse( manifest_data, media_type=response.headers.get("Content-Type"), ) async def manifest_write( self, ref: RegistryManifestRef, manifest: Manifest ) -> None: """ Write a manifest to a registry. If `ref.ref` is empty or is a digest ref, then `ref.ref` will be ignored and the manifest will be pushed untagged using the digest of `manifest.canonical()`. """ if not ref.ref or ref.is_digest_ref(): ref = ref.copy(update=dict(ref=manifest.digest)) async with await self._request( "PUT", ref.registry or self.default_registry, ref.url, data=manifest.canonical(), headers={"Content-Type": manifest.get_media_type()}, ) as response: if response.status // 100 != 2: raise RegistryException("Failed to copy manifest") async def blob_write( self, ref: RegistryBlobRef, data: AsyncIterable[bytes] ) -> RegistryBlobRef: """ Writes a blob to the registry. The digest will be calculated automatically while uploading, ignoring `ref.ref`. A copy of `ref` with `ref.ref` set to the calculated digest will be returned. """ # Perform the blob upload flow, POST -> PATCH -> PUT registry = ref.registry or self.default_registry async with await self._request( "POST", registry, ref.upload_url(), ) as response: if response.status // 100 != 2: raise RegistryException( "Unexpected response attempting to start blob copy" ) upload_location = response.headers["Location"] hsh = hashlib.sha256() async for chunk in async_generator_buffer(data, 4): hsh.update(chunk) async with await self._request( "PATCH", registry, upload_location, data=chunk, headers={"Content-Type": "application/octet-stream"}, has_host=True, ) as response: if response.status // 100 != 2: raise RegistryException("Unexpected response writing blob data") upload_location = response.headers["Location"] digest = "sha256:" + hsh.hexdigest() async with await self._request( "PUT", registry, f"{upload_location}&digest={digest}", has_host=True, ) as response: if response.status // 100 != 2: raise RegistryException("Unexpected response ending blob copy") return ref.copy(update=dict(ref=digest)) async def registry_repos(self, registry: Optional[Registry]) -> List[str]: """ Return a list of all repos for the given registry. It is up to the registry implementation to determine what if any repo names will be returned. """ async with await self._request( "GET", registry or self.default_registry, "/v2/_catalog", ) as response: try: return (await response.json())["repositories"] except ValueError as exc: raise RegistryException("Unexpected response getting repos") from exc async def registry_repo_tags( self, registry: Optional[Registry], repo: List[str] ) -> List[str]: """ Return a list of all tags for the given repo name. """ async with await self._request( "GET", registry or self.default_registry, f"/v2/{"/".join(repo)}/tags/list", ) as response: try: return (await response.json())["tags"] except ValueError as exc: raise RegistryException( "Unexpected response getting repo tags" ) from exc async def copy_refs(self, src: RegistryBlobRef, dst: RegistryBlobRef) -> bool: """ Copy the blob src to dst. Returns True if any data was copied and False if the content already existed. """ if src.OBJECT_TYPE != dst.OBJECT_TYPE: raise ValueError("Cannot copy ref to different object type") if dst.is_digest_ref(): if src.ref != dst.ref: raise ValueError( "Cannot copy to a content address that does not match the source" ) if src == dst: LOGGER.info("skipping copy of identical refs") return False # Check if ref already exists if src.is_digest_ref(): if await self.ref_lookup(dst) is not None: LOGGER.info("Skipping copy %s -> %s - already exists", src, dst) return False if isinstance(src, RegistryManifestRef): manifest = await self.manifest_download(src) await asyncio.gather( *( self.copy_refs( RegistryManifestRef( registry=src.registry, repo=src.repo, ref=digest ), RegistryManifestRef( registry=dst.registry, repo=dst.repo, ref=digest ), ) for digest in manifest.get_manifest_dependencies() ), *( self.copy_refs( RegistryBlobRef( registry=src.registry, repo=src.repo, ref=digest ), RegistryBlobRef( registry=dst.registry, repo=dst.repo, ref=digest ), ) for digest in manifest.get_blob_dependencies() ), ) assert isinstance(dst, RegistryManifestRef) await self.manifest_write(dst, manifest) LOGGER.info("Copied manifest %s -> %s", src, dst) return True # Attempt mount if blobs come from the same registry. if src.registry == dst.registry: query_str = urllib.parse.urlencode( { "from": "/".join(src.repo), "mount": dst.ref, } ) async with await self._request( "POST", dst.registry or self.default_registry, f"v2/{"/".join(dst.repo)}/blobs/uploads/?{query_str}", ) as response: if response.status == 201: LOGGER.info( "Mounted blob %s from %s", dst.ref, "/".join(src.repo), ) return True LOGGER.warning( "mount failed with status %s, trying copy", response.status, ) raise Exception("no") await self.blob_write(dst, self.ref_content_stream(src)) LOGGER.info("Copied blob %s -> %s", src, dst) return True
""" Module implementing a client for the v2 docker registry API. See https://docs.docker.com/registry/spec/api/ """ import asyncio import hashlib import json import logging import ssl import urllib.parse from typing import AsyncIterable, Dict, List, Optional, Tuple, Union import aiohttp from .auth import CredentialStore, DictCredentialStore from .exceptions import RegistryException from .models import ( MANIFEST_TYPE_MAP, Descriptor, Manifest, Registry, RegistryBlobRef, RegistryManifestRef, ) from .parsing import split_quote from .utils import ReleaseableAsyncContextManager, async_generator_buffer LOGGER = logging.getLogger(__name__) class AsyncRegistryClient: """ Class that holds network session and context information. """ _ACCEPT_HEADER = ",".join(MANIFEST_TYPE_MAP) + ", */*" _DEFAULT_REGISTRY = Registry( host="registry-1.docker.io", host_alias="docker.io", ) _DEFAULT_TIMEOUT = aiohttp.ClientTimeout( total=None, connect=None, sock_connect=10, sock_read=10, ) def __init__( self, *, session: Optional[aiohttp.ClientSession] = None, creds: Optional[CredentialStore] = None, timeout: Optional[aiohttp.ClientTimeout] = None, default_registry: Optional[Registry] = None, ssl_context: Optional[ssl.SSLContext] = None, ) -> None: self.custom_session = bool(session) self.session = session or aiohttp.ClientSession() self.timeout = timeout or self._DEFAULT_TIMEOUT self.default_registry = default_registry or self._DEFAULT_REGISTRY self.ssl_context = ssl_context self.access_tokens: Dict[Tuple[str, str], str] = {} self.creds = creds or DictCredentialStore({}) async def __aenter__(self) -> "AsyncRegistryClient": return self async def __aexit__(self, exc_type, exc_value, exc_traceback) -> None: if not self.custom_session: await self.session.close() async def _request( self, method: str, registry: Registry, path: str, *, headers: Optional[Dict[str, str]] = None, data: Optional[Union[str, bytes]] = None, has_host: bool = False, ): """ Make a request to a registry, applying the appropriate credentials. Returns an async context manager that yields an aiohttp response. """ # Parse URL and determine the the authentication key for any # authentication tokens. url = path if has_host else f"{registry.url}/{path}" url_data = urllib.parse.urlparse(url) path_parts = url_data.path.split("/") auth_key = (url_data.hostname or "", "/".join(path_parts[0:4])) # Lookup any basic auth credentials to supply. if not registry and url_data.hostname is None: raise ValueError("No registry or hostname provided") auth = None creds = await self.creds.get( registry.host_alias or registry.host if registry else url_data.hostname # type: ignore ) if creds is not None: auth = aiohttp.BasicAuth(creds[0], password=creds[1]) # Attempt to make the request twice. If the first attempt fails with a # 401 try to get an authentication token and then try again. first_attempt = True while True: all_headers = dict(headers or {}) all_headers["Accept"] = self._ACCEPT_HEADER basic_auth = None auth_token = self.access_tokens.get(auth_key) if auth_token is None: basic_auth = auth else: all_headers["Authorization"] = "Bearer " + auth_token acm = ReleaseableAsyncContextManager( self.session.request( method, url, auth=basic_auth, headers=all_headers, data=data, timeout=self.timeout, ssl=self.ssl_context, ) ) async with acm as response: if not first_attempt or response.status != 401: return acm.release() www_auth = response.headers.get("WWW-Authenticate", "") if not www_auth.startswith("Bearer "): raise RegistryException("Failed to make request, unauthorized") auth_parts = split_quote(www_auth[7:], "=,") auth_args = { auth_parts[i]: auth_parts[i + 2] for i in range(0, len(auth_parts) - 2, 4) } realm = auth_args.pop("realm", "") if realm is None: raise RegistryException("Expected authentication realm") query_parts = [] if service := auth_args.get("service"): query_parts.append(("service", service)) query_parts.extend( ("scope", scope) for scope in auth_args.get("scope", "").split(" ") if scope ) async with self.session.get( realm + "?" + urllib.parse.urlencode(query_parts), auth=auth, timeout=self.timeout, ssl=self.ssl_context, ) as auth_resp: if auth_resp.status != 200: raise RegistryException("Failed to generate authentication token") self.access_tokens[auth_key] = (await auth_resp.json())["access_token"] first_attempt = False async def ref_delete(self, ref: RegistryBlobRef) -> bool: """ Attempts to delete a reference from the registry. This is only supported for non-digest manifest references. Returns True if the delete succeeded. If permission is denied or the ref does not exist returns False. Other failures will raise an exception. """ registry = ref.registry or self.default_registry try: async with await self._request("DELETE", registry, ref.url) as response: if response.status in (401, 404): return False if response.status != 202: raise RegistryException("Delete failed") return True except aiohttp.ClientError as exc: raise RegistryException("failed to contact registry") from exc async def ref_lookup(self, ref: RegistryBlobRef) -> Optional[Descriptor]: """ Attempts to lookup the requested ref and return a :class:`Descriptor` representation. The descriptor includes the media type, digest, and size information of the object. If the registry returns a 404 Not Found or 401 Unauthorized this method will return None. Any other failure to retrieve metadata about the object will raise an exception. """ registry = ref.registry or self.default_registry try: async with await self._request("HEAD", registry, ref.url) as response: if response.status in (401, 404): return None if response.status != 200: print(response.status, await response.content.read()) raise RegistryException("Unexpected response from registry") # Extract digest if ref.is_digest_ref(): digest = ref.ref else: digest = response.headers.get("Docker-Content-Digest") if digest is None: raise RegistryException("No digest given by server for tag ref") # Extract media type media_type = response.headers.get("Content-Type") if media_type is None: raise RegistryException("No content type given by server") # Extract size size = response.headers.get("Content-Length") if size is None: raise RegistryException("No content length given by server") try: isize = int(size) except ValueError as exc: raise RegistryException( "Invalid content length given by server" ) from exc return Descriptor( mediaType=media_type, size=isize, digest=digest, ) except aiohttp.ClientError as exc: raise RegistryException("failed to contact registry") from exc async def ref_content_stream( self, ref: RegistryBlobRef, chunk_size: int = 2**20, ) -> AsyncIterable[bytes]: """ Stream the contents of `ref` as an async iterable of `chunk_size` bytes objects. The last chunk may be smaller than `chunk_size`. """ registry = ref.registry or self.default_registry try: async with await self._request("GET", registry, ref.url) as response: if response.status != 200: raise RegistryException( f"Unexpected response from registry HTTP {response.status}" ) cur_chunk: List[bytes] = [] cur_chunk_size = 0 async for chunk in response.content.iter_chunked(chunk_size): need = chunk_size - cur_chunk_size cur_chunk_size += len(chunk) if len(chunk) >= need: yield b"".join(cur_chunk) + chunk[:need] cur_chunk.clear() if need < len(chunk): cur_chunk.append(chunk[need:]) cur_chunk_size -= chunk_size else: cur_chunk.append(chunk) except aiohttp.ClientError as exc: raise RegistryException("failed to contact registry") from exc if cur_chunk: yield b"".join(cur_chunk) async def manifest_download(self, ref: RegistryManifestRef) -> Manifest: """ Attempt to download a manifest. """ registry = ref.registry or self.default_registry try: async with await self._request("GET", registry, ref.url) as response: if response.status != 200: raise RegistryException( f"Unexpected response from registry HTTP {response.status}" ) try: manifest_data = json.loads(await response.text(encoding="utf-8")) except ValueError as exc: raise RegistryException( "Failed decoding JSON response from registry" ) from exc except aiohttp.ClientError as exc: raise RegistryException("failed to contact registry") from exc return Manifest.parse( manifest_data, media_type=response.headers.get("Content-Type"), ) async def manifest_write( self, ref: RegistryManifestRef, manifest: Manifest ) -> None: """ Write a manifest to a registry. If `ref.ref` is empty or is a digest ref, then `ref.ref` will be ignored and the manifest will be pushed untagged using the digest of `manifest.canonical()`. """ if not ref.ref or ref.is_digest_ref(): ref = ref.copy(update=dict(ref=manifest.digest)) async with await self._request( "PUT", ref.registry or self.default_registry, ref.url, data=manifest.canonical(), headers={"Content-Type": manifest.get_media_type()}, ) as response: if response.status // 100 != 2: raise RegistryException("Failed to copy manifest") async def blob_write( self, ref: RegistryBlobRef, data: AsyncIterable[bytes] ) -> RegistryBlobRef: """ Writes a blob to the registry. The digest will be calculated automatically while uploading, ignoring `ref.ref`. A copy of `ref` with `ref.ref` set to the calculated digest will be returned. """ # Perform the blob upload flow, POST -> PATCH -> PUT registry = ref.registry or self.default_registry async with await self._request( "POST", registry, ref.upload_url(), ) as response: if response.status // 100 != 2: raise RegistryException( "Unexpected response attempting to start blob copy" ) upload_location = response.headers["Location"] hsh = hashlib.sha256() async for chunk in async_generator_buffer(data, 4): hsh.update(chunk) async with await self._request( "PATCH", registry, upload_location, data=chunk, headers={"Content-Type": "application/octet-stream"}, has_host=True, ) as response: if response.status // 100 != 2: raise RegistryException("Unexpected response writing blob data") upload_location = response.headers["Location"] digest = "sha256:" + hsh.hexdigest() async with await self._request( "PUT", registry, f"{upload_location}&digest={digest}", has_host=True, ) as response: if response.status // 100 != 2: raise RegistryException("Unexpected response ending blob copy") return ref.copy(update=dict(ref=digest)) async def registry_repos(self, registry: Optional[Registry]) -> List[str]: """ Return a list of all repos for the given registry. It is up to the registry implementation to determine what if any repo names will be returned. """ async with await self._request( "GET", registry or self.default_registry, "/v2/_catalog", ) as response: try: return (await response.json())["repositories"] except ValueError as exc: raise RegistryException("Unexpected response getting repos") from exc async def registry_repo_tags( self, registry: Optional[Registry], repo: List[str] ) -> List[str]: """ Return a list of all tags for the given repo name. """ async with await self._request( "GET", registry or self.default_registry, f"/v2/{'/'.join(repo)}/tags/list", ) as response: try: return (await response.json())["tags"] except ValueError as exc: raise RegistryException( "Unexpected response getting repo tags" ) from exc async def copy_refs(self, src: RegistryBlobRef, dst: RegistryBlobRef) -> bool: """ Copy the blob src to dst. Returns True if any data was copied and False if the content already existed. """ if src.OBJECT_TYPE != dst.OBJECT_TYPE: raise ValueError("Cannot copy ref to different object type") if dst.is_digest_ref(): if src.ref != dst.ref: raise ValueError( "Cannot copy to a content address that does not match the source" ) if src == dst: LOGGER.info("skipping copy of identical refs") return False # Check if ref already exists if src.is_digest_ref(): if await self.ref_lookup(dst) is not None: LOGGER.info("Skipping copy %s -> %s - already exists", src, dst) return False if isinstance(src, RegistryManifestRef): manifest = await self.manifest_download(src) await asyncio.gather( *( self.copy_refs( RegistryManifestRef( registry=src.registry, repo=src.repo, ref=digest ), RegistryManifestRef( registry=dst.registry, repo=dst.repo, ref=digest ), ) for digest in manifest.get_manifest_dependencies() ), *( self.copy_refs( RegistryBlobRef( registry=src.registry, repo=src.repo, ref=digest ), RegistryBlobRef( registry=dst.registry, repo=dst.repo, ref=digest ), ) for digest in manifest.get_blob_dependencies() ), ) assert isinstance(dst, RegistryManifestRef) await self.manifest_write(dst, manifest) LOGGER.info("Copied manifest %s -> %s", src, dst) return True # Attempt mount if blobs come from the same registry. if src.registry == dst.registry: query_str = urllib.parse.urlencode( { "from": "/".join(src.repo), "mount": dst.ref, } ) async with await self._request( "POST", dst.registry or self.default_registry, f"v2/{'/'.join(dst.repo)}/blobs/uploads/?{query_str}", ) as response: if response.status == 201: LOGGER.info( "Mounted blob %s from %s", dst.ref, "/".join(src.repo), ) return True LOGGER.warning( "mount failed with status %s, trying copy", response.status, ) raise Exception("no") await self.blob_write(dst, self.ref_content_stream(src)) LOGGER.info("Copied blob %s -> %s", src, dst) return True
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2021-01-06 16:12 from typing import List from elit.common.dataset import SortingSamplerBuilder from elit.common.transform import NormalizeToken from elit.components.mtl.multi_task_learning import MultiTaskLearning from elit.components.mtl.tasks.constituency import CRFConstituencyParsing from elit.components.mtl.tasks.dep import BiaffineDependencyParsing from elit.components.mtl.tasks.ner.biaffine_ner import BiaffineNamedEntityRecognition from elit.components.mtl.tasks.pos import TransformerTagging from elit.components.mtl.tasks.srl.rank_srl import SpanRankingSemanticRoleLabeling from elit.datasets.parsing.ptb import PTB_TOKEN_MAPPING from elit.datasets.srl.ontonotes5.chinese import ONTONOTES5_POS_CHINESE_TRAIN, ONTONOTES5_POS_CHINESE_TEST, \ ONTONOTES5_POS_CHINESE_DEV, ONTONOTES5_CHINESE_TRAIN, ONTONOTES5_CHINESE_TEST, ONTONOTES5_CHINESE_DEV, \ ONTONOTES5_CON_CHINESE_TRAIN, ONTONOTES5_CON_CHINESE_DEV, ONTONOTES5_CON_CHINESE_TEST, ONTONOTES5_DEP_CHINESE_TEST, \ ONTONOTES5_DEP_CHINESE_DEV, ONTONOTES5_DEP_CHINESE_TRAIN from elit.layers.embeddings.contextual_word_embedding import ContextualWordEmbedding from elit.metrics.mtl import MetricDict from elit.utils.log_util import cprint from stem_cell_hypothesis import cdroot def main(): cdroot() scores: List[MetricDict] = [] for i in range(3): tasks = { # 'pos': TransformerTagging( # ONTONOTES5_POS_CHINESE_TRAIN, # ONTONOTES5_POS_CHINESE_DEV, # ONTONOTES5_POS_CHINESE_TEST, # SortingSamplerBuilder(batch_size=64, batch_max_tokens=6400), # lr=1e-3, # ), 'ner': BiaffineNamedEntityRecognition( ONTONOTES5_CHINESE_TRAIN, ONTONOTES5_CHINESE_DEV, ONTONOTES5_CHINESE_TEST, SortingSamplerBuilder(batch_size=64, batch_max_tokens=6400), lr=1e-3, doc_level_offset=True, ), # 'srl': SpanRankingSemanticRoleLabeling( # ONTONOTES5_CHINESE_TRAIN, # ONTONOTES5_CHINESE_DEV, # ONTONOTES5_CHINESE_TEST, # SortingSamplerBuilder(batch_size=64, batch_max_tokens=6400), # lr=1e-3, # doc_level_offset=True, # ), # 'dep': BiaffineDependencyParsing( # ONTONOTES5_DEP_CHINESE_TRAIN, # ONTONOTES5_DEP_CHINESE_DEV, # ONTONOTES5_DEP_CHINESE_TEST, # SortingSamplerBuilder(batch_size=64, batch_max_tokens=6400), # lr=1e-3, # ), # 'con': CRFConstituencyParsing( # ONTONOTES5_CON_CHINESE_TRAIN, # ONTONOTES5_CON_CHINESE_DEV, # ONTONOTES5_CON_CHINESE_TEST, # SortingSamplerBuilder(batch_size=64, batch_max_tokens=6400), # lr=1e-3, # ), } mtl = MultiTaskLearning() save_dir = f'data/model/mtl/ontonotes_electra_base_ner_zh_{i}' cprint(f'Model will be saved in [cyan]{save_dir}[/cyan]') mtl.fit( ContextualWordEmbedding( 'token', "hfl/chinese-electra-180g-base-discriminator", average_subwords=True, max_sequence_length=512, word_dropout=.2, ), tasks, save_dir, 30, lr=1e-3, encoder_lr=5e-5, grad_norm=1, gradient_accumulation=2, eval_trn=False, # prefetch=10, # cache='data/tmp' ) cprint(f'Model saved in [cyan]{save_dir}[/cyan]') mtl.load(save_dir) if 'dep' in mtl.tasks: mtl['dep'].config.tree = True mtl['dep'].config.proj = True mtl.save_config(save_dir) for k, v in mtl.tasks.items(): v.trn = tasks[k].trn v.dev = tasks[k].dev v.tst = tasks[k].tst metric = mtl.evaluate(save_dir)[0] scores.append(metric) print(f'{'-'.join(tasks.keys())} {len(scores)} runs scores:') for each in scores: cprint(each.cstr()) if __name__ == '__main__': import torch # torch.multiprocessing.set_start_method('spawn') # See https://github.com/pytorch/pytorch/issues/40403 main()
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2021-01-06 16:12 from typing import List from elit.common.dataset import SortingSamplerBuilder from elit.common.transform import NormalizeToken from elit.components.mtl.multi_task_learning import MultiTaskLearning from elit.components.mtl.tasks.constituency import CRFConstituencyParsing from elit.components.mtl.tasks.dep import BiaffineDependencyParsing from elit.components.mtl.tasks.ner.biaffine_ner import BiaffineNamedEntityRecognition from elit.components.mtl.tasks.pos import TransformerTagging from elit.components.mtl.tasks.srl.rank_srl import SpanRankingSemanticRoleLabeling from elit.datasets.parsing.ptb import PTB_TOKEN_MAPPING from elit.datasets.srl.ontonotes5.chinese import ONTONOTES5_POS_CHINESE_TRAIN, ONTONOTES5_POS_CHINESE_TEST, \ ONTONOTES5_POS_CHINESE_DEV, ONTONOTES5_CHINESE_TRAIN, ONTONOTES5_CHINESE_TEST, ONTONOTES5_CHINESE_DEV, \ ONTONOTES5_CON_CHINESE_TRAIN, ONTONOTES5_CON_CHINESE_DEV, ONTONOTES5_CON_CHINESE_TEST, ONTONOTES5_DEP_CHINESE_TEST, \ ONTONOTES5_DEP_CHINESE_DEV, ONTONOTES5_DEP_CHINESE_TRAIN from elit.layers.embeddings.contextual_word_embedding import ContextualWordEmbedding from elit.metrics.mtl import MetricDict from elit.utils.log_util import cprint from stem_cell_hypothesis import cdroot def main(): cdroot() scores: List[MetricDict] = [] for i in range(3): tasks = { # 'pos': TransformerTagging( # ONTONOTES5_POS_CHINESE_TRAIN, # ONTONOTES5_POS_CHINESE_DEV, # ONTONOTES5_POS_CHINESE_TEST, # SortingSamplerBuilder(batch_size=64, batch_max_tokens=6400), # lr=1e-3, # ), 'ner': BiaffineNamedEntityRecognition( ONTONOTES5_CHINESE_TRAIN, ONTONOTES5_CHINESE_DEV, ONTONOTES5_CHINESE_TEST, SortingSamplerBuilder(batch_size=64, batch_max_tokens=6400), lr=1e-3, doc_level_offset=True, ), # 'srl': SpanRankingSemanticRoleLabeling( # ONTONOTES5_CHINESE_TRAIN, # ONTONOTES5_CHINESE_DEV, # ONTONOTES5_CHINESE_TEST, # SortingSamplerBuilder(batch_size=64, batch_max_tokens=6400), # lr=1e-3, # doc_level_offset=True, # ), # 'dep': BiaffineDependencyParsing( # ONTONOTES5_DEP_CHINESE_TRAIN, # ONTONOTES5_DEP_CHINESE_DEV, # ONTONOTES5_DEP_CHINESE_TEST, # SortingSamplerBuilder(batch_size=64, batch_max_tokens=6400), # lr=1e-3, # ), # 'con': CRFConstituencyParsing( # ONTONOTES5_CON_CHINESE_TRAIN, # ONTONOTES5_CON_CHINESE_DEV, # ONTONOTES5_CON_CHINESE_TEST, # SortingSamplerBuilder(batch_size=64, batch_max_tokens=6400), # lr=1e-3, # ), } mtl = MultiTaskLearning() save_dir = f'data/model/mtl/ontonotes_electra_base_ner_zh_{i}' cprint(f'Model will be saved in [cyan]{save_dir}[/cyan]') mtl.fit( ContextualWordEmbedding( 'token', "hfl/chinese-electra-180g-base-discriminator", average_subwords=True, max_sequence_length=512, word_dropout=.2, ), tasks, save_dir, 30, lr=1e-3, encoder_lr=5e-5, grad_norm=1, gradient_accumulation=2, eval_trn=False, # prefetch=10, # cache='data/tmp' ) cprint(f'Model saved in [cyan]{save_dir}[/cyan]') mtl.load(save_dir) if 'dep' in mtl.tasks: mtl['dep'].config.tree = True mtl['dep'].config.proj = True mtl.save_config(save_dir) for k, v in mtl.tasks.items(): v.trn = tasks[k].trn v.dev = tasks[k].dev v.tst = tasks[k].tst metric = mtl.evaluate(save_dir)[0] scores.append(metric) print(f'{"-".join(tasks.keys())} {len(scores)} runs scores:') for each in scores: cprint(each.cstr()) if __name__ == '__main__': import torch # torch.multiprocessing.set_start_method('spawn') # See https://github.com/pytorch/pytorch/issues/40403 main()
# load modules from requests_api import request from ..entity import SearchResponse # const SERVER = 'https://beatsaver.com/api' # definition async def search_maps( # Options are a little weird, I may add another enum field in future to make this clearer. # true = both, false = only ai, null = no ai automapper: bool = False, # chroma chrome: bool = False, # cinema cinema: bool = False, # curated curated: bool = False, # Instant from_: str = '', # fullSpread fullSpread: bool = False, # Float maxBpm: float = 0, # maxDuration maxDuration: int = 0, # Float maxNps: float = 0, # Float maxRating: float = 0, # me me: bool = False, # Float minBpm: float = 0, # minDuration minDuration: int = 0, # Float minNps: float = 0, # Float minRating: float = 0, # noodle noodle: bool = False, # page page: int = 0, # q q: str = '', # ranked ranked: bool = False, # sortOrder sortOrder: str = '', # Comma seperated tags tags: str = '', # Instant to: str = '' ): """ GET /search/text/{page} """ # prepare query query_list = [] if automapper: query_list.append(f'automapper={automapper}') if chrome: query_list.append(f'chrome=true') if cinema: query_list.append(f'cinema=true') if curated: query_list.append(f'curated=true') if from_: query_list.append(f'from={from_}') if fullSpread: query_list.append(f'fullSpread=true') if maxBpm > 0: query_list.append(f'maxBpm={maxBpm}') if maxDuration > 0: query_list.append(f'maxDuration={maxDuration}') if maxNps > 0: query_list.append(f'maxNps={maxNps}') if maxRating > 0: query_list.append(f'maxRating={maxRating}') if me: query_list.append(f'me=true') if minBpm > 0: query_list.append(f'minBpm={minBpm}') if minDuration > 0: query_list.append(f'minDuration={minDuration}') if minNps > 0: query_list.append(f'minNps={minNps}') if minRating > 0: query_list.append(f'minRating={minRating}') if noodle: query_list.append(f'noodle=true') if q: query_list.append(f'q={q}') if ranked: query_list.append(f'ranked=true') if (sortOrder == 'Latest') or (sortOrder == 'Relevance') or (sortOrder == 'Rating'): query_list.append(f'sortOrder={sortOrder}') if tags: query_list.append(f'tags={tags}') if to: query_list.append(f'to={to}') if len(query_list) > 0: query = f'?{'&'.join(query_list)}' else: query = '' # request request_url = f'{SERVER}/search/text/{page}{query}' response_dict = await request.get(request_url) return SearchResponse.gen(response_dict)
# load modules from requests_api import request from ..entity import SearchResponse # const SERVER = 'https://beatsaver.com/api' # definition async def search_maps( # Options are a little weird, I may add another enum field in future to make this clearer. # true = both, false = only ai, null = no ai automapper: bool = False, # chroma chrome: bool = False, # cinema cinema: bool = False, # curated curated: bool = False, # Instant from_: str = '', # fullSpread fullSpread: bool = False, # Float maxBpm: float = 0, # maxDuration maxDuration: int = 0, # Float maxNps: float = 0, # Float maxRating: float = 0, # me me: bool = False, # Float minBpm: float = 0, # minDuration minDuration: int = 0, # Float minNps: float = 0, # Float minRating: float = 0, # noodle noodle: bool = False, # page page: int = 0, # q q: str = '', # ranked ranked: bool = False, # sortOrder sortOrder: str = '', # Comma seperated tags tags: str = '', # Instant to: str = '' ): """ GET /search/text/{page} """ # prepare query query_list = [] if automapper: query_list.append(f'automapper={automapper}') if chrome: query_list.append(f'chrome=true') if cinema: query_list.append(f'cinema=true') if curated: query_list.append(f'curated=true') if from_: query_list.append(f'from={from_}') if fullSpread: query_list.append(f'fullSpread=true') if maxBpm > 0: query_list.append(f'maxBpm={maxBpm}') if maxDuration > 0: query_list.append(f'maxDuration={maxDuration}') if maxNps > 0: query_list.append(f'maxNps={maxNps}') if maxRating > 0: query_list.append(f'maxRating={maxRating}') if me: query_list.append(f'me=true') if minBpm > 0: query_list.append(f'minBpm={minBpm}') if minDuration > 0: query_list.append(f'minDuration={minDuration}') if minNps > 0: query_list.append(f'minNps={minNps}') if minRating > 0: query_list.append(f'minRating={minRating}') if noodle: query_list.append(f'noodle=true') if q: query_list.append(f'q={q}') if ranked: query_list.append(f'ranked=true') if (sortOrder == 'Latest') or (sortOrder == 'Relevance') or (sortOrder == 'Rating'): query_list.append(f'sortOrder={sortOrder}') if tags: query_list.append(f'tags={tags}') if to: query_list.append(f'to={to}') if len(query_list) > 0: query = f'?{"&".join(query_list)}' else: query = '' # request request_url = f'{SERVER}/search/text/{page}{query}' response_dict = await request.get(request_url) return SearchResponse.gen(response_dict)
""" This module sets up all the post endpoints Author: Dave """ from flask import request, jsonify, make_response, Blueprint, session from app.api.v1.utils.posts_validator import PostValidator from app.api.v1.models.posts import Post, AuthenticationRequired from app.api.v1.models.users import User, AuthenticationRequired v1 = Blueprint('postv1', __name__, url_prefix='/api/v1/') """ This route fetches all posts """ @v1.route("/posts", methods=['GET']) def get(): posts = Post().fetch_posts('(title, body, created_on, id, author_id)', 'True = True') posts_list = [] for post in posts: username = User().fetch_specific_user('username', f"id = {post[0]["f5"]}")[0] user_img = User().fetch_specific_user('image', f"id = {post[0]["f5"]}")[0] post_item = { "title": post[0]['f1'], "body": post[0]['f2'], "createdOn": post[0]['f3'], "id": post[0]['f4'], "author": username, "photo": user_img } posts_list.append(post_item) return jsonify({ "status": 200, "posts": posts_list }), 200 """ This route fetches a single post """ @v1.route("posts/<int:postId>", methods=['GET']) def getPost(postId): try: post = Post().grab_items('(title, body, id, author_id)', f'id = {postId}', 'posts') username = User().fetch_specific_user('username', f'id = {post[0]['f4']}')[0] post_item = { "title": post[0]['f1'], "body": post[0]['f2'], "id": post[0]['f3'], "author_id": post[0]['f4'], "username": username } return jsonify({ "post": post_item, "status": 200 }) except: return jsonify({ "error": "post not found", "status": 404 }), 404 """ This route posts a post """ @v1.route("<int:userId>/posts", methods=['POST']) @AuthenticationRequired def post(userId): data = request.get_json() auth_token = request.headers.get('Authorization') token = auth_token.split(" ")[1] if PostValidator().post_fields(data): return make_response(jsonify(PostValidator().post_fields(data)), 400) else: validate_post = PostValidator(data) validation_methods = [ validate_post.valid_post, validate_post.data_exists ] for error in validation_methods: if error(): return make_response(jsonify({ "error": error() }), 422) if User().fetch_specific_user('email', f"id = {userId}"): print('-->', User().fetch_specific_user('email', f"id = {userId}")) post = { "author_id": userId, "title": data['title'], "body": data['body'] } if not User().blacklisted(token): post_model = Post(post) if isinstance(post_model.save_post(), dict): return make_response(jsonify(post_model.save_post())) else: post_model.save_post() return make_response(jsonify({ "status": 201, "message": "You have successfully posted a post", "data": { "title": data['title'], "body": data['body'], "user": userId, "post_id": post_model.fetch_post_id(data['title'])[0] } }), 201) else: return make_response(jsonify({ "error": "Please log in first!", "status": 403 }), 403) else: return make_response(jsonify({ "error": "user not found or does not exist!", "status": 404 }), 404) """ This route updates a post """ @v1.route("/<int:userId>/posts/<int:postId>", methods=['PUT']) @AuthenticationRequired def edit_post(postId, userId): data = request.get_json() print(data) auth_token = request.headers.get('Authorization') token = auth_token.split(" ")[1] if PostValidator().post_fields(data): return make_response(jsonify(PostValidator().post_fields(data)), 400) else: validate_post = PostValidator(data) if validate_post.valid_post(): return make_response(jsonify({ "error": validate_post.valid_post() }), 422) if Post().fetch_specific_post('author_id', f"id = {postId}")[0] == userId: post = Post().update_post(postId, data) if isinstance(post, dict): return make_response(post) else: if not User().blacklisted(token): return make_response(jsonify({ "message": "Post was updated successfully", "status": 200 }), 200) else: return make_response(jsonify({ "error": 'Please log in first!', "status": 403 }), 403) else: return make_response(jsonify({ "error": "You are not authorized to perform this action!", "status": 401 }), 401) """ This route deletes a post """ @v1.route("<int:userId>/posts/<int:postId>", methods=['DELETE']) @AuthenticationRequired def delete_post(postId, userId): auth_token = request.headers.get('Authorization') token = auth_token.split(" ")[1] if not User().blacklisted(token): if Post().fetch_specific_post('author_id', f"id = {postId}") == (userId,): post = Post().delete_post(postId) if isinstance(post, dict): return make_response(post) else: return make_response(jsonify({ "message": 'post was deleted successfully', "status": 200 }), 200) else: return make_response(jsonify({ "error": "You are not authorized to perform this action!", "status": 401 }), 401) else: return make_response(jsonify({ "error": 'Please log in first', "status": 403 }), 403)
""" This module sets up all the post endpoints Author: Dave """ from flask import request, jsonify, make_response, Blueprint, session from app.api.v1.utils.posts_validator import PostValidator from app.api.v1.models.posts import Post, AuthenticationRequired from app.api.v1.models.users import User, AuthenticationRequired v1 = Blueprint('postv1', __name__, url_prefix='/api/v1/') """ This route fetches all posts """ @v1.route("/posts", methods=['GET']) def get(): posts = Post().fetch_posts('(title, body, created_on, id, author_id)', 'True = True') posts_list = [] for post in posts: username = User().fetch_specific_user('username', f"id = {post[0]['f5']}")[0] user_img = User().fetch_specific_user('image', f"id = {post[0]['f5']}")[0] post_item = { "title": post[0]['f1'], "body": post[0]['f2'], "createdOn": post[0]['f3'], "id": post[0]['f4'], "author": username, "photo": user_img } posts_list.append(post_item) return jsonify({ "status": 200, "posts": posts_list }), 200 """ This route fetches a single post """ @v1.route("posts/<int:postId>", methods=['GET']) def getPost(postId): try: post = Post().grab_items('(title, body, id, author_id)', f'id = {postId}', 'posts') username = User().fetch_specific_user('username', f'id = {post[0]["f4"]}')[0] post_item = { "title": post[0]['f1'], "body": post[0]['f2'], "id": post[0]['f3'], "author_id": post[0]['f4'], "username": username } return jsonify({ "post": post_item, "status": 200 }) except: return jsonify({ "error": "post not found", "status": 404 }), 404 """ This route posts a post """ @v1.route("<int:userId>/posts", methods=['POST']) @AuthenticationRequired def post(userId): data = request.get_json() auth_token = request.headers.get('Authorization') token = auth_token.split(" ")[1] if PostValidator().post_fields(data): return make_response(jsonify(PostValidator().post_fields(data)), 400) else: validate_post = PostValidator(data) validation_methods = [ validate_post.valid_post, validate_post.data_exists ] for error in validation_methods: if error(): return make_response(jsonify({ "error": error() }), 422) if User().fetch_specific_user('email', f"id = {userId}"): print('-->', User().fetch_specific_user('email', f"id = {userId}")) post = { "author_id": userId, "title": data['title'], "body": data['body'] } if not User().blacklisted(token): post_model = Post(post) if isinstance(post_model.save_post(), dict): return make_response(jsonify(post_model.save_post())) else: post_model.save_post() return make_response(jsonify({ "status": 201, "message": "You have successfully posted a post", "data": { "title": data['title'], "body": data['body'], "user": userId, "post_id": post_model.fetch_post_id(data['title'])[0] } }), 201) else: return make_response(jsonify({ "error": "Please log in first!", "status": 403 }), 403) else: return make_response(jsonify({ "error": "user not found or does not exist!", "status": 404 }), 404) """ This route updates a post """ @v1.route("/<int:userId>/posts/<int:postId>", methods=['PUT']) @AuthenticationRequired def edit_post(postId, userId): data = request.get_json() print(data) auth_token = request.headers.get('Authorization') token = auth_token.split(" ")[1] if PostValidator().post_fields(data): return make_response(jsonify(PostValidator().post_fields(data)), 400) else: validate_post = PostValidator(data) if validate_post.valid_post(): return make_response(jsonify({ "error": validate_post.valid_post() }), 422) if Post().fetch_specific_post('author_id', f"id = {postId}")[0] == userId: post = Post().update_post(postId, data) if isinstance(post, dict): return make_response(post) else: if not User().blacklisted(token): return make_response(jsonify({ "message": "Post was updated successfully", "status": 200 }), 200) else: return make_response(jsonify({ "error": 'Please log in first!', "status": 403 }), 403) else: return make_response(jsonify({ "error": "You are not authorized to perform this action!", "status": 401 }), 401) """ This route deletes a post """ @v1.route("<int:userId>/posts/<int:postId>", methods=['DELETE']) @AuthenticationRequired def delete_post(postId, userId): auth_token = request.headers.get('Authorization') token = auth_token.split(" ")[1] if not User().blacklisted(token): if Post().fetch_specific_post('author_id', f"id = {postId}") == (userId,): post = Post().delete_post(postId) if isinstance(post, dict): return make_response(post) else: return make_response(jsonify({ "message": 'post was deleted successfully', "status": 200 }), 200) else: return make_response(jsonify({ "error": "You are not authorized to perform this action!", "status": 401 }), 401) else: return make_response(jsonify({ "error": 'Please log in first', "status": 403 }), 403)
"""UniFi switch platform tests.""" from copy import deepcopy from unittest.mock import patch from aiounifi.controller import MESSAGE_CLIENT_REMOVED, MESSAGE_EVENT from homeassistant import config_entries, core from homeassistant.components.device_tracker import DOMAIN as TRACKER_DOMAIN from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN from homeassistant.components.unifi.const import ( CONF_BLOCK_CLIENT, CONF_DPI_RESTRICTIONS, CONF_POE_CLIENTS, CONF_TRACK_CLIENTS, CONF_TRACK_DEVICES, DOMAIN as UNIFI_DOMAIN, ) from homeassistant.components.unifi.switch import POE_SWITCH from homeassistant.const import ENTITY_CATEGORY_CONFIG, STATE_OFF, STATE_ON from homeassistant.helpers import entity_registry as er from homeassistant.helpers.dispatcher import async_dispatcher_send from .test_controller import ( CONTROLLER_HOST, DEFAULT_CONFIG_ENTRY_ID, DESCRIPTION, ENTRY_CONFIG, setup_unifi_integration, ) CLIENT_1 = { "hostname": "client_1", "ip": "10.0.0.1", "is_wired": True, "last_seen": 1562600145, "mac": "00:00:00:00:00:01", "name": "POE Client 1", "oui": "Producer", "sw_mac": "00:00:00:00:01:01", "sw_port": 1, "wired-rx_bytes": 1234000000, "wired-tx_bytes": 5678000000, } CLIENT_2 = { "hostname": "client_2", "ip": "10.0.0.2", "is_wired": True, "last_seen": 1562600145, "mac": "00:00:00:00:00:02", "name": "POE Client 2", "oui": "Producer", "sw_mac": "00:00:00:00:01:01", "sw_port": 2, "wired-rx_bytes": 1234000000, "wired-tx_bytes": 5678000000, } CLIENT_3 = { "hostname": "client_3", "ip": "10.0.0.3", "is_wired": True, "last_seen": 1562600145, "mac": "00:00:00:00:00:03", "name": "Non-POE Client 3", "oui": "Producer", "sw_mac": "00:00:00:00:01:01", "sw_port": 3, "wired-rx_bytes": 1234000000, "wired-tx_bytes": 5678000000, } CLIENT_4 = { "hostname": "client_4", "ip": "10.0.0.4", "is_wired": True, "last_seen": 1562600145, "mac": "00:00:00:00:00:04", "name": "Non-POE Client 4", "oui": "Producer", "sw_mac": "00:00:00:00:01:01", "sw_port": 4, "wired-rx_bytes": 1234000000, "wired-tx_bytes": 5678000000, } POE_SWITCH_CLIENTS = [ { "hostname": "client_1", "ip": "10.0.0.1", "is_wired": True, "last_seen": 1562600145, "mac": "00:00:00:00:00:01", "name": "POE Client 1", "oui": "Producer", "sw_mac": "00:00:00:00:01:01", "sw_port": 1, "wired-rx_bytes": 1234000000, "wired-tx_bytes": 5678000000, }, { "hostname": "client_2", "ip": "10.0.0.2", "is_wired": True, "last_seen": 1562600145, "mac": "00:00:00:00:00:02", "name": "POE Client 2", "oui": "Producer", "sw_mac": "00:00:00:00:01:01", "sw_port": 1, "wired-rx_bytes": 1234000000, "wired-tx_bytes": 5678000000, }, ] DEVICE_1 = { "device_id": "mock-id", "ip": "10.0.1.1", "mac": "00:00:00:00:01:01", "last_seen": 1562600145, "model": "US16P150", "name": "mock-name", "port_overrides": [], "port_table": [ { "media": "GE", "name": "Port 1", "port_idx": 1, "poe_class": "Class 4", "poe_enable": True, "poe_mode": "auto", "poe_power": "2.56", "poe_voltage": "53.40", "portconf_id": "1a1", "port_poe": True, "up": True, }, { "media": "GE", "name": "Port 2", "port_idx": 2, "poe_class": "Class 4", "poe_enable": True, "poe_mode": "auto", "poe_power": "2.56", "poe_voltage": "53.40", "portconf_id": "1a2", "port_poe": True, "up": True, }, { "media": "GE", "name": "Port 3", "port_idx": 3, "poe_class": "Unknown", "poe_enable": False, "poe_mode": "off", "poe_power": "0.00", "poe_voltage": "0.00", "portconf_id": "1a3", "port_poe": False, "up": True, }, { "media": "GE", "name": "Port 4", "port_idx": 4, "poe_class": "Unknown", "poe_enable": False, "poe_mode": "auto", "poe_power": "0.00", "poe_voltage": "0.00", "portconf_id": "1a4", "port_poe": True, "up": True, }, ], "state": 1, "type": "usw", "version": "4.0.42.10433", } BLOCKED = { "blocked": True, "hostname": "block_client_1", "ip": "10.0.0.1", "is_guest": False, "is_wired": False, "last_seen": 1562600145, "mac": "00:00:00:00:01:01", "name": "Block Client 1", "noted": True, "oui": "Producer", } UNBLOCKED = { "blocked": False, "hostname": "block_client_2", "ip": "10.0.0.2", "is_guest": False, "is_wired": True, "last_seen": 1562600145, "mac": "00:00:00:00:01:02", "name": "Block Client 2", "noted": True, "oui": "Producer", } EVENT_BLOCKED_CLIENT_CONNECTED = { "user": BLOCKED["mac"], "radio": "na", "channel": "44", "hostname": BLOCKED["hostname"], "key": "EVT_WU_Connected", "subsystem": "wlan", "site_id": "name", "time": 1587753456179, "datetime": "2020-04-24T18:37:36Z", "msg": f'User{[BLOCKED['mac']]} has connected."', "_id": "5ea331fa30c49e00f90ddc1a", } EVENT_BLOCKED_CLIENT_BLOCKED = { "user": BLOCKED["mac"], "hostname": BLOCKED["hostname"], "key": "EVT_WC_Blocked", "subsystem": "wlan", "site_id": "name", "time": 1587753456179, "datetime": "2020-04-24T18:37:36Z", "msg": f'User{[BLOCKED['mac']]} has been blocked."', "_id": "5ea331fa30c49e00f90ddc1a", } EVENT_BLOCKED_CLIENT_UNBLOCKED = { "user": BLOCKED["mac"], "hostname": BLOCKED["hostname"], "key": "EVT_WC_Unblocked", "subsystem": "wlan", "site_id": "name", "time": 1587753456179, "datetime": "2020-04-24T18:37:36Z", "msg": f'User{[BLOCKED['mac']]} has been unblocked."', "_id": "5ea331fa30c49e00f90ddc1a", } EVENT_CLIENT_2_CONNECTED = { "user": CLIENT_2["mac"], "radio": "na", "channel": "44", "hostname": CLIENT_2["hostname"], "key": "EVT_WU_Connected", "subsystem": "wlan", "site_id": "name", "time": 1587753456179, "datetime": "2020-04-24T18:37:36Z", "msg": f'User{[CLIENT_2['mac']]} has connected."', "_id": "5ea331fa30c49e00f90ddc1a", } DPI_GROUPS = [ { "_id": "5ba29dd8e3c58f026e9d7c4a", "attr_no_delete": True, "attr_hidden_id": "Default", "name": "Default", "site_id": "name", }, { "_id": "5f976f4ae3c58f018ec7dff6", "name": "Block Media Streaming", "site_id": "name", "dpiapp_ids": ["5f976f62e3c58f018ec7e17d"], }, ] DPI_APPS = [ { "_id": "5f976f62e3c58f018ec7e17d", "apps": [], "blocked": True, "cats": ["4"], "enabled": True, "log": True, "site_id": "name", } ] DPI_GROUP_REMOVED_EVENT = { "meta": {"rc": "ok", "message": "dpigroup:delete"}, "data": [ { "_id": "5f976f4ae3c58f018ec7dff6", "name": "dpi group", "site_id": "name", "dpiapp_ids": [], } ], } DPI_APP_DISABLED_EVENT = { "meta": {"rc": "ok", "message": "dpiapp:sync"}, "data": [ { "_id": "5f976f62e3c58f018ec7e17d", "apps": [], "blocked": False, "cats": [], "enabled": False, "log": False, "site_id": "name", } ], } async def test_no_clients(hass, aioclient_mock): """Test the update_clients function when no clients are found.""" await setup_unifi_integration( hass, aioclient_mock, options={ CONF_TRACK_CLIENTS: False, CONF_TRACK_DEVICES: False, CONF_DPI_RESTRICTIONS: False, }, ) assert aioclient_mock.call_count == 10 assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 0 async def test_controller_not_client(hass, aioclient_mock): """Test that the controller doesn't become a switch.""" await setup_unifi_integration( hass, aioclient_mock, options={CONF_TRACK_CLIENTS: False, CONF_TRACK_DEVICES: False}, clients_response=[CONTROLLER_HOST], devices_response=[DEVICE_1], ) assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 0 cloudkey = hass.states.get("switch.cloud_key") assert cloudkey is None async def test_not_admin(hass, aioclient_mock): """Test that switch platform only work on an admin account.""" description = deepcopy(DESCRIPTION) description[0]["site_role"] = "not admin" await setup_unifi_integration( hass, aioclient_mock, options={CONF_TRACK_CLIENTS: False, CONF_TRACK_DEVICES: False}, site_description=description, clients_response=[CLIENT_1], devices_response=[DEVICE_1], ) assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 0 async def test_switches(hass, aioclient_mock): """Test the update_items function with some clients.""" config_entry = await setup_unifi_integration( hass, aioclient_mock, options={ CONF_BLOCK_CLIENT: [BLOCKED["mac"], UNBLOCKED["mac"]], CONF_TRACK_CLIENTS: False, CONF_TRACK_DEVICES: False, }, clients_response=[CLIENT_1, CLIENT_4], devices_response=[DEVICE_1], clients_all_response=[BLOCKED, UNBLOCKED, CLIENT_1], dpigroup_response=DPI_GROUPS, dpiapp_response=DPI_APPS, ) controller = hass.data[UNIFI_DOMAIN][config_entry.entry_id] assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 4 switch_1 = hass.states.get("switch.poe_client_1") assert switch_1 is not None assert switch_1.state == "on" assert switch_1.attributes["power"] == "2.56" assert switch_1.attributes[SWITCH_DOMAIN] == "00:00:00:00:01:01" assert switch_1.attributes["port"] == 1 assert switch_1.attributes["poe_mode"] == "auto" switch_4 = hass.states.get("switch.poe_client_4") assert switch_4 is None blocked = hass.states.get("switch.block_client_1") assert blocked is not None assert blocked.state == "off" unblocked = hass.states.get("switch.block_client_2") assert unblocked is not None assert unblocked.state == "on" dpi_switch = hass.states.get("switch.block_media_streaming") assert dpi_switch is not None assert dpi_switch.state == "on" assert dpi_switch.attributes["icon"] == "mdi:network" ent_reg = er.async_get(hass) for entry_id in ( "switch.poe_client_1", "switch.block_client_1", "switch.block_media_streaming", ): assert ent_reg.async_get(entry_id).entity_category == ENTITY_CATEGORY_CONFIG # Block and unblock client aioclient_mock.post( f"https://{controller.host}:1234/api/s/{controller.site}/cmd/stamgr", ) await hass.services.async_call( SWITCH_DOMAIN, "turn_off", {"entity_id": "switch.block_client_1"}, blocking=True ) assert aioclient_mock.call_count == 11 assert aioclient_mock.mock_calls[10][2] == { "mac": "00:00:00:00:01:01", "cmd": "block-sta", } await hass.services.async_call( SWITCH_DOMAIN, "turn_on", {"entity_id": "switch.block_client_1"}, blocking=True ) assert aioclient_mock.call_count == 12 assert aioclient_mock.mock_calls[11][2] == { "mac": "00:00:00:00:01:01", "cmd": "unblock-sta", } # Enable and disable DPI aioclient_mock.put( f"https://{controller.host}:1234/api/s/{controller.site}/rest/dpiapp/5f976f62e3c58f018ec7e17d", ) await hass.services.async_call( SWITCH_DOMAIN, "turn_off", {"entity_id": "switch.block_media_streaming"}, blocking=True, ) assert aioclient_mock.call_count == 13 assert aioclient_mock.mock_calls[12][2] == {"enabled": False} await hass.services.async_call( SWITCH_DOMAIN, "turn_on", {"entity_id": "switch.block_media_streaming"}, blocking=True, ) assert aioclient_mock.call_count == 14 assert aioclient_mock.mock_calls[13][2] == {"enabled": True} # Make sure no duplicates arise on generic signal update async_dispatcher_send(hass, controller.signal_update) await hass.async_block_till_done() assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 4 async def test_remove_switches(hass, aioclient_mock, mock_unifi_websocket): """Test the update_items function with some clients.""" await setup_unifi_integration( hass, aioclient_mock, options={CONF_BLOCK_CLIENT: [UNBLOCKED["mac"]]}, clients_response=[CLIENT_1, UNBLOCKED], devices_response=[DEVICE_1], dpigroup_response=DPI_GROUPS, dpiapp_response=DPI_APPS, ) assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 3 assert hass.states.get("switch.poe_client_1") is not None assert hass.states.get("switch.block_client_2") is not None assert hass.states.get("switch.block_media_streaming") is not None mock_unifi_websocket( data={ "meta": {"message": MESSAGE_CLIENT_REMOVED}, "data": [CLIENT_1, UNBLOCKED], } ) await hass.async_block_till_done() assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 1 assert hass.states.get("switch.poe_client_1") is None assert hass.states.get("switch.block_client_2") is None assert hass.states.get("switch.block_media_streaming") is not None mock_unifi_websocket(data=DPI_GROUP_REMOVED_EVENT) await hass.async_block_till_done() await hass.async_block_till_done() assert hass.states.get("switch.block_media_streaming") is None assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 0 async def test_block_switches(hass, aioclient_mock, mock_unifi_websocket): """Test the update_items function with some clients.""" config_entry = await setup_unifi_integration( hass, aioclient_mock, options={ CONF_BLOCK_CLIENT: [BLOCKED["mac"], UNBLOCKED["mac"]], CONF_TRACK_CLIENTS: False, CONF_TRACK_DEVICES: False, }, clients_response=[UNBLOCKED], clients_all_response=[BLOCKED], ) controller = hass.data[UNIFI_DOMAIN][config_entry.entry_id] assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 2 blocked = hass.states.get("switch.block_client_1") assert blocked is not None assert blocked.state == "off" unblocked = hass.states.get("switch.block_client_2") assert unblocked is not None assert unblocked.state == "on" mock_unifi_websocket( data={ "meta": {"message": MESSAGE_EVENT}, "data": [EVENT_BLOCKED_CLIENT_UNBLOCKED], } ) await hass.async_block_till_done() assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 2 blocked = hass.states.get("switch.block_client_1") assert blocked is not None assert blocked.state == "on" mock_unifi_websocket( data={ "meta": {"message": MESSAGE_EVENT}, "data": [EVENT_BLOCKED_CLIENT_BLOCKED], } ) await hass.async_block_till_done() assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 2 blocked = hass.states.get("switch.block_client_1") assert blocked is not None assert blocked.state == "off" aioclient_mock.post( f"https://{controller.host}:1234/api/s/{controller.site}/cmd/stamgr", ) await hass.services.async_call( SWITCH_DOMAIN, "turn_off", {"entity_id": "switch.block_client_1"}, blocking=True ) assert aioclient_mock.call_count == 11 assert aioclient_mock.mock_calls[10][2] == { "mac": "00:00:00:00:01:01", "cmd": "block-sta", } await hass.services.async_call( SWITCH_DOMAIN, "turn_on", {"entity_id": "switch.block_client_1"}, blocking=True ) assert aioclient_mock.call_count == 12 assert aioclient_mock.mock_calls[11][2] == { "mac": "00:00:00:00:01:01", "cmd": "unblock-sta", } async def test_dpi_switches(hass, aioclient_mock, mock_unifi_websocket): """Test the update_items function with some clients.""" await setup_unifi_integration( hass, aioclient_mock, dpigroup_response=DPI_GROUPS, dpiapp_response=DPI_APPS, ) assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 1 dpi_switch = hass.states.get("switch.block_media_streaming") assert dpi_switch is not None assert dpi_switch.state == STATE_ON assert dpi_switch.attributes["icon"] == "mdi:network" mock_unifi_websocket(data=DPI_APP_DISABLED_EVENT) await hass.async_block_till_done() assert hass.states.get("switch.block_media_streaming").state == STATE_OFF async def test_new_client_discovered_on_block_control( hass, aioclient_mock, mock_unifi_websocket ): """Test if 2nd update has a new client.""" await setup_unifi_integration( hass, aioclient_mock, options={ CONF_BLOCK_CLIENT: [BLOCKED["mac"]], CONF_TRACK_CLIENTS: False, CONF_TRACK_DEVICES: False, CONF_DPI_RESTRICTIONS: False, }, ) assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 0 blocked = hass.states.get("switch.block_client_1") assert blocked is None mock_unifi_websocket( data={ "meta": {"message": "sta:sync"}, "data": [BLOCKED], } ) await hass.async_block_till_done() assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 0 mock_unifi_websocket( data={ "meta": {"message": MESSAGE_EVENT}, "data": [EVENT_BLOCKED_CLIENT_CONNECTED], } ) await hass.async_block_till_done() assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 1 blocked = hass.states.get("switch.block_client_1") assert blocked is not None async def test_option_block_clients(hass, aioclient_mock): """Test the changes to option reflects accordingly.""" config_entry = await setup_unifi_integration( hass, aioclient_mock, options={CONF_BLOCK_CLIENT: [BLOCKED["mac"]]}, clients_all_response=[BLOCKED, UNBLOCKED], ) assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 1 # Add a second switch hass.config_entries.async_update_entry( config_entry, options={CONF_BLOCK_CLIENT: [BLOCKED["mac"], UNBLOCKED["mac"]]}, ) await hass.async_block_till_done() assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 1 # Remove the second switch again hass.config_entries.async_update_entry( config_entry, options={CONF_BLOCK_CLIENT: [BLOCKED["mac"]]}, ) await hass.async_block_till_done() assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 1 # Enable one and remove another one hass.config_entries.async_update_entry( config_entry, options={CONF_BLOCK_CLIENT: [UNBLOCKED["mac"]]}, ) await hass.async_block_till_done() assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 0 # Remove one hass.config_entries.async_update_entry( config_entry, options={CONF_BLOCK_CLIENT: []}, ) await hass.async_block_till_done() assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 0 async def test_option_remove_switches(hass, aioclient_mock): """Test removal of DPI switch when options updated.""" config_entry = await setup_unifi_integration( hass, aioclient_mock, options={ CONF_TRACK_CLIENTS: False, CONF_TRACK_DEVICES: False, }, clients_response=[CLIENT_1], devices_response=[DEVICE_1], dpigroup_response=DPI_GROUPS, dpiapp_response=DPI_APPS, ) assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 2 # Disable DPI Switches hass.config_entries.async_update_entry( config_entry, options={CONF_DPI_RESTRICTIONS: False, CONF_POE_CLIENTS: False}, ) await hass.async_block_till_done() assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 0 async def test_new_client_discovered_on_poe_control( hass, aioclient_mock, mock_unifi_websocket ): """Test if 2nd update has a new client.""" config_entry = await setup_unifi_integration( hass, aioclient_mock, options={CONF_TRACK_CLIENTS: False, CONF_TRACK_DEVICES: False}, clients_response=[CLIENT_1], devices_response=[DEVICE_1], ) controller = hass.data[UNIFI_DOMAIN][config_entry.entry_id] assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 1 mock_unifi_websocket( data={ "meta": {"message": "sta:sync"}, "data": [CLIENT_2], } ) await hass.async_block_till_done() assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 1 mock_unifi_websocket( data={ "meta": {"message": MESSAGE_EVENT}, "data": [EVENT_CLIENT_2_CONNECTED], } ) await hass.async_block_till_done() assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 2 switch_2 = hass.states.get("switch.poe_client_2") assert switch_2 is not None aioclient_mock.put( f"https://{controller.host}:1234/api/s/{controller.site}/rest/device/mock-id", ) await hass.services.async_call( SWITCH_DOMAIN, "turn_off", {"entity_id": "switch.poe_client_1"}, blocking=True ) assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 2 assert aioclient_mock.call_count == 11 assert aioclient_mock.mock_calls[10][2] == { "port_overrides": [{"port_idx": 1, "portconf_id": "1a1", "poe_mode": "off"}] } await hass.services.async_call( SWITCH_DOMAIN, "turn_on", {"entity_id": "switch.poe_client_1"}, blocking=True ) assert aioclient_mock.call_count == 12 assert aioclient_mock.mock_calls[11][2] == { "port_overrides": [{"port_idx": 1, "portconf_id": "1a1", "poe_mode": "auto"}] } async def test_ignore_multiple_poe_clients_on_same_port(hass, aioclient_mock): """Ignore when there are multiple POE driven clients on same port. If there is a non-UniFi switch powered by POE, clients will be transparently marked as having POE as well. """ await setup_unifi_integration( hass, aioclient_mock, clients_response=POE_SWITCH_CLIENTS, devices_response=[DEVICE_1], ) assert len(hass.states.async_entity_ids(TRACKER_DOMAIN)) == 3 switch_1 = hass.states.get("switch.poe_client_1") switch_2 = hass.states.get("switch.poe_client_2") assert switch_1 is None assert switch_2 is None async def test_restore_client_succeed(hass, aioclient_mock): """Test that RestoreEntity works as expected.""" POE_DEVICE = { "device_id": "12345", "ip": "1.0.1.1", "mac": "00:00:00:00:01:01", "last_seen": 1562600145, "model": "US16P150", "name": "POE Switch", "port_overrides": [ { "poe_mode": "off", "port_idx": 1, "portconf_id": "5f3edd2aba4cc806a19f2db2", } ], "port_table": [ { "media": "GE", "name": "Port 1", "op_mode": "switch", "poe_caps": 7, "poe_class": "Unknown", "poe_current": "0.00", "poe_enable": False, "poe_good": False, "poe_mode": "off", "poe_power": "0.00", "poe_voltage": "0.00", "port_idx": 1, "port_poe": True, "portconf_id": "5f3edd2aba4cc806a19f2db2", "up": False, }, ], "state": 1, "type": "usw", "version": "4.0.42.10433", } POE_CLIENT = { "hostname": "poe_client", "ip": "1.0.0.1", "is_wired": True, "last_seen": 1562600145, "mac": "00:00:00:00:00:01", "name": "POE Client", "oui": "Producer", } fake_state = core.State( "switch.poe_client", "off", { "power": "0.00", "switch": POE_DEVICE["mac"], "port": 1, "poe_mode": "auto", }, ) config_entry = config_entries.ConfigEntry( version=1, domain=UNIFI_DOMAIN, title="Mock Title", data=ENTRY_CONFIG, source="test", options={}, entry_id=DEFAULT_CONFIG_ENTRY_ID, ) registry = er.async_get(hass) registry.async_get_or_create( SWITCH_DOMAIN, UNIFI_DOMAIN, f'{POE_SWITCH}-{POE_CLIENT['mac']}', suggested_object_id=POE_CLIENT["hostname"], config_entry=config_entry, ) with patch( "homeassistant.helpers.restore_state.RestoreEntity.async_get_last_state", return_value=fake_state, ): await setup_unifi_integration( hass, aioclient_mock, options={ CONF_TRACK_CLIENTS: False, CONF_TRACK_DEVICES: False, }, clients_response=[], devices_response=[POE_DEVICE], clients_all_response=[POE_CLIENT], ) assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 1 poe_client = hass.states.get("switch.poe_client") assert poe_client.state == "off" async def test_restore_client_no_old_state(hass, aioclient_mock): """Test that RestoreEntity without old state makes entity unavailable.""" POE_DEVICE = { "device_id": "12345", "ip": "1.0.1.1", "mac": "00:00:00:00:01:01", "last_seen": 1562600145, "model": "US16P150", "name": "POE Switch", "port_overrides": [ { "poe_mode": "off", "port_idx": 1, "portconf_id": "5f3edd2aba4cc806a19f2db2", } ], "port_table": [ { "media": "GE", "name": "Port 1", "op_mode": "switch", "poe_caps": 7, "poe_class": "Unknown", "poe_current": "0.00", "poe_enable": False, "poe_good": False, "poe_mode": "off", "poe_power": "0.00", "poe_voltage": "0.00", "port_idx": 1, "port_poe": True, "portconf_id": "5f3edd2aba4cc806a19f2db2", "up": False, }, ], "state": 1, "type": "usw", "version": "4.0.42.10433", } POE_CLIENT = { "hostname": "poe_client", "ip": "1.0.0.1", "is_wired": True, "last_seen": 1562600145, "mac": "00:00:00:00:00:01", "name": "POE Client", "oui": "Producer", } config_entry = config_entries.ConfigEntry( version=1, domain=UNIFI_DOMAIN, title="Mock Title", data=ENTRY_CONFIG, source="test", options={}, entry_id=DEFAULT_CONFIG_ENTRY_ID, ) registry = er.async_get(hass) registry.async_get_or_create( SWITCH_DOMAIN, UNIFI_DOMAIN, f'{POE_SWITCH}-{POE_CLIENT['mac']}', suggested_object_id=POE_CLIENT["hostname"], config_entry=config_entry, ) await setup_unifi_integration( hass, aioclient_mock, options={ CONF_TRACK_CLIENTS: False, CONF_TRACK_DEVICES: False, }, clients_response=[], devices_response=[POE_DEVICE], clients_all_response=[POE_CLIENT], ) assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 1 poe_client = hass.states.get("switch.poe_client") assert poe_client.state == "unavailable" # self.poe_mode is None
"""UniFi switch platform tests.""" from copy import deepcopy from unittest.mock import patch from aiounifi.controller import MESSAGE_CLIENT_REMOVED, MESSAGE_EVENT from homeassistant import config_entries, core from homeassistant.components.device_tracker import DOMAIN as TRACKER_DOMAIN from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN from homeassistant.components.unifi.const import ( CONF_BLOCK_CLIENT, CONF_DPI_RESTRICTIONS, CONF_POE_CLIENTS, CONF_TRACK_CLIENTS, CONF_TRACK_DEVICES, DOMAIN as UNIFI_DOMAIN, ) from homeassistant.components.unifi.switch import POE_SWITCH from homeassistant.const import ENTITY_CATEGORY_CONFIG, STATE_OFF, STATE_ON from homeassistant.helpers import entity_registry as er from homeassistant.helpers.dispatcher import async_dispatcher_send from .test_controller import ( CONTROLLER_HOST, DEFAULT_CONFIG_ENTRY_ID, DESCRIPTION, ENTRY_CONFIG, setup_unifi_integration, ) CLIENT_1 = { "hostname": "client_1", "ip": "10.0.0.1", "is_wired": True, "last_seen": 1562600145, "mac": "00:00:00:00:00:01", "name": "POE Client 1", "oui": "Producer", "sw_mac": "00:00:00:00:01:01", "sw_port": 1, "wired-rx_bytes": 1234000000, "wired-tx_bytes": 5678000000, } CLIENT_2 = { "hostname": "client_2", "ip": "10.0.0.2", "is_wired": True, "last_seen": 1562600145, "mac": "00:00:00:00:00:02", "name": "POE Client 2", "oui": "Producer", "sw_mac": "00:00:00:00:01:01", "sw_port": 2, "wired-rx_bytes": 1234000000, "wired-tx_bytes": 5678000000, } CLIENT_3 = { "hostname": "client_3", "ip": "10.0.0.3", "is_wired": True, "last_seen": 1562600145, "mac": "00:00:00:00:00:03", "name": "Non-POE Client 3", "oui": "Producer", "sw_mac": "00:00:00:00:01:01", "sw_port": 3, "wired-rx_bytes": 1234000000, "wired-tx_bytes": 5678000000, } CLIENT_4 = { "hostname": "client_4", "ip": "10.0.0.4", "is_wired": True, "last_seen": 1562600145, "mac": "00:00:00:00:00:04", "name": "Non-POE Client 4", "oui": "Producer", "sw_mac": "00:00:00:00:01:01", "sw_port": 4, "wired-rx_bytes": 1234000000, "wired-tx_bytes": 5678000000, } POE_SWITCH_CLIENTS = [ { "hostname": "client_1", "ip": "10.0.0.1", "is_wired": True, "last_seen": 1562600145, "mac": "00:00:00:00:00:01", "name": "POE Client 1", "oui": "Producer", "sw_mac": "00:00:00:00:01:01", "sw_port": 1, "wired-rx_bytes": 1234000000, "wired-tx_bytes": 5678000000, }, { "hostname": "client_2", "ip": "10.0.0.2", "is_wired": True, "last_seen": 1562600145, "mac": "00:00:00:00:00:02", "name": "POE Client 2", "oui": "Producer", "sw_mac": "00:00:00:00:01:01", "sw_port": 1, "wired-rx_bytes": 1234000000, "wired-tx_bytes": 5678000000, }, ] DEVICE_1 = { "device_id": "mock-id", "ip": "10.0.1.1", "mac": "00:00:00:00:01:01", "last_seen": 1562600145, "model": "US16P150", "name": "mock-name", "port_overrides": [], "port_table": [ { "media": "GE", "name": "Port 1", "port_idx": 1, "poe_class": "Class 4", "poe_enable": True, "poe_mode": "auto", "poe_power": "2.56", "poe_voltage": "53.40", "portconf_id": "1a1", "port_poe": True, "up": True, }, { "media": "GE", "name": "Port 2", "port_idx": 2, "poe_class": "Class 4", "poe_enable": True, "poe_mode": "auto", "poe_power": "2.56", "poe_voltage": "53.40", "portconf_id": "1a2", "port_poe": True, "up": True, }, { "media": "GE", "name": "Port 3", "port_idx": 3, "poe_class": "Unknown", "poe_enable": False, "poe_mode": "off", "poe_power": "0.00", "poe_voltage": "0.00", "portconf_id": "1a3", "port_poe": False, "up": True, }, { "media": "GE", "name": "Port 4", "port_idx": 4, "poe_class": "Unknown", "poe_enable": False, "poe_mode": "auto", "poe_power": "0.00", "poe_voltage": "0.00", "portconf_id": "1a4", "port_poe": True, "up": True, }, ], "state": 1, "type": "usw", "version": "4.0.42.10433", } BLOCKED = { "blocked": True, "hostname": "block_client_1", "ip": "10.0.0.1", "is_guest": False, "is_wired": False, "last_seen": 1562600145, "mac": "00:00:00:00:01:01", "name": "Block Client 1", "noted": True, "oui": "Producer", } UNBLOCKED = { "blocked": False, "hostname": "block_client_2", "ip": "10.0.0.2", "is_guest": False, "is_wired": True, "last_seen": 1562600145, "mac": "00:00:00:00:01:02", "name": "Block Client 2", "noted": True, "oui": "Producer", } EVENT_BLOCKED_CLIENT_CONNECTED = { "user": BLOCKED["mac"], "radio": "na", "channel": "44", "hostname": BLOCKED["hostname"], "key": "EVT_WU_Connected", "subsystem": "wlan", "site_id": "name", "time": 1587753456179, "datetime": "2020-04-24T18:37:36Z", "msg": f'User{[BLOCKED["mac"]]} has connected."', "_id": "5ea331fa30c49e00f90ddc1a", } EVENT_BLOCKED_CLIENT_BLOCKED = { "user": BLOCKED["mac"], "hostname": BLOCKED["hostname"], "key": "EVT_WC_Blocked", "subsystem": "wlan", "site_id": "name", "time": 1587753456179, "datetime": "2020-04-24T18:37:36Z", "msg": f'User{[BLOCKED["mac"]]} has been blocked."', "_id": "5ea331fa30c49e00f90ddc1a", } EVENT_BLOCKED_CLIENT_UNBLOCKED = { "user": BLOCKED["mac"], "hostname": BLOCKED["hostname"], "key": "EVT_WC_Unblocked", "subsystem": "wlan", "site_id": "name", "time": 1587753456179, "datetime": "2020-04-24T18:37:36Z", "msg": f'User{[BLOCKED["mac"]]} has been unblocked."', "_id": "5ea331fa30c49e00f90ddc1a", } EVENT_CLIENT_2_CONNECTED = { "user": CLIENT_2["mac"], "radio": "na", "channel": "44", "hostname": CLIENT_2["hostname"], "key": "EVT_WU_Connected", "subsystem": "wlan", "site_id": "name", "time": 1587753456179, "datetime": "2020-04-24T18:37:36Z", "msg": f'User{[CLIENT_2["mac"]]} has connected."', "_id": "5ea331fa30c49e00f90ddc1a", } DPI_GROUPS = [ { "_id": "5ba29dd8e3c58f026e9d7c4a", "attr_no_delete": True, "attr_hidden_id": "Default", "name": "Default", "site_id": "name", }, { "_id": "5f976f4ae3c58f018ec7dff6", "name": "Block Media Streaming", "site_id": "name", "dpiapp_ids": ["5f976f62e3c58f018ec7e17d"], }, ] DPI_APPS = [ { "_id": "5f976f62e3c58f018ec7e17d", "apps": [], "blocked": True, "cats": ["4"], "enabled": True, "log": True, "site_id": "name", } ] DPI_GROUP_REMOVED_EVENT = { "meta": {"rc": "ok", "message": "dpigroup:delete"}, "data": [ { "_id": "5f976f4ae3c58f018ec7dff6", "name": "dpi group", "site_id": "name", "dpiapp_ids": [], } ], } DPI_APP_DISABLED_EVENT = { "meta": {"rc": "ok", "message": "dpiapp:sync"}, "data": [ { "_id": "5f976f62e3c58f018ec7e17d", "apps": [], "blocked": False, "cats": [], "enabled": False, "log": False, "site_id": "name", } ], } async def test_no_clients(hass, aioclient_mock): """Test the update_clients function when no clients are found.""" await setup_unifi_integration( hass, aioclient_mock, options={ CONF_TRACK_CLIENTS: False, CONF_TRACK_DEVICES: False, CONF_DPI_RESTRICTIONS: False, }, ) assert aioclient_mock.call_count == 10 assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 0 async def test_controller_not_client(hass, aioclient_mock): """Test that the controller doesn't become a switch.""" await setup_unifi_integration( hass, aioclient_mock, options={CONF_TRACK_CLIENTS: False, CONF_TRACK_DEVICES: False}, clients_response=[CONTROLLER_HOST], devices_response=[DEVICE_1], ) assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 0 cloudkey = hass.states.get("switch.cloud_key") assert cloudkey is None async def test_not_admin(hass, aioclient_mock): """Test that switch platform only work on an admin account.""" description = deepcopy(DESCRIPTION) description[0]["site_role"] = "not admin" await setup_unifi_integration( hass, aioclient_mock, options={CONF_TRACK_CLIENTS: False, CONF_TRACK_DEVICES: False}, site_description=description, clients_response=[CLIENT_1], devices_response=[DEVICE_1], ) assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 0 async def test_switches(hass, aioclient_mock): """Test the update_items function with some clients.""" config_entry = await setup_unifi_integration( hass, aioclient_mock, options={ CONF_BLOCK_CLIENT: [BLOCKED["mac"], UNBLOCKED["mac"]], CONF_TRACK_CLIENTS: False, CONF_TRACK_DEVICES: False, }, clients_response=[CLIENT_1, CLIENT_4], devices_response=[DEVICE_1], clients_all_response=[BLOCKED, UNBLOCKED, CLIENT_1], dpigroup_response=DPI_GROUPS, dpiapp_response=DPI_APPS, ) controller = hass.data[UNIFI_DOMAIN][config_entry.entry_id] assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 4 switch_1 = hass.states.get("switch.poe_client_1") assert switch_1 is not None assert switch_1.state == "on" assert switch_1.attributes["power"] == "2.56" assert switch_1.attributes[SWITCH_DOMAIN] == "00:00:00:00:01:01" assert switch_1.attributes["port"] == 1 assert switch_1.attributes["poe_mode"] == "auto" switch_4 = hass.states.get("switch.poe_client_4") assert switch_4 is None blocked = hass.states.get("switch.block_client_1") assert blocked is not None assert blocked.state == "off" unblocked = hass.states.get("switch.block_client_2") assert unblocked is not None assert unblocked.state == "on" dpi_switch = hass.states.get("switch.block_media_streaming") assert dpi_switch is not None assert dpi_switch.state == "on" assert dpi_switch.attributes["icon"] == "mdi:network" ent_reg = er.async_get(hass) for entry_id in ( "switch.poe_client_1", "switch.block_client_1", "switch.block_media_streaming", ): assert ent_reg.async_get(entry_id).entity_category == ENTITY_CATEGORY_CONFIG # Block and unblock client aioclient_mock.post( f"https://{controller.host}:1234/api/s/{controller.site}/cmd/stamgr", ) await hass.services.async_call( SWITCH_DOMAIN, "turn_off", {"entity_id": "switch.block_client_1"}, blocking=True ) assert aioclient_mock.call_count == 11 assert aioclient_mock.mock_calls[10][2] == { "mac": "00:00:00:00:01:01", "cmd": "block-sta", } await hass.services.async_call( SWITCH_DOMAIN, "turn_on", {"entity_id": "switch.block_client_1"}, blocking=True ) assert aioclient_mock.call_count == 12 assert aioclient_mock.mock_calls[11][2] == { "mac": "00:00:00:00:01:01", "cmd": "unblock-sta", } # Enable and disable DPI aioclient_mock.put( f"https://{controller.host}:1234/api/s/{controller.site}/rest/dpiapp/5f976f62e3c58f018ec7e17d", ) await hass.services.async_call( SWITCH_DOMAIN, "turn_off", {"entity_id": "switch.block_media_streaming"}, blocking=True, ) assert aioclient_mock.call_count == 13 assert aioclient_mock.mock_calls[12][2] == {"enabled": False} await hass.services.async_call( SWITCH_DOMAIN, "turn_on", {"entity_id": "switch.block_media_streaming"}, blocking=True, ) assert aioclient_mock.call_count == 14 assert aioclient_mock.mock_calls[13][2] == {"enabled": True} # Make sure no duplicates arise on generic signal update async_dispatcher_send(hass, controller.signal_update) await hass.async_block_till_done() assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 4 async def test_remove_switches(hass, aioclient_mock, mock_unifi_websocket): """Test the update_items function with some clients.""" await setup_unifi_integration( hass, aioclient_mock, options={CONF_BLOCK_CLIENT: [UNBLOCKED["mac"]]}, clients_response=[CLIENT_1, UNBLOCKED], devices_response=[DEVICE_1], dpigroup_response=DPI_GROUPS, dpiapp_response=DPI_APPS, ) assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 3 assert hass.states.get("switch.poe_client_1") is not None assert hass.states.get("switch.block_client_2") is not None assert hass.states.get("switch.block_media_streaming") is not None mock_unifi_websocket( data={ "meta": {"message": MESSAGE_CLIENT_REMOVED}, "data": [CLIENT_1, UNBLOCKED], } ) await hass.async_block_till_done() assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 1 assert hass.states.get("switch.poe_client_1") is None assert hass.states.get("switch.block_client_2") is None assert hass.states.get("switch.block_media_streaming") is not None mock_unifi_websocket(data=DPI_GROUP_REMOVED_EVENT) await hass.async_block_till_done() await hass.async_block_till_done() assert hass.states.get("switch.block_media_streaming") is None assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 0 async def test_block_switches(hass, aioclient_mock, mock_unifi_websocket): """Test the update_items function with some clients.""" config_entry = await setup_unifi_integration( hass, aioclient_mock, options={ CONF_BLOCK_CLIENT: [BLOCKED["mac"], UNBLOCKED["mac"]], CONF_TRACK_CLIENTS: False, CONF_TRACK_DEVICES: False, }, clients_response=[UNBLOCKED], clients_all_response=[BLOCKED], ) controller = hass.data[UNIFI_DOMAIN][config_entry.entry_id] assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 2 blocked = hass.states.get("switch.block_client_1") assert blocked is not None assert blocked.state == "off" unblocked = hass.states.get("switch.block_client_2") assert unblocked is not None assert unblocked.state == "on" mock_unifi_websocket( data={ "meta": {"message": MESSAGE_EVENT}, "data": [EVENT_BLOCKED_CLIENT_UNBLOCKED], } ) await hass.async_block_till_done() assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 2 blocked = hass.states.get("switch.block_client_1") assert blocked is not None assert blocked.state == "on" mock_unifi_websocket( data={ "meta": {"message": MESSAGE_EVENT}, "data": [EVENT_BLOCKED_CLIENT_BLOCKED], } ) await hass.async_block_till_done() assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 2 blocked = hass.states.get("switch.block_client_1") assert blocked is not None assert blocked.state == "off" aioclient_mock.post( f"https://{controller.host}:1234/api/s/{controller.site}/cmd/stamgr", ) await hass.services.async_call( SWITCH_DOMAIN, "turn_off", {"entity_id": "switch.block_client_1"}, blocking=True ) assert aioclient_mock.call_count == 11 assert aioclient_mock.mock_calls[10][2] == { "mac": "00:00:00:00:01:01", "cmd": "block-sta", } await hass.services.async_call( SWITCH_DOMAIN, "turn_on", {"entity_id": "switch.block_client_1"}, blocking=True ) assert aioclient_mock.call_count == 12 assert aioclient_mock.mock_calls[11][2] == { "mac": "00:00:00:00:01:01", "cmd": "unblock-sta", } async def test_dpi_switches(hass, aioclient_mock, mock_unifi_websocket): """Test the update_items function with some clients.""" await setup_unifi_integration( hass, aioclient_mock, dpigroup_response=DPI_GROUPS, dpiapp_response=DPI_APPS, ) assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 1 dpi_switch = hass.states.get("switch.block_media_streaming") assert dpi_switch is not None assert dpi_switch.state == STATE_ON assert dpi_switch.attributes["icon"] == "mdi:network" mock_unifi_websocket(data=DPI_APP_DISABLED_EVENT) await hass.async_block_till_done() assert hass.states.get("switch.block_media_streaming").state == STATE_OFF async def test_new_client_discovered_on_block_control( hass, aioclient_mock, mock_unifi_websocket ): """Test if 2nd update has a new client.""" await setup_unifi_integration( hass, aioclient_mock, options={ CONF_BLOCK_CLIENT: [BLOCKED["mac"]], CONF_TRACK_CLIENTS: False, CONF_TRACK_DEVICES: False, CONF_DPI_RESTRICTIONS: False, }, ) assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 0 blocked = hass.states.get("switch.block_client_1") assert blocked is None mock_unifi_websocket( data={ "meta": {"message": "sta:sync"}, "data": [BLOCKED], } ) await hass.async_block_till_done() assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 0 mock_unifi_websocket( data={ "meta": {"message": MESSAGE_EVENT}, "data": [EVENT_BLOCKED_CLIENT_CONNECTED], } ) await hass.async_block_till_done() assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 1 blocked = hass.states.get("switch.block_client_1") assert blocked is not None async def test_option_block_clients(hass, aioclient_mock): """Test the changes to option reflects accordingly.""" config_entry = await setup_unifi_integration( hass, aioclient_mock, options={CONF_BLOCK_CLIENT: [BLOCKED["mac"]]}, clients_all_response=[BLOCKED, UNBLOCKED], ) assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 1 # Add a second switch hass.config_entries.async_update_entry( config_entry, options={CONF_BLOCK_CLIENT: [BLOCKED["mac"], UNBLOCKED["mac"]]}, ) await hass.async_block_till_done() assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 1 # Remove the second switch again hass.config_entries.async_update_entry( config_entry, options={CONF_BLOCK_CLIENT: [BLOCKED["mac"]]}, ) await hass.async_block_till_done() assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 1 # Enable one and remove another one hass.config_entries.async_update_entry( config_entry, options={CONF_BLOCK_CLIENT: [UNBLOCKED["mac"]]}, ) await hass.async_block_till_done() assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 0 # Remove one hass.config_entries.async_update_entry( config_entry, options={CONF_BLOCK_CLIENT: []}, ) await hass.async_block_till_done() assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 0 async def test_option_remove_switches(hass, aioclient_mock): """Test removal of DPI switch when options updated.""" config_entry = await setup_unifi_integration( hass, aioclient_mock, options={ CONF_TRACK_CLIENTS: False, CONF_TRACK_DEVICES: False, }, clients_response=[CLIENT_1], devices_response=[DEVICE_1], dpigroup_response=DPI_GROUPS, dpiapp_response=DPI_APPS, ) assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 2 # Disable DPI Switches hass.config_entries.async_update_entry( config_entry, options={CONF_DPI_RESTRICTIONS: False, CONF_POE_CLIENTS: False}, ) await hass.async_block_till_done() assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 0 async def test_new_client_discovered_on_poe_control( hass, aioclient_mock, mock_unifi_websocket ): """Test if 2nd update has a new client.""" config_entry = await setup_unifi_integration( hass, aioclient_mock, options={CONF_TRACK_CLIENTS: False, CONF_TRACK_DEVICES: False}, clients_response=[CLIENT_1], devices_response=[DEVICE_1], ) controller = hass.data[UNIFI_DOMAIN][config_entry.entry_id] assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 1 mock_unifi_websocket( data={ "meta": {"message": "sta:sync"}, "data": [CLIENT_2], } ) await hass.async_block_till_done() assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 1 mock_unifi_websocket( data={ "meta": {"message": MESSAGE_EVENT}, "data": [EVENT_CLIENT_2_CONNECTED], } ) await hass.async_block_till_done() assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 2 switch_2 = hass.states.get("switch.poe_client_2") assert switch_2 is not None aioclient_mock.put( f"https://{controller.host}:1234/api/s/{controller.site}/rest/device/mock-id", ) await hass.services.async_call( SWITCH_DOMAIN, "turn_off", {"entity_id": "switch.poe_client_1"}, blocking=True ) assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 2 assert aioclient_mock.call_count == 11 assert aioclient_mock.mock_calls[10][2] == { "port_overrides": [{"port_idx": 1, "portconf_id": "1a1", "poe_mode": "off"}] } await hass.services.async_call( SWITCH_DOMAIN, "turn_on", {"entity_id": "switch.poe_client_1"}, blocking=True ) assert aioclient_mock.call_count == 12 assert aioclient_mock.mock_calls[11][2] == { "port_overrides": [{"port_idx": 1, "portconf_id": "1a1", "poe_mode": "auto"}] } async def test_ignore_multiple_poe_clients_on_same_port(hass, aioclient_mock): """Ignore when there are multiple POE driven clients on same port. If there is a non-UniFi switch powered by POE, clients will be transparently marked as having POE as well. """ await setup_unifi_integration( hass, aioclient_mock, clients_response=POE_SWITCH_CLIENTS, devices_response=[DEVICE_1], ) assert len(hass.states.async_entity_ids(TRACKER_DOMAIN)) == 3 switch_1 = hass.states.get("switch.poe_client_1") switch_2 = hass.states.get("switch.poe_client_2") assert switch_1 is None assert switch_2 is None async def test_restore_client_succeed(hass, aioclient_mock): """Test that RestoreEntity works as expected.""" POE_DEVICE = { "device_id": "12345", "ip": "1.0.1.1", "mac": "00:00:00:00:01:01", "last_seen": 1562600145, "model": "US16P150", "name": "POE Switch", "port_overrides": [ { "poe_mode": "off", "port_idx": 1, "portconf_id": "5f3edd2aba4cc806a19f2db2", } ], "port_table": [ { "media": "GE", "name": "Port 1", "op_mode": "switch", "poe_caps": 7, "poe_class": "Unknown", "poe_current": "0.00", "poe_enable": False, "poe_good": False, "poe_mode": "off", "poe_power": "0.00", "poe_voltage": "0.00", "port_idx": 1, "port_poe": True, "portconf_id": "5f3edd2aba4cc806a19f2db2", "up": False, }, ], "state": 1, "type": "usw", "version": "4.0.42.10433", } POE_CLIENT = { "hostname": "poe_client", "ip": "1.0.0.1", "is_wired": True, "last_seen": 1562600145, "mac": "00:00:00:00:00:01", "name": "POE Client", "oui": "Producer", } fake_state = core.State( "switch.poe_client", "off", { "power": "0.00", "switch": POE_DEVICE["mac"], "port": 1, "poe_mode": "auto", }, ) config_entry = config_entries.ConfigEntry( version=1, domain=UNIFI_DOMAIN, title="Mock Title", data=ENTRY_CONFIG, source="test", options={}, entry_id=DEFAULT_CONFIG_ENTRY_ID, ) registry = er.async_get(hass) registry.async_get_or_create( SWITCH_DOMAIN, UNIFI_DOMAIN, f'{POE_SWITCH}-{POE_CLIENT["mac"]}', suggested_object_id=POE_CLIENT["hostname"], config_entry=config_entry, ) with patch( "homeassistant.helpers.restore_state.RestoreEntity.async_get_last_state", return_value=fake_state, ): await setup_unifi_integration( hass, aioclient_mock, options={ CONF_TRACK_CLIENTS: False, CONF_TRACK_DEVICES: False, }, clients_response=[], devices_response=[POE_DEVICE], clients_all_response=[POE_CLIENT], ) assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 1 poe_client = hass.states.get("switch.poe_client") assert poe_client.state == "off" async def test_restore_client_no_old_state(hass, aioclient_mock): """Test that RestoreEntity without old state makes entity unavailable.""" POE_DEVICE = { "device_id": "12345", "ip": "1.0.1.1", "mac": "00:00:00:00:01:01", "last_seen": 1562600145, "model": "US16P150", "name": "POE Switch", "port_overrides": [ { "poe_mode": "off", "port_idx": 1, "portconf_id": "5f3edd2aba4cc806a19f2db2", } ], "port_table": [ { "media": "GE", "name": "Port 1", "op_mode": "switch", "poe_caps": 7, "poe_class": "Unknown", "poe_current": "0.00", "poe_enable": False, "poe_good": False, "poe_mode": "off", "poe_power": "0.00", "poe_voltage": "0.00", "port_idx": 1, "port_poe": True, "portconf_id": "5f3edd2aba4cc806a19f2db2", "up": False, }, ], "state": 1, "type": "usw", "version": "4.0.42.10433", } POE_CLIENT = { "hostname": "poe_client", "ip": "1.0.0.1", "is_wired": True, "last_seen": 1562600145, "mac": "00:00:00:00:00:01", "name": "POE Client", "oui": "Producer", } config_entry = config_entries.ConfigEntry( version=1, domain=UNIFI_DOMAIN, title="Mock Title", data=ENTRY_CONFIG, source="test", options={}, entry_id=DEFAULT_CONFIG_ENTRY_ID, ) registry = er.async_get(hass) registry.async_get_or_create( SWITCH_DOMAIN, UNIFI_DOMAIN, f'{POE_SWITCH}-{POE_CLIENT["mac"]}', suggested_object_id=POE_CLIENT["hostname"], config_entry=config_entry, ) await setup_unifi_integration( hass, aioclient_mock, options={ CONF_TRACK_CLIENTS: False, CONF_TRACK_DEVICES: False, }, clients_response=[], devices_response=[POE_DEVICE], clients_all_response=[POE_CLIENT], ) assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 1 poe_client = hass.states.get("switch.poe_client") assert poe_client.state == "unavailable" # self.poe_mode is None
import pathlib import tensorflow as tf import tensorflow_datasets as tfds from dataduit.log.dataduit_logging import config_logger from dataduit.dataset.io.read.location.local.records.parse import return_parse_feature def read_tf_from_dir(config_dict): logger = config_logger(config_dict["meta"]["logging"], "download") logger.debug(f"obtain_datasets({config_dict}") try: root_dir = config_dict["meta"]["root_location"] except KeyError: raise KeyError(f"no dataset meta:root_location name specified") try: dataset_name = config_dict["meta"]["name"] except KeyError: # TODO: list names in the root_location raise KeyError(f"no dataset meta:name name specified") try: stage = config_dict["read"]["from_stage"] except KeyError: # TODO: list names in the root_location raise KeyError(f"no dataset meta:name name specified") try: split_percents = config_dict["read"]["split_percents"] except KeyError: raise KeyError( f"no split specified. Please specify a split. an example may be {[75, 15, 10]}" ) try: split_names = config_dict["read"]["split_names"] except KeyError: raise KeyError( f"no split specified. Please specify a split. an example may be {["train", "val", "test"]}" ) assert len(split_percents) == len( split_names ), f"dataset percents(len:{len(split_percents)})and names(len:{len(split_names)}) don't match splits({split_percents}), names({split_names})" records_dir = pathlib.Path(root_dir).joinpath(dataset_name).joinpath(stage) if not records_dir.is_dir(): raise ValueError(f"indicated directory does not exist: {records_dir}") logger.info(f"records_dir set to {records_dir}") # create splits # TODO: ensure this: # 1) shuffles # 2) is consistent each call # ds_split_percents = tfds.Split.TRAIN.subsplit(split_percents) # create dataset datasets = {} # for i, ds_split_percent in enumerate(ds_split_percents): # cur_ds = tfds.load( # dataset_name, # data_dir=records_dir, # split=ds_split_percent, # as_supervised=True, # ) # datasets[split_names[i]] = cur_ds # TODO: is this the right way to resolve the path to string? # print(list(records_dir.glob("*"))) file_paths = [str(fp) for fp in list(records_dir.glob("*"))] SEED = 42 filepath_dataset = tf.data.Dataset.list_files(file_paths, seed=SEED) # TODO: interesting example: https://www.tensorflow.org/api_docs/python/tf/data/TFRecordDataset?version=stable # d = d.filter(lambda x: x < 3) full_dataset = filepath_dataset.interleave( lambda filepath: tf.data.TFRecordDataset(filepath), cycle_length=tf.data.experimental.AUTOTUNE, ) try: keys = config_dict["read"]["iterate"]["schema"].keys() except KeyError: raise KeyError("no keys specified by read:iterate:schema") feature_description = {} for k in keys: try: feat_names = config_dict["read"]["iterate"]["schema"][k].keys() except KeyError: raise KeyError( f"no feature names described by read:iterate:schema ({config_dict["read"]["iterate"]})" ) for feat in feat_names: try: dt_conf = config_dict["read"]["iterate"]["schema"][k][feat]["datatype"] except KeyError: raise KeyError( f"no datatype config defined for key {k}, feat {feat}: {config_dict["read"]["iterate"]["schema"]}" ) feature_description[feat] = return_parse_feature(dt_conf) def _parse_function(example_proto): # Parse the input `tf.Example` proto using the dictionary above. return tf.io.parse_single_example(example_proto, feature_description) full_dataset = full_dataset.map(_parse_function) def _decode(example_proto): # decode the values # NOTE: may convert to more explicit decode_<img_type> example_proto["image"] = tf.io.decode_image(example_proto["image"].values[0]) return example_proto full_dataset = full_dataset.map(_decode) # return logic try: r_type = config_dict["read"]["iterate"]["return_type"] except KeyError: r_type = None def _output_as_tuple(example_proto, keys): o = [] for k in keys: o.append(example_proto[k]) return tf.tuple(o) if r_type == "tuple": # TODO: this ...works... but it will need to be profiled and optimized # particularly the part in _output_as_tuple where we iterate over the keys identifiers = [] for k in keys: identifiers.extend(list(config_dict["read"]["iterate"]["schema"][k].keys())) full_dataset = full_dataset.map(lambda x: _output_as_tuple(x, identifiers)) # TODO: JACK datasets["train"] = full_dataset return datasets
import pathlib import tensorflow as tf import tensorflow_datasets as tfds from dataduit.log.dataduit_logging import config_logger from dataduit.dataset.io.read.location.local.records.parse import return_parse_feature def read_tf_from_dir(config_dict): logger = config_logger(config_dict["meta"]["logging"], "download") logger.debug(f"obtain_datasets({config_dict}") try: root_dir = config_dict["meta"]["root_location"] except KeyError: raise KeyError(f"no dataset meta:root_location name specified") try: dataset_name = config_dict["meta"]["name"] except KeyError: # TODO: list names in the root_location raise KeyError(f"no dataset meta:name name specified") try: stage = config_dict["read"]["from_stage"] except KeyError: # TODO: list names in the root_location raise KeyError(f"no dataset meta:name name specified") try: split_percents = config_dict["read"]["split_percents"] except KeyError: raise KeyError( f"no split specified. Please specify a split. an example may be {[75, 15, 10]}" ) try: split_names = config_dict["read"]["split_names"] except KeyError: raise KeyError( f"no split specified. Please specify a split. an example may be {['train', 'val', 'test']}" ) assert len(split_percents) == len( split_names ), f"dataset percents(len:{len(split_percents)})and names(len:{len(split_names)}) don't match splits({split_percents}), names({split_names})" records_dir = pathlib.Path(root_dir).joinpath(dataset_name).joinpath(stage) if not records_dir.is_dir(): raise ValueError(f"indicated directory does not exist: {records_dir}") logger.info(f"records_dir set to {records_dir}") # create splits # TODO: ensure this: # 1) shuffles # 2) is consistent each call # ds_split_percents = tfds.Split.TRAIN.subsplit(split_percents) # create dataset datasets = {} # for i, ds_split_percent in enumerate(ds_split_percents): # cur_ds = tfds.load( # dataset_name, # data_dir=records_dir, # split=ds_split_percent, # as_supervised=True, # ) # datasets[split_names[i]] = cur_ds # TODO: is this the right way to resolve the path to string? # print(list(records_dir.glob("*"))) file_paths = [str(fp) for fp in list(records_dir.glob("*"))] SEED = 42 filepath_dataset = tf.data.Dataset.list_files(file_paths, seed=SEED) # TODO: interesting example: https://www.tensorflow.org/api_docs/python/tf/data/TFRecordDataset?version=stable # d = d.filter(lambda x: x < 3) full_dataset = filepath_dataset.interleave( lambda filepath: tf.data.TFRecordDataset(filepath), cycle_length=tf.data.experimental.AUTOTUNE, ) try: keys = config_dict["read"]["iterate"]["schema"].keys() except KeyError: raise KeyError("no keys specified by read:iterate:schema") feature_description = {} for k in keys: try: feat_names = config_dict["read"]["iterate"]["schema"][k].keys() except KeyError: raise KeyError( f"no feature names described by read:iterate:schema ({config_dict['read']['iterate']})" ) for feat in feat_names: try: dt_conf = config_dict["read"]["iterate"]["schema"][k][feat]["datatype"] except KeyError: raise KeyError( f"no datatype config defined for key {k}, feat {feat}: {config_dict['read']['iterate']['schema']}" ) feature_description[feat] = return_parse_feature(dt_conf) def _parse_function(example_proto): # Parse the input `tf.Example` proto using the dictionary above. return tf.io.parse_single_example(example_proto, feature_description) full_dataset = full_dataset.map(_parse_function) def _decode(example_proto): # decode the values # NOTE: may convert to more explicit decode_<img_type> example_proto["image"] = tf.io.decode_image(example_proto["image"].values[0]) return example_proto full_dataset = full_dataset.map(_decode) # return logic try: r_type = config_dict["read"]["iterate"]["return_type"] except KeyError: r_type = None def _output_as_tuple(example_proto, keys): o = [] for k in keys: o.append(example_proto[k]) return tf.tuple(o) if r_type == "tuple": # TODO: this ...works... but it will need to be profiled and optimized # particularly the part in _output_as_tuple where we iterate over the keys identifiers = [] for k in keys: identifiers.extend(list(config_dict["read"]["iterate"]["schema"][k].keys())) full_dataset = full_dataset.map(lambda x: _output_as_tuple(x, identifiers)) # TODO: JACK datasets["train"] = full_dataset return datasets
import logging from datetime import datetime, timezone from flask import Blueprint from flask import current_app as app from flask import flash, redirect, render_template, request, url_for from flask_login import login_required from flask_paginate import Pagination from iso8601 import parse_date from structlog import wrap_logger from response_operations_ui.common.mappers import map_ce_response_status, map_region from response_operations_ui.controllers import ( case_controller, iac_controller, party_controller, reporting_units_controllers, ) from response_operations_ui.controllers.collection_exercise_controllers import ( get_case_group_status_by_collection_exercise, get_collection_exercise_by_id, ) from response_operations_ui.controllers.survey_controllers import get_survey_by_id from response_operations_ui.forms import EditContactDetailsForm, RuSearchForm logger = wrap_logger(logging.getLogger(__name__)) reporting_unit_bp = Blueprint("reporting_unit_bp", __name__, static_folder="static", template_folder="templates") @reporting_unit_bp.route("/<ru_ref>", methods=["GET"]) @login_required def view_reporting_unit(ru_ref): logger.info("Gathering data to view reporting unit", ru_ref=ru_ref) # Make some initial calls to retrieve some data we'll need reporting_unit = party_controller.get_business_by_ru_ref(ru_ref) cases = case_controller.get_cases_by_business_party_id(reporting_unit["id"]) case_groups = [case["caseGroup"] for case in cases] # Get all collection exercises for retrieved case groups collection_exercise_ids = {case_group["collectionExerciseId"] for case_group in case_groups} collection_exercises = [get_collection_exercise_by_id(ce_id) for ce_id in collection_exercise_ids] live_collection_exercises = [ ce for ce in collection_exercises if parse_date(ce["scheduledStartDateTime"]) < datetime.now(timezone.utc) ] survey_table_data = build_survey_table_data_dict(live_collection_exercises, case_groups) breadcrumbs = create_reporting_unit_breadcrumbs(ru_ref) logger.info("Successfully gathered data to view reporting unit", ru_ref=ru_ref) return render_template("reporting-unit.html", ru=reporting_unit, surveys=survey_table_data, breadcrumbs=breadcrumbs) def build_survey_table_data_dict(collection_exercises: list, case_groups: list) -> list: """ Creates the dictionary of survey & CE information for the front-end table to display :param collection_exercises: A list of collection exercises to add to the table :param case_groups: A list of case groups for the reporting unit :return: A sorted list of survey/CE information to provide to the front-end table """ table_data = {} for ce in collection_exercises: survey = get_survey_by_id(ce["surveyId"]) if survey["surveyRef"] in table_data: # Keep the one with the later go-live date if parse_date(table_data[survey["surveyRef"]]["goLive"]) > parse_date(ce["scheduledStartDateTime"]): continue table_data[survey["surveyRef"]] = { "surveyName": f"{survey["surveyRef"]} {survey["shortName"]}", "surveyId": ce["surveyId"], "shortName": survey["shortName"], "period": ce["exerciseRef"], "goLive": ce["scheduledStartDateTime"], "caseStatus": map_ce_response_status(get_case_group_status_by_collection_exercise(case_groups, ce["id"])), } return sorted(table_data.items(), key=lambda t: t[0]) @reporting_unit_bp.route("/<ru_ref>/respondents", methods=["GET"]) @login_required def view_respondents(ru_ref: str): logger.info("Gathering data to view reporting unit", ru_ref=ru_ref) # Make some initial calls to retrieve some data we'll need reporting_unit = party_controller.get_business_by_ru_ref(ru_ref) # Get all respondents for the given ru respondent_party_ids = [respondent["partyId"] for respondent in reporting_unit.get("associations")] respondents = party_controller.get_respondent_by_party_ids(respondent_party_ids) respondent_table_data = build_respondent_table_data_dict(respondents, ru_ref) breadcrumbs = create_reporting_unit_breadcrumbs(ru_ref) return render_template( "reporting-unit-respondents.html", ru=reporting_unit, respondents=respondent_table_data, breadcrumbs=breadcrumbs ) def build_respondent_table_data_dict(respondents: list, ru_ref: str): table_data = {} survey_data = {} for respondent in respondents: table_data[respondent["id"]] = { "respondent": f"{respondent["firstName"]} {respondent["lastName"]}", "status": respondent["status"].title(), "surveys": {}, "id": respondent["id"], } respondent_surveys = party_controller.survey_ids_for_respondent(respondent, ru_ref) for survey_id in respondent_surveys: # Build up a cache of survey ref/name pairs if survey_id not in survey_data: survey = get_survey_by_id(survey_id) survey_data[survey_id] = f"{survey["surveyRef"]} {survey["shortName"]}" enrolment_status = next( iter(party_controller.add_enrolment_status_for_respondent(respondent, ru_ref, survey_id)) ) table_data[respondent["id"]]["surveys"][survey_id] = { "name": survey_data[survey_id], "status": enrolment_status, } table_data[respondent["id"]]["surveys"] = sorted( table_data[respondent["id"]]["surveys"].items(), key=lambda t: t[1]["name"] ) return sorted(table_data.values(), key=lambda t: t["respondent"]) @reporting_unit_bp.route("/<ru_ref>/surveys/<survey>", methods=["GET"]) @login_required def view_reporting_unit_survey(ru_ref, survey): logger.info("Gathering data to view reporting unit", ru_ref=ru_ref) # Make some initial calls to retrieve some data we'll need reporting_unit = party_controller.get_business_by_ru_ref(ru_ref) cases = case_controller.get_cases_by_business_party_id(reporting_unit["id"]) case_groups = [case["caseGroup"] for case in cases] # Get all collection exercises for retrieved case groups collection_exercise_ids = {case_group["collectionExerciseId"] for case_group in case_groups} collection_exercises = [get_collection_exercise_by_id(ce_id) for ce_id in collection_exercise_ids] live_collection_exercises = [ ce for ce in collection_exercises if parse_date(ce["scheduledStartDateTime"]) < datetime.now(timezone.utc) ] # Get all respondents for the given ru respondent_party_ids = [respondent["partyId"] for respondent in reporting_unit.get("associations")] respondents = party_controller.get_respondent_by_party_ids(respondent_party_ids) survey_respondents = [ party_controller.add_enrolment_status_for_respondent(respondent, ru_ref, survey) for respondent in respondents if survey in party_controller.survey_ids_for_respondent(respondent, ru_ref) ] survey_collection_exercises = sorted( [ collection_exercise for collection_exercise in live_collection_exercises if survey == collection_exercise["surveyId"] ], key=lambda ce: ce["scheduledStartDateTime"], reverse=True, ) attributes = party_controller.get_business_attributes_by_party_id(reporting_unit["id"]) collection_exercises_with_details = [ add_collection_exercise_details(ce, attributes[ce["id"]], case_groups) for ce in survey_collection_exercises ] survey_details = get_survey_by_id(survey) survey_details["display_name"] = f"{survey_details["surveyRef"]} {survey_details["shortName"]}" # If there's an active IAC on the newest case, return it to be displayed collection_exercise_ids = [ce["id"] for ce in survey_collection_exercises] valid_cases = [ case for case in cases if case.get("caseGroup", {}).get("collectionExerciseId") in collection_exercise_ids ] case = next(iter(sorted(valid_cases, key=lambda c: c["createdDateTime"], reverse=True)), None) unused_iac = "" if case is not None and iac_controller.is_iac_active(case["iac"]): unused_iac = case["iac"] return render_template( "reporting-unit-survey.html", ru=reporting_unit, survey=survey_details, respondents=survey_respondents, collection_exercises=collection_exercises_with_details, iac=unused_iac, case=case, ) def add_collection_exercise_details(collection_exercise, reporting_unit, case_groups): collection_exercise["responseStatus"] = map_ce_response_status( get_case_group_status_by_collection_exercise(case_groups, collection_exercise["id"]) ) collection_exercise["companyName"] = reporting_unit["name"] collection_exercise["companyRegion"] = map_region(reporting_unit["attributes"]["region"]) collection_exercise["tradingAs"] = reporting_unit["trading_as"] return collection_exercise @reporting_unit_bp.route("/<ru_ref>/edit-contact-details/<respondent_id>", methods=["GET"]) @login_required def view_contact_details(ru_ref, respondent_id): respondent_details = party_controller.get_respondent_by_party_id(respondent_id) form = EditContactDetailsForm(form=request.form, default_values=respondent_details) return render_template( "edit-contact-details.html", ru_ref=ru_ref, respondent_details=respondent_details, form=form, tab="reporting_units", ) @reporting_unit_bp.route("/<ru_ref>/edit-contact-details/<respondent_id>", methods=["POST"]) @login_required def edit_contact_details(ru_ref, respondent_id): edit_contact_details_form = EditContactDetailsForm(form=request.form) if not edit_contact_details_form.validate(): contact_details = party_controller.get_respondent_by_party_id(respondent_id) return render_template( "edit-contact-details.html", form=edit_contact_details_form, tab="reporting_units", ru_ref=ru_ref, respondent_id=respondent_id, errors=edit_contact_details_form.errors, respondent_details=contact_details, ) logger.info("Updating respondent details", ru_ref=ru_ref, respondent_id=respondent_id) form = request.form contact_details_changed = party_controller.update_contact_details(respondent_id, form, ru_ref) if "emailAddress" in contact_details_changed: flash(f'Contact details changed and verification email sent to {form.get('email')}') elif len(contact_details_changed) > 0: flash("Contact details changed") else: flash("No updates were necessary") return redirect(url_for("reporting_unit_bp.view_reporting_unit", ru_ref=ru_ref)) @reporting_unit_bp.route("/", methods=["GET"]) @login_required def search_reporting_unit_home(): return render_template( "reporting-unit-search/reporting-units-search.html", form=RuSearchForm(), breadcrumbs=[{"text": "Reporting units"}], ) @reporting_unit_bp.route("/", methods=["POST"]) @login_required def search_redirect(): form = RuSearchForm(request.form) if form.validate_on_submit(): query = request.form.get("query") return redirect(url_for("reporting_unit_bp.search_reporting_units", query=query)) @reporting_unit_bp.route("/search", methods=["GET"]) @login_required def search_reporting_units(): search_key_words = request.values.get("query", "") page = request.values.get("page", "1") limit = app.config["PARTY_BUSINESS_RESULTS_PER_PAGE"] max_rec = app.config["PARTY_BUSINESS_RESULTS_TOTAL"] breadcrumbs = [{"text": "Reporting units"}] form = RuSearchForm() form.query.data = search_key_words # this tells us if the search is all numbers # if yes we take it as ru search and not keyword search is_ru_search = search_key_words.isdecimal() response_data = reporting_units_controllers.search_reporting_units(search_key_words, limit, page, is_ru_search) business_list = response_data["businesses"] total_business_count = response_data["total_business_count"] offset = (int(page) - 1) * limit last_index = (limit + offset) if total_business_count >= limit else total_business_count pagination = Pagination( page=int(page), per_page=limit, total=len(business_list) if len(business_list) != 0 and total_business_count <= limit else total_business_count, record_name="Business", prev_label="Previous", next_label="Next", outer_window=0, format_total=True, format_number=True, show_single_page=False, ) return render_template( "reporting-unit-search/reporting-units.html", form=form, business_list=business_list, total_business_count=len(business_list) if len(business_list) != 0 and total_business_count <= limit else total_business_count, breadcrumbs=breadcrumbs, first_index=1 + offset, last_index=last_index, pagination=pagination, show_pagination=bool(total_business_count > limit) and total_business_count < max_rec, max_rec=max_rec, ) # Not sure why is this endpoint exposed : Amit Sinha @reporting_unit_bp.route("/resend_verification/<ru_ref>/<party_id>", methods=["GET"]) @login_required def view_resend_verification(ru_ref, party_id): logger.info("Re-send verification email requested", ru_ref=ru_ref, party_id=party_id) respondent = party_controller.get_respondent_by_party_id(party_id) email = respondent["pendingEmailAddress"] if "pendingEmailAddress" in respondent else respondent["emailAddress"] return render_template("re-send-verification-email.html", ru_ref=ru_ref, email=email, tab="reporting_units") # Not sure why is this endpoint exposed : Amit Sinha @reporting_unit_bp.route("/resend_verification/<ru_ref>/<party_id>", methods=["POST"]) @login_required def resend_verification(ru_ref, party_id): reporting_units_controllers.resend_verification_email(party_id) logger.info("Re-sent verification email.", party_id=party_id) flash("Verification email re-sent") return redirect(url_for("reporting_unit_bp.view_reporting_unit", ru_ref=ru_ref)) @reporting_unit_bp.route("/<ru_ref>/new_enrolment_code", methods=["GET"]) @login_required def generate_new_enrolment_code(ru_ref): case_id = request.args.get("case_id") reporting_units_controllers.generate_new_enrolment_code(case_id) case = case_controller.get_case_by_id(case_id) return render_template( "new-enrolment-code.html", iac=case["iac"], ru_ref=ru_ref, ru_name=request.args.get("ru_name"), trading_as=request.args.get("trading_as"), survey_name=request.args.get("survey_name"), survey_ref=request.args.get("survey_ref"), ) @reporting_unit_bp.route("/<ru_ref>/change-enrolment-status", methods=["GET"]) @login_required def confirm_change_enrolment_status(ru_ref): return render_template( "confirm-enrolment-change.html", business_id=request.args["business_id"], ru_ref=ru_ref, ru_name=request.args.get("ru_name"), trading_as=request.args["trading_as"], survey_id=request.args["survey_id"], survey_name=request.args["survey_name"], respondent_id=request.args["respondent_id"], first_name=request.args["respondent_first_name"], last_name=request.args["respondent_last_name"], change_flag=request.args["change_flag"], tab=request.args["tab"], ) @reporting_unit_bp.route("/<ru_ref>/change-respondent-status", methods=["GET"]) @login_required def confirm_change_respondent_status(ru_ref): respondent = party_controller.get_respondent_by_party_id(request.args["party_id"]) return render_template( "confirm-respondent-status-change.html", ru_ref=ru_ref, respondent_id=respondent["id"], first_name=respondent["firstName"], last_name=respondent["lastName"], email_address=respondent["emailAddress"], change_flag=request.args["change_flag"], tab=request.args["tab"], ) @reporting_unit_bp.route("/<ru_ref>/change-enrolment-status", methods=["POST"]) @login_required def change_enrolment_status(ru_ref): reporting_units_controllers.change_enrolment_status( business_id=request.args["business_id"], respondent_id=request.args["respondent_id"], survey_id=request.args["survey_id"], change_flag=request.args["change_flag"], ) return redirect(url_for("reporting_unit_bp.view_reporting_unit", ru_ref=ru_ref, enrolment_changed="True")) @reporting_unit_bp.route("/<ru_ref>/change-respondent-status", methods=["POST"]) @login_required def change_respondent_status(ru_ref): reporting_units_controllers.change_respondent_status( respondent_id=request.args["respondent_id"], change_flag=request.args["change_flag"] ) return redirect(url_for("reporting_unit_bp.view_reporting_unit", ru_ref=ru_ref, account_status_changed="True")) def create_reporting_unit_breadcrumbs(ru_ref: str) -> list: return [{"text": "Reporting units", "url": "/reporting-units"}, {"text": f"{ru_ref}"}]
import logging from datetime import datetime, timezone from flask import Blueprint from flask import current_app as app from flask import flash, redirect, render_template, request, url_for from flask_login import login_required from flask_paginate import Pagination from iso8601 import parse_date from structlog import wrap_logger from response_operations_ui.common.mappers import map_ce_response_status, map_region from response_operations_ui.controllers import ( case_controller, iac_controller, party_controller, reporting_units_controllers, ) from response_operations_ui.controllers.collection_exercise_controllers import ( get_case_group_status_by_collection_exercise, get_collection_exercise_by_id, ) from response_operations_ui.controllers.survey_controllers import get_survey_by_id from response_operations_ui.forms import EditContactDetailsForm, RuSearchForm logger = wrap_logger(logging.getLogger(__name__)) reporting_unit_bp = Blueprint("reporting_unit_bp", __name__, static_folder="static", template_folder="templates") @reporting_unit_bp.route("/<ru_ref>", methods=["GET"]) @login_required def view_reporting_unit(ru_ref): logger.info("Gathering data to view reporting unit", ru_ref=ru_ref) # Make some initial calls to retrieve some data we'll need reporting_unit = party_controller.get_business_by_ru_ref(ru_ref) cases = case_controller.get_cases_by_business_party_id(reporting_unit["id"]) case_groups = [case["caseGroup"] for case in cases] # Get all collection exercises for retrieved case groups collection_exercise_ids = {case_group["collectionExerciseId"] for case_group in case_groups} collection_exercises = [get_collection_exercise_by_id(ce_id) for ce_id in collection_exercise_ids] live_collection_exercises = [ ce for ce in collection_exercises if parse_date(ce["scheduledStartDateTime"]) < datetime.now(timezone.utc) ] survey_table_data = build_survey_table_data_dict(live_collection_exercises, case_groups) breadcrumbs = create_reporting_unit_breadcrumbs(ru_ref) logger.info("Successfully gathered data to view reporting unit", ru_ref=ru_ref) return render_template("reporting-unit.html", ru=reporting_unit, surveys=survey_table_data, breadcrumbs=breadcrumbs) def build_survey_table_data_dict(collection_exercises: list, case_groups: list) -> list: """ Creates the dictionary of survey & CE information for the front-end table to display :param collection_exercises: A list of collection exercises to add to the table :param case_groups: A list of case groups for the reporting unit :return: A sorted list of survey/CE information to provide to the front-end table """ table_data = {} for ce in collection_exercises: survey = get_survey_by_id(ce["surveyId"]) if survey["surveyRef"] in table_data: # Keep the one with the later go-live date if parse_date(table_data[survey["surveyRef"]]["goLive"]) > parse_date(ce["scheduledStartDateTime"]): continue table_data[survey["surveyRef"]] = { "surveyName": f"{survey['surveyRef']} {survey['shortName']}", "surveyId": ce["surveyId"], "shortName": survey["shortName"], "period": ce["exerciseRef"], "goLive": ce["scheduledStartDateTime"], "caseStatus": map_ce_response_status(get_case_group_status_by_collection_exercise(case_groups, ce["id"])), } return sorted(table_data.items(), key=lambda t: t[0]) @reporting_unit_bp.route("/<ru_ref>/respondents", methods=["GET"]) @login_required def view_respondents(ru_ref: str): logger.info("Gathering data to view reporting unit", ru_ref=ru_ref) # Make some initial calls to retrieve some data we'll need reporting_unit = party_controller.get_business_by_ru_ref(ru_ref) # Get all respondents for the given ru respondent_party_ids = [respondent["partyId"] for respondent in reporting_unit.get("associations")] respondents = party_controller.get_respondent_by_party_ids(respondent_party_ids) respondent_table_data = build_respondent_table_data_dict(respondents, ru_ref) breadcrumbs = create_reporting_unit_breadcrumbs(ru_ref) return render_template( "reporting-unit-respondents.html", ru=reporting_unit, respondents=respondent_table_data, breadcrumbs=breadcrumbs ) def build_respondent_table_data_dict(respondents: list, ru_ref: str): table_data = {} survey_data = {} for respondent in respondents: table_data[respondent["id"]] = { "respondent": f"{respondent['firstName']} {respondent['lastName']}", "status": respondent["status"].title(), "surveys": {}, "id": respondent["id"], } respondent_surveys = party_controller.survey_ids_for_respondent(respondent, ru_ref) for survey_id in respondent_surveys: # Build up a cache of survey ref/name pairs if survey_id not in survey_data: survey = get_survey_by_id(survey_id) survey_data[survey_id] = f"{survey['surveyRef']} {survey['shortName']}" enrolment_status = next( iter(party_controller.add_enrolment_status_for_respondent(respondent, ru_ref, survey_id)) ) table_data[respondent["id"]]["surveys"][survey_id] = { "name": survey_data[survey_id], "status": enrolment_status, } table_data[respondent["id"]]["surveys"] = sorted( table_data[respondent["id"]]["surveys"].items(), key=lambda t: t[1]["name"] ) return sorted(table_data.values(), key=lambda t: t["respondent"]) @reporting_unit_bp.route("/<ru_ref>/surveys/<survey>", methods=["GET"]) @login_required def view_reporting_unit_survey(ru_ref, survey): logger.info("Gathering data to view reporting unit", ru_ref=ru_ref) # Make some initial calls to retrieve some data we'll need reporting_unit = party_controller.get_business_by_ru_ref(ru_ref) cases = case_controller.get_cases_by_business_party_id(reporting_unit["id"]) case_groups = [case["caseGroup"] for case in cases] # Get all collection exercises for retrieved case groups collection_exercise_ids = {case_group["collectionExerciseId"] for case_group in case_groups} collection_exercises = [get_collection_exercise_by_id(ce_id) for ce_id in collection_exercise_ids] live_collection_exercises = [ ce for ce in collection_exercises if parse_date(ce["scheduledStartDateTime"]) < datetime.now(timezone.utc) ] # Get all respondents for the given ru respondent_party_ids = [respondent["partyId"] for respondent in reporting_unit.get("associations")] respondents = party_controller.get_respondent_by_party_ids(respondent_party_ids) survey_respondents = [ party_controller.add_enrolment_status_for_respondent(respondent, ru_ref, survey) for respondent in respondents if survey in party_controller.survey_ids_for_respondent(respondent, ru_ref) ] survey_collection_exercises = sorted( [ collection_exercise for collection_exercise in live_collection_exercises if survey == collection_exercise["surveyId"] ], key=lambda ce: ce["scheduledStartDateTime"], reverse=True, ) attributes = party_controller.get_business_attributes_by_party_id(reporting_unit["id"]) collection_exercises_with_details = [ add_collection_exercise_details(ce, attributes[ce["id"]], case_groups) for ce in survey_collection_exercises ] survey_details = get_survey_by_id(survey) survey_details["display_name"] = f"{survey_details['surveyRef']} {survey_details['shortName']}" # If there's an active IAC on the newest case, return it to be displayed collection_exercise_ids = [ce["id"] for ce in survey_collection_exercises] valid_cases = [ case for case in cases if case.get("caseGroup", {}).get("collectionExerciseId") in collection_exercise_ids ] case = next(iter(sorted(valid_cases, key=lambda c: c["createdDateTime"], reverse=True)), None) unused_iac = "" if case is not None and iac_controller.is_iac_active(case["iac"]): unused_iac = case["iac"] return render_template( "reporting-unit-survey.html", ru=reporting_unit, survey=survey_details, respondents=survey_respondents, collection_exercises=collection_exercises_with_details, iac=unused_iac, case=case, ) def add_collection_exercise_details(collection_exercise, reporting_unit, case_groups): collection_exercise["responseStatus"] = map_ce_response_status( get_case_group_status_by_collection_exercise(case_groups, collection_exercise["id"]) ) collection_exercise["companyName"] = reporting_unit["name"] collection_exercise["companyRegion"] = map_region(reporting_unit["attributes"]["region"]) collection_exercise["tradingAs"] = reporting_unit["trading_as"] return collection_exercise @reporting_unit_bp.route("/<ru_ref>/edit-contact-details/<respondent_id>", methods=["GET"]) @login_required def view_contact_details(ru_ref, respondent_id): respondent_details = party_controller.get_respondent_by_party_id(respondent_id) form = EditContactDetailsForm(form=request.form, default_values=respondent_details) return render_template( "edit-contact-details.html", ru_ref=ru_ref, respondent_details=respondent_details, form=form, tab="reporting_units", ) @reporting_unit_bp.route("/<ru_ref>/edit-contact-details/<respondent_id>", methods=["POST"]) @login_required def edit_contact_details(ru_ref, respondent_id): edit_contact_details_form = EditContactDetailsForm(form=request.form) if not edit_contact_details_form.validate(): contact_details = party_controller.get_respondent_by_party_id(respondent_id) return render_template( "edit-contact-details.html", form=edit_contact_details_form, tab="reporting_units", ru_ref=ru_ref, respondent_id=respondent_id, errors=edit_contact_details_form.errors, respondent_details=contact_details, ) logger.info("Updating respondent details", ru_ref=ru_ref, respondent_id=respondent_id) form = request.form contact_details_changed = party_controller.update_contact_details(respondent_id, form, ru_ref) if "emailAddress" in contact_details_changed: flash(f'Contact details changed and verification email sent to {form.get("email")}') elif len(contact_details_changed) > 0: flash("Contact details changed") else: flash("No updates were necessary") return redirect(url_for("reporting_unit_bp.view_reporting_unit", ru_ref=ru_ref)) @reporting_unit_bp.route("/", methods=["GET"]) @login_required def search_reporting_unit_home(): return render_template( "reporting-unit-search/reporting-units-search.html", form=RuSearchForm(), breadcrumbs=[{"text": "Reporting units"}], ) @reporting_unit_bp.route("/", methods=["POST"]) @login_required def search_redirect(): form = RuSearchForm(request.form) if form.validate_on_submit(): query = request.form.get("query") return redirect(url_for("reporting_unit_bp.search_reporting_units", query=query)) @reporting_unit_bp.route("/search", methods=["GET"]) @login_required def search_reporting_units(): search_key_words = request.values.get("query", "") page = request.values.get("page", "1") limit = app.config["PARTY_BUSINESS_RESULTS_PER_PAGE"] max_rec = app.config["PARTY_BUSINESS_RESULTS_TOTAL"] breadcrumbs = [{"text": "Reporting units"}] form = RuSearchForm() form.query.data = search_key_words # this tells us if the search is all numbers # if yes we take it as ru search and not keyword search is_ru_search = search_key_words.isdecimal() response_data = reporting_units_controllers.search_reporting_units(search_key_words, limit, page, is_ru_search) business_list = response_data["businesses"] total_business_count = response_data["total_business_count"] offset = (int(page) - 1) * limit last_index = (limit + offset) if total_business_count >= limit else total_business_count pagination = Pagination( page=int(page), per_page=limit, total=len(business_list) if len(business_list) != 0 and total_business_count <= limit else total_business_count, record_name="Business", prev_label="Previous", next_label="Next", outer_window=0, format_total=True, format_number=True, show_single_page=False, ) return render_template( "reporting-unit-search/reporting-units.html", form=form, business_list=business_list, total_business_count=len(business_list) if len(business_list) != 0 and total_business_count <= limit else total_business_count, breadcrumbs=breadcrumbs, first_index=1 + offset, last_index=last_index, pagination=pagination, show_pagination=bool(total_business_count > limit) and total_business_count < max_rec, max_rec=max_rec, ) # Not sure why is this endpoint exposed : Amit Sinha @reporting_unit_bp.route("/resend_verification/<ru_ref>/<party_id>", methods=["GET"]) @login_required def view_resend_verification(ru_ref, party_id): logger.info("Re-send verification email requested", ru_ref=ru_ref, party_id=party_id) respondent = party_controller.get_respondent_by_party_id(party_id) email = respondent["pendingEmailAddress"] if "pendingEmailAddress" in respondent else respondent["emailAddress"] return render_template("re-send-verification-email.html", ru_ref=ru_ref, email=email, tab="reporting_units") # Not sure why is this endpoint exposed : Amit Sinha @reporting_unit_bp.route("/resend_verification/<ru_ref>/<party_id>", methods=["POST"]) @login_required def resend_verification(ru_ref, party_id): reporting_units_controllers.resend_verification_email(party_id) logger.info("Re-sent verification email.", party_id=party_id) flash("Verification email re-sent") return redirect(url_for("reporting_unit_bp.view_reporting_unit", ru_ref=ru_ref)) @reporting_unit_bp.route("/<ru_ref>/new_enrolment_code", methods=["GET"]) @login_required def generate_new_enrolment_code(ru_ref): case_id = request.args.get("case_id") reporting_units_controllers.generate_new_enrolment_code(case_id) case = case_controller.get_case_by_id(case_id) return render_template( "new-enrolment-code.html", iac=case["iac"], ru_ref=ru_ref, ru_name=request.args.get("ru_name"), trading_as=request.args.get("trading_as"), survey_name=request.args.get("survey_name"), survey_ref=request.args.get("survey_ref"), ) @reporting_unit_bp.route("/<ru_ref>/change-enrolment-status", methods=["GET"]) @login_required def confirm_change_enrolment_status(ru_ref): return render_template( "confirm-enrolment-change.html", business_id=request.args["business_id"], ru_ref=ru_ref, ru_name=request.args.get("ru_name"), trading_as=request.args["trading_as"], survey_id=request.args["survey_id"], survey_name=request.args["survey_name"], respondent_id=request.args["respondent_id"], first_name=request.args["respondent_first_name"], last_name=request.args["respondent_last_name"], change_flag=request.args["change_flag"], tab=request.args["tab"], ) @reporting_unit_bp.route("/<ru_ref>/change-respondent-status", methods=["GET"]) @login_required def confirm_change_respondent_status(ru_ref): respondent = party_controller.get_respondent_by_party_id(request.args["party_id"]) return render_template( "confirm-respondent-status-change.html", ru_ref=ru_ref, respondent_id=respondent["id"], first_name=respondent["firstName"], last_name=respondent["lastName"], email_address=respondent["emailAddress"], change_flag=request.args["change_flag"], tab=request.args["tab"], ) @reporting_unit_bp.route("/<ru_ref>/change-enrolment-status", methods=["POST"]) @login_required def change_enrolment_status(ru_ref): reporting_units_controllers.change_enrolment_status( business_id=request.args["business_id"], respondent_id=request.args["respondent_id"], survey_id=request.args["survey_id"], change_flag=request.args["change_flag"], ) return redirect(url_for("reporting_unit_bp.view_reporting_unit", ru_ref=ru_ref, enrolment_changed="True")) @reporting_unit_bp.route("/<ru_ref>/change-respondent-status", methods=["POST"]) @login_required def change_respondent_status(ru_ref): reporting_units_controllers.change_respondent_status( respondent_id=request.args["respondent_id"], change_flag=request.args["change_flag"] ) return redirect(url_for("reporting_unit_bp.view_reporting_unit", ru_ref=ru_ref, account_status_changed="True")) def create_reporting_unit_breadcrumbs(ru_ref: str) -> list: return [{"text": "Reporting units", "url": "/reporting-units"}, {"text": f"{ru_ref}"}]
import RaceRandom as random from collections import defaultdict, deque import logging import time from enum import unique, Flag from typing import DefaultDict, Dict, List from BaseClasses import RegionType, Region, Door, DoorType, Direction, Sector, CrystalBarrier, DungeonInfo, dungeon_keys from Doors import reset_portals from Dungeons import dungeon_regions, region_starts, standard_starts, split_region_starts from Dungeons import dungeon_bigs, dungeon_hints from Items import ItemFactory from RoomData import DoorKind, PairedDoor, reset_rooms from DungeonGenerator import ExplorationState, convert_regions, generate_dungeon, pre_validate, determine_required_paths, drop_entrances from DungeonGenerator import create_dungeon_builders, split_dungeon_builder, simple_dungeon_builder, default_dungeon_entrances from DungeonGenerator import dungeon_portals, dungeon_drops, GenerationException from KeyDoorShuffle import analyze_dungeon, build_key_layout, validate_key_layout, determine_prize_lock from Utils import ncr, kth_combination def link_doors(world, player): orig_swamp_patch = world.swamp_patch_required[player] attempt, valid = 1, False while not valid: try: link_doors_main(world, player) valid = True except GenerationException as e: logging.getLogger('').debug(f'Irreconcilable generation. {str(e)} Starting a new attempt.') attempt += 1 if attempt > 10: raise Exception('Could not create world in 10 attempts. Generation algorithms need more work', e) for door in world.doors: if door.player == player: door.dest = None door.entranceFlag = False ent = door.entrance if (door.type != DoorType.Logical or door.controller) and ent.connected_region is not None: ent.connected_region.entrances = [x for x in ent.connected_region.entrances if x != ent] ent.connected_region = None for portal in world.dungeon_portals[player]: disconnect_portal(portal, world, player) reset_portals(world, player) reset_rooms(world, player) world.get_door("Skull Pinball WS", player).no_exit() world.swamp_patch_required[player] = orig_swamp_patch def link_doors_main(world, player): # Drop-down connections & push blocks for exitName, regionName in logical_connections: connect_simple_door(world, exitName, regionName, player) # These should all be connected for now as normal connections for edge_a, edge_b in interior_doors: connect_interior_doors(edge_a, edge_b, world, player) # These connections are here because they are currently unable to be shuffled for exitName, regionName in falldown_pits: connect_simple_door(world, exitName, regionName, player) for exitName, regionName in dungeon_warps: connect_simple_door(world, exitName, regionName, player) if world.intensity[player] < 2: for entrance, ext in open_edges: connect_two_way(world, entrance, ext, player) for entrance, ext in straight_staircases: connect_two_way(world, entrance, ext, player) for entrance, ext in ladders: connect_two_way(world, entrance, ext, player) if world.intensity[player] < 3 or world.doorShuffle[player] == 'vanilla': mirror_route = world.get_entrance('Sanctuary Mirror Route', player) mr_door = mirror_route.door sanctuary = mirror_route.parent_region if mirror_route in sanctuary.exits: sanctuary.exits.remove(mirror_route) world.remove_entrance(mirror_route, player) world.remove_door(mr_door, player) connect_custom(world, player) find_inaccessible_regions(world, player) if world.intensity[player] >= 3 and world.doorShuffle[player] in ['basic', 'crossed']: choose_portals(world, player) else: if world.shuffle[player] == 'vanilla': if world.mode[player] == 'standard': world.get_portal('Sanctuary', player).destination = True world.get_portal('Desert East', player).destination = True if (world.mode[player] == 'inverted') != (0x30 in world.owswaps[player][0] and world.owMixed[player]): world.get_portal('Desert West', player).destination = True if (world.mode[player] == 'inverted') == (0x00 in world.owswaps[player][0] and world.owMixed[player]): world.get_portal('Skull 2 West', player).destination = True if (world.mode[player] == 'inverted') == (0x05 in world.owswaps[player][0] and world.owMixed[player]): world.get_portal('Turtle Rock Lazy Eyes', player).destination = True world.get_portal('Turtle Rock Eye Bridge', player).destination = True else: analyze_portals(world, player) for portal in world.dungeon_portals[player]: connect_portal(portal, world, player) if not world.doorShuffle[player] == 'vanilla': fix_big_key_doors_with_ugly_smalls(world, player) else: unmark_ugly_smalls(world, player) if world.doorShuffle[player] == 'vanilla': for entrance, ext in open_edges: connect_two_way(world, entrance, ext, player) for entrance, ext in straight_staircases: connect_two_way(world, entrance, ext, player) for exitName, regionName in vanilla_logical_connections: connect_simple_door(world, exitName, regionName, player) for entrance, ext in spiral_staircases: connect_two_way(world, entrance, ext, player) for entrance, ext in ladders: connect_two_way(world, entrance, ext, player) for entrance, ext in default_door_connections: connect_two_way(world, entrance, ext, player) for ent, ext in default_one_way_connections: connect_one_way(world, ent, ext, player) vanilla_key_logic(world, player) elif world.doorShuffle[player] == 'basic': within_dungeon(world, player) elif world.doorShuffle[player] == 'crossed': cross_dungeon(world, player) else: logging.getLogger('').error('Invalid door shuffle setting: %s' % world.doorShuffle[player]) raise Exception('Invalid door shuffle setting: %s' % world.doorShuffle[player]) if world.doorShuffle[player] != 'vanilla': create_door_spoiler(world, player) # todo: I think this function is not necessary def mark_regions(world, player): # traverse dungeons and make sure dungeon property is assigned player_dungeons = [dungeon for dungeon in world.dungeons if dungeon.player == player] for dungeon in player_dungeons: queue = deque(dungeon.regions) while len(queue) > 0: region = world.get_region(queue.popleft(), player) if region.name not in dungeon.regions: dungeon.regions.append(region.name) region.dungeon = dungeon for ext in region.exits: d = world.check_for_door(ext.name, player) connected = ext.connected_region if d is not None and connected is not None: if d.dest is not None and connected.name not in dungeon.regions and connected.type == RegionType.Dungeon and connected.name not in queue: queue.append(connected) # needs to be added elif connected is not None and connected.name not in dungeon.regions and connected.type == RegionType.Dungeon and connected.name not in queue: queue.append(connected) # needs to be added def create_door_spoiler(world, player): logger = logging.getLogger('') queue = deque(world.dungeon_layouts[player].values()) while len(queue) > 0: builder = queue.popleft() done = set() start_regions = set(convert_regions(builder.layout_starts, world, player)) # todo: set all_entrances for basic reg_queue = deque(start_regions) visited = set(start_regions) while len(reg_queue) > 0: next = reg_queue.pop() for ext in next.exits: door_a = ext.door connect = ext.connected_region if door_a and door_a.type in [DoorType.Normal, DoorType.SpiralStairs, DoorType.Open, DoorType.StraightStairs, DoorType.Ladder] and door_a not in done: done.add(door_a) door_b = door_a.dest if door_b and not isinstance(door_b, Region): done.add(door_b) if not door_a.blocked and not door_b.blocked: world.spoiler.set_door(door_a.name, door_b.name, 'both', player, builder.name) elif door_a.blocked: world.spoiler.set_door(door_b.name, door_a.name, 'entrance', player, builder.name) elif door_b.blocked: world.spoiler.set_door(door_a.name, door_b.name, 'entrance', player, builder.name) else: logger.warning('This is a bug during door spoiler') elif not isinstance(door_b, Region): logger.warning('Door not connected: %s', door_a.name) if connect and connect.type == RegionType.Dungeon and connect not in visited: visited.add(connect) reg_queue.append(connect) def vanilla_key_logic(world, player): builders = [] world.dungeon_layouts[player] = {} for dungeon in [dungeon for dungeon in world.dungeons if dungeon.player == player]: sector = Sector() sector.name = dungeon.name sector.regions.extend(convert_regions(dungeon.regions, world, player)) builder = simple_dungeon_builder(sector.name, [sector]) builder.master_sector = sector builders.append(builder) world.dungeon_layouts[player][builder.name] = builder add_inaccessible_doors(world, player) for builder in builders: origin_list = find_accessible_entrances(world, player, builder) start_regions = convert_regions(origin_list, world, player) doors = convert_key_doors(default_small_key_doors[builder.name], world, player) key_layout = build_key_layout(builder, start_regions, doors, world, player) valid = validate_key_layout(key_layout, world, player) if not valid: logging.getLogger('').warning('Vanilla key layout not valid %s', builder.name) builder.key_door_proposal = doors if player not in world.key_logic.keys(): world.key_logic[player] = {} analyze_dungeon(key_layout, world, player) world.key_logic[player][builder.name] = key_layout.key_logic log_key_logic(builder.name, key_layout.key_logic) # if world.shuffle[player] == 'vanilla' and world.owShuffle[player] == 'vanilla' and world.owCrossed[player] == 'none' and not world.owMixed[player] and world.accessibility[player] == 'items' and not world.retro[player] and not world.keydropshuffle[player]: # validate_vanilla_key_logic(world, player) # some useful functions oppositemap = { Direction.South: Direction.North, Direction.North: Direction.South, Direction.West: Direction.East, Direction.East: Direction.West, Direction.Up: Direction.Down, Direction.Down: Direction.Up, } def switch_dir(direction): return oppositemap[direction] def convert_key_doors(k_doors, world, player): result = [] for d in k_doors: if type(d) is tuple: result.append((world.get_door(d[0], player), world.get_door(d[1], player))) else: result.append(world.get_door(d, player)) return result def connect_custom(world, player): if hasattr(world, 'custom_doors') and world.custom_doors[player]: for entrance, ext in world.custom_doors[player]: connect_two_way(world, entrance, ext, player) def connect_simple_door(world, exit_name, region_name, player): region = world.get_region(region_name, player) world.get_entrance(exit_name, player).connect(region) d = world.check_for_door(exit_name, player) if d is not None: d.dest = region def connect_door_only(world, exit_name, region, player): d = world.check_for_door(exit_name, player) if d is not None: d.dest = region def connect_interior_doors(a, b, world, player): door_a = world.get_door(a, player) door_b = world.get_door(b, player) if door_a.blocked: connect_one_way(world, b, a, player) elif door_b.blocked: connect_one_way(world, a, b, player) else: connect_two_way(world, a, b, player) def connect_two_way(world, entrancename, exitname, player): entrance = world.get_entrance(entrancename, player) ext = world.get_entrance(exitname, player) # if these were already connected somewhere, remove the backreference if entrance.connected_region is not None: entrance.connected_region.entrances.remove(entrance) if ext.connected_region is not None: ext.connected_region.entrances.remove(ext) entrance.connect(ext.parent_region) ext.connect(entrance.parent_region) if entrance.parent_region.dungeon: ext.parent_region.dungeon = entrance.parent_region.dungeon x = world.check_for_door(entrancename, player) y = world.check_for_door(exitname, player) if x is not None: x.dest = y if y is not None: y.dest = x def connect_one_way(world, entrancename, exitname, player): entrance = world.get_entrance(entrancename, player) ext = world.get_entrance(exitname, player) # if these were already connected somewhere, remove the backreference if entrance.connected_region is not None: entrance.connected_region.entrances.remove(entrance) if ext.connected_region is not None: ext.connected_region.entrances.remove(ext) entrance.connect(ext.parent_region) if entrance.parent_region.dungeon: ext.parent_region.dungeon = entrance.parent_region.dungeon x = world.check_for_door(entrancename, player) y = world.check_for_door(exitname, player) if x is not None: x.dest = y if y is not None: y.dest = x def unmark_ugly_smalls(world, player): for d in ['Eastern Hint Tile Blocked Path SE', 'Eastern Darkness S', 'Thieves Hallway SE', 'Mire Left Bridge S', 'TR Lava Escape SE', 'GT Hidden Spikes SE']: door = world.get_door(d, player) door.smallKey = False def fix_big_key_doors_with_ugly_smalls(world, player): remove_ugly_small_key_doors(world, player) unpair_big_key_doors(world, player) def remove_ugly_small_key_doors(world, player): for d in ['Eastern Hint Tile Blocked Path SE', 'Eastern Darkness S', 'Thieves Hallway SE', 'Mire Left Bridge S', 'TR Lava Escape SE', 'GT Hidden Spikes SE']: door = world.get_door(d, player) room = world.get_room(door.roomIndex, player) if not door.entranceFlag: room.change(door.doorListPos, DoorKind.Normal) door.smallKey = False door.ugly = False def unpair_big_key_doors(world, player): problematic_bk_doors = ['Eastern Courtyard N', 'Eastern Big Key NE', 'Thieves BK Corner NE', 'Mire BK Door Room N', 'TR Dodgers NE', 'GT Dash Hall NE'] for paired_door in world.paired_doors[player]: if paired_door.door_a in problematic_bk_doors or paired_door.door_b in problematic_bk_doors: paired_door.pair = False def pair_existing_key_doors(world, player, door_a, door_b): already_paired = False door_names = [door_a.name, door_b.name] for pd in world.paired_doors[player]: if pd.door_a in door_names and pd.door_b in door_names: already_paired = True break if already_paired: return for paired_door in world.paired_doors[player]: if paired_door.door_a in door_names or paired_door.door_b in door_names: paired_door.pair = False world.paired_doors[player].append(PairedDoor(door_a, door_b)) def choose_portals(world, player): if world.doorShuffle[player] in ['basic', 'crossed']: cross_flag = world.doorShuffle[player] == 'crossed' # key drops allow the big key in the right place in Desert Tiles 2 bk_shuffle = world.bigkeyshuffle[player] or world.keydropshuffle[player] std_flag = world.mode[player] == 'standard' # roast incognito doors world.get_room(0x60, player).delete(5) world.get_room(0x60, player).change(2, DoorKind.DungeonEntrance) world.get_room(0x62, player).delete(5) world.get_room(0x62, player).change(1, DoorKind.DungeonEntrance) info_map = {} for dungeon, portal_list in dungeon_portals.items(): info = DungeonInfo(dungeon) region_map = defaultdict(list) reachable_portals = [] inaccessible_portals = [] hc_flag = std_flag and dungeon == 'Hyrule Castle' for portal in portal_list: placeholder = world.get_region(portal + ' Portal', player) portal_region = placeholder.exits[0].connected_region name = portal_region.name if portal_region.type == RegionType.LightWorld: world.get_portal(portal, player).light_world = True if name in world.inaccessible_regions[player] or (hc_flag and portal != 'Hyrule Castle South'): name_key = 'Desert Ledge' if name == 'Desert Palace Entrance (North) Spot' else name region_map[name_key].append(portal) inaccessible_portals.append(portal) else: reachable_portals.append(portal) info.total = len(portal_list) info.required_passage = region_map if len(reachable_portals) == 0: if len(inaccessible_portals) == 1: info.sole_entrance = inaccessible_portals[0] info.required_passage.clear() else: raise Exception('please inspect this case') if len(reachable_portals) == 1: info.sole_entrance = reachable_portals[0] info_map[dungeon] = info master_door_list = [x for x in world.doors if x.player == player and x.portalAble] portal_assignment = defaultdict(list) shuffled_info = list(info_map.items()) if cross_flag: random.shuffle(shuffled_info) for dungeon, info in shuffled_info: outstanding_portals = list(dungeon_portals[dungeon]) hc_flag = std_flag and dungeon == 'Hyrule Castle' rupee_bow_flag = hc_flag and world.retro[player] # rupee bow if hc_flag: sanc = world.get_portal('Sanctuary', player) sanc.destination = True clean_up_portal_assignment(portal_assignment, dungeon, sanc, master_door_list, outstanding_portals) for target_region, possible_portals in info.required_passage.items(): info.required_passage[target_region] = [x for x in possible_portals if x != sanc.name] info.required_passage = {x: y for x, y in info.required_passage.items() if len(y) > 0} for target_region, possible_portals in info.required_passage.items(): candidates = find_portal_candidates(master_door_list, dungeon, need_passage=True, crossed=cross_flag, bk_shuffle=bk_shuffle, rupee_bow=rupee_bow_flag) choice, portal = assign_portal(candidates, possible_portals, world, player) portal.destination = True clean_up_portal_assignment(portal_assignment, dungeon, portal, master_door_list, outstanding_portals) dead_end_choices = info.total - 1 - len(portal_assignment[dungeon]) for i in range(0, dead_end_choices): candidates = find_portal_candidates(master_door_list, dungeon, dead_end_allowed=True, crossed=cross_flag, bk_shuffle=bk_shuffle, rupee_bow=rupee_bow_flag) possible_portals = outstanding_portals if not info.sole_entrance else [x for x in outstanding_portals if x != info.sole_entrance] choice, portal = assign_portal(candidates, possible_portals, world, player) if choice.deadEnd: if choice.passage: portal.destination = True else: portal.deadEnd = True clean_up_portal_assignment(portal_assignment, dungeon, portal, master_door_list, outstanding_portals) the_rest = info.total - len(portal_assignment[dungeon]) for i in range(0, the_rest): candidates = find_portal_candidates(master_door_list, dungeon, crossed=cross_flag, bk_shuffle=bk_shuffle, standard=hc_flag, rupee_bow=rupee_bow_flag) choice, portal = assign_portal(candidates, outstanding_portals, world, player) clean_up_portal_assignment(portal_assignment, dungeon, portal, master_door_list, outstanding_portals) for portal in world.dungeon_portals[player]: connect_portal(portal, world, player) hc_south = world.get_door('Hyrule Castle Lobby S', player) if not hc_south.entranceFlag: world.get_room(0x61, player).delete(6) world.get_room(0x61, player).change(4, DoorKind.NormalLow) else: world.get_room(0x61, player).change(4, DoorKind.DungeonEntrance) world.get_room(0x61, player).change(6, DoorKind.CaveEntranceLow) sanctuary_door = world.get_door('Sanctuary S', player) if not sanctuary_door.entranceFlag: world.get_room(0x12, player).delete(3) world.get_room(0x12, player).change(2, DoorKind.NormalLow) else: world.get_room(0x12, player).change(2, DoorKind.DungeonEntrance) world.get_room(0x12, player).change(3, DoorKind.CaveEntranceLow) hera_door = world.get_door('Hera Lobby S', player) if not hera_door.entranceFlag: world.get_room(0x77, player).change(0, DoorKind.NormalLow2) # tr rock bomb entrances for portal in world.dungeon_portals[player]: if not portal.destination and not portal.deadEnd: if portal.door.name == 'TR Lazy Eyes SE': world.get_room(0x23, player).change(0, DoorKind.DungeonEntrance) if portal.door.name == 'TR Eye Bridge SW': world.get_room(0xd5, player).change(0, DoorKind.DungeonEntrance) if not world.swamp_patch_required[player]: swamp_portal = world.get_portal('Swamp', player) if swamp_portal.door.name != 'Swamp Lobby S': world.swamp_patch_required[player] = True def analyze_portals(world, player): info_map = {} for dungeon, portal_list in dungeon_portals.items(): info = DungeonInfo(dungeon) region_map = defaultdict(list) reachable_portals = [] inaccessible_portals = [] for portal in portal_list: placeholder = world.get_region(portal + ' Portal', player) portal_region = placeholder.exits[0].connected_region name = portal_region.name if portal_region.type == RegionType.LightWorld: world.get_portal(portal, player).light_world = True if name in world.inaccessible_regions[player]: name_key = 'Desert Ledge' if name == 'Desert Palace Entrance (North) Spot' else name region_map[name_key].append(portal) inaccessible_portals.append(portal) else: reachable_portals.append(portal) info.total = len(portal_list) info.required_passage = region_map if len(reachable_portals) == 0: if len(inaccessible_portals) == 1: info.sole_entrance = inaccessible_portals[0] info.required_passage.clear() else: raise Exception('please inspect this case') if len(reachable_portals) == 1: info.sole_entrance = reachable_portals[0] if world.intensity[player] < 2 and world.doorShuffle[player] == 'basic' and dungeon == 'Desert Palace': if len(inaccessible_portals) == 1 and inaccessible_portals[0] == 'Desert Back': info.required_passage.clear() # can't make a passage at this intensity level, something else must exit info_map[dungeon] = info for dungeon, info in info_map.items(): if dungeon == 'Hyrule Castle' and world.mode[player] == 'standard': sanc = world.get_portal('Sanctuary', player) sanc.destination = True for target_region, possible_portals in info.required_passage.items(): if len(possible_portals) == 1: world.get_portal(possible_portals[0], player).destination = True elif len(possible_portals) > 1: dest_portal = random.choice(possible_portals) access_portal = world.get_portal(dest_portal, player) access_portal.destination = True for other_portal in possible_portals: if other_portal != dest_portal: world.get_portal(dest_portal, player).dependent = access_portal def connect_portal(portal, world, player): ent, ext, entrance_name = portal_map[portal.name] portal_entrance = world.get_entrance(portal.door.entrance.name, player) # ensures I get the right one for copying target_exit = world.get_entrance(ext, player) portal_entrance.connected_region = target_exit.parent_region portal_region = world.get_region(portal.name + ' Portal', player) portal_region.entrances.append(portal_entrance) edit_entrance = world.get_entrance(entrance_name, player) edit_entrance.connected_region = portal_entrance.parent_region chosen_door = world.get_door(portal_entrance.name, player) chosen_door.blocked = False connect_door_only(world, chosen_door, portal_region, player) portal_entrance.parent_region.entrances.append(edit_entrance) def disconnect_portal(portal, world, player): ent, ext, entrance_name = portal_map[portal.name] portal_entrance = world.get_entrance(portal.door.entrance.name, player) # portal_region = world.get_region(portal.name + ' Portal', player) edit_entrance = world.get_entrance(entrance_name, player) chosen_door = world.get_door(portal_entrance.name, player) # reverse work if edit_entrance in portal_entrance.parent_region.entrances: portal_entrance.parent_region.entrances.remove(edit_entrance) chosen_door.blocked = chosen_door.blocked_orig chosen_door.entranceFlag = False def find_portal_candidates(door_list, dungeon, need_passage=False, dead_end_allowed=False, crossed=False, bk_shuffle=False, standard=False, rupee_bow=False): ret = [x for x in door_list if bk_shuffle or not x.bk_shuffle_req] if crossed: ret = [x for x in ret if not x.dungeonLink or x.dungeonLink == dungeon or x.dungeonLink.startswith('link')] else: ret = [x for x in ret if x.entrance.parent_region.dungeon.name == dungeon] if need_passage: ret = [x for x in ret if x.passage] if not dead_end_allowed: ret = [x for x in ret if not x.deadEnd] if standard: ret = [x for x in ret if not x.standard_restricted] if rupee_bow: ret = [x for x in ret if not x.rupee_bow_restricted] return ret def assign_portal(candidates, possible_portals, world, player): candidate = random.choice(candidates) portal_choice = random.choice(possible_portals) portal = world.get_portal(portal_choice, player) while candidate.lw_restricted and not portal.light_world: candidates.remove(candidate) candidate = random.choice(candidates) if candidate != portal.door: if candidate.entranceFlag: for other_portal in world.dungeon_portals[player]: if other_portal.door == candidate: other_portal.door = None break old_door = portal.door if old_door: old_door.entranceFlag = False if old_door.name not in ['Hyrule Castle Lobby S', 'Sanctuary S', 'Hera Lobby S']: old_door_kind = DoorKind.NormalLow if old_door.layer or old_door.pseudo_bg else DoorKind.Normal world.get_room(old_door.roomIndex, player).change(old_door.doorListPos, old_door_kind) portal.change_door(candidate) if candidate.name not in ['Hyrule Castle Lobby S', 'Sanctuary S']: if candidate.name == 'Swamp Hub S': new_door_kind = DoorKind.CaveEntranceLow elif candidate.layer or candidate.pseudo_bg: new_door_kind = DoorKind.DungeonEntranceLow else: new_door_kind = DoorKind.DungeonEntrance world.get_room(candidate.roomIndex, player).change(candidate.doorListPos, new_door_kind) candidate.entranceFlag = True return candidate, portal def clean_up_portal_assignment(portal_assignment, dungeon, portal, master_door_list, outstanding_portals): portal_assignment[dungeon].append(portal) master_door_list[:] = [x for x in master_door_list if x.roomIndex != portal.door.roomIndex] if portal.door.dungeonLink and portal.door.dungeonLink.startswith('link'): match_link = portal.door.dungeonLink for door in master_door_list: if door.dungeonLink == match_link: door.dungeonLink = dungeon outstanding_portals.remove(portal.name) def create_dungeon_entrances(world, player): entrance_map = defaultdict(list) split_map: DefaultDict[str, DefaultDict[str, List]] = defaultdict(lambda: defaultdict(list)) originating: DefaultDict[str, DefaultDict[str, Dict]] = defaultdict(lambda: defaultdict(dict)) for key, portal_list in dungeon_portals.items(): if key in dungeon_drops.keys(): entrance_map[key].extend(dungeon_drops[key]) if key in split_portals.keys(): dead_ends = [] destinations = [] the_rest = [] for portal_name in portal_list: portal = world.get_portal(portal_name, player) entrance_map[key].append(portal.door.entrance.parent_region.name) if portal.deadEnd: dead_ends.append(portal) elif portal.destination: destinations.append(portal) else: the_rest.append(portal) choices = list(split_portals[key]) for portal in dead_ends: choice = random.choice(choices) choices.remove(choice) r_name = portal.door.entrance.parent_region.name split_map[key][choice].append(r_name) for portal in the_rest: if len(choices) == 0: choices.append('Extra') choice = random.choice(choices) p_entrance = portal.door.entrance r_name = p_entrance.parent_region.name split_map[key][choice].append(r_name) entrance_region = find_entrance_region(portal) originating[key][choice][entrance_region.name] = None dest_choices = [x for x in choices if len(split_map[key][x]) > 0] for portal in destinations: entrance_region = find_entrance_region(portal) restricted = entrance_region.name in world.inaccessible_regions[player] if restricted: filtered_choices = [x for x in choices if any(y not in world.inaccessible_regions[player] for y in originating[key][x].keys())] else: filtered_choices = dest_choices if len(filtered_choices) == 0: raise Exception('No valid destinations') choice = random.choice(filtered_choices) r_name = portal.door.entrance.parent_region.name split_map[key][choice].append(r_name) else: for portal_name in portal_list: portal = world.get_portal(portal_name, player) r_name = portal.door.entrance.parent_region.name entrance_map[key].append(r_name) return entrance_map, split_map def find_entrance_region(portal): for entrance in portal.door.entrance.connected_region.entrances: if entrance.parent_region.type != RegionType.Dungeon: return entrance.parent_region return None # def unpair_all_doors(world, player): # for paired_door in world.paired_doors[player]: # paired_door.pair = False def within_dungeon(world, player): add_inaccessible_doors(world, player) entrances_map, potentials, connections = determine_entrance_list(world, player) connections_tuple = (entrances_map, potentials, connections) dungeon_builders = {} for key in dungeon_regions.keys(): sector_list = convert_to_sectors(dungeon_regions[key], world, player) dungeon_builders[key] = simple_dungeon_builder(key, sector_list) dungeon_builders[key].entrance_list = list(entrances_map[key]) recombinant_builders = {} entrances, splits = create_dungeon_entrances(world, player) builder_info = entrances, splits, connections_tuple, world, player handle_split_dungeons(dungeon_builders, recombinant_builders, entrances_map, builder_info) main_dungeon_generation(dungeon_builders, recombinant_builders, connections_tuple, world, player) paths = determine_required_paths(world, player) check_required_paths(paths, world, player) # shuffle_key_doors for dungeons logging.getLogger('').info(world.fish.translate("cli", "cli", "shuffling.keydoors")) start = time.process_time() for builder in world.dungeon_layouts[player].values(): shuffle_key_doors(builder, world, player) logging.getLogger('').info('%s: %s', world.fish.translate("cli", "cli", "keydoor.shuffle.time"), time.process_time()-start) smooth_door_pairs(world, player) if world.intensity[player] >= 3: portal = world.get_portal('Sanctuary', player) target = portal.door.entrance.parent_region connect_simple_door(world, 'Sanctuary Mirror Route', target, player) refine_boss_exits(world, player) def handle_split_dungeons(dungeon_builders, recombinant_builders, entrances_map, builder_info): dungeon_entrances, split_dungeon_entrances, c_tuple, world, player = builder_info if dungeon_entrances is None: dungeon_entrances = default_dungeon_entrances if split_dungeon_entrances is None: split_dungeon_entrances = split_region_starts builder_info = dungeon_entrances, split_dungeon_entrances, c_tuple, world, player for name, split_list in split_dungeon_entrances.items(): builder = dungeon_builders.pop(name) recombinant_builders[name] = builder split_builders = split_dungeon_builder(builder, split_list, builder_info) dungeon_builders.update(split_builders) for sub_name, split_entrances in split_list.items(): key = name+' '+sub_name if key not in dungeon_builders: continue sub_builder = dungeon_builders[key] sub_builder.split_flag = True entrance_list = list(split_entrances) for ent in entrances_map[name]: add_shuffled_entrances(sub_builder.sectors, ent, entrance_list) filtered_entrance_list = [x for x in entrance_list if x in entrances_map[name]] sub_builder.entrance_list = filtered_entrance_list def main_dungeon_generation(dungeon_builders, recombinant_builders, connections_tuple, world, player): entrances_map, potentials, connections = connections_tuple enabled_entrances = world.enabled_entrances[player] = {} sector_queue = deque(dungeon_builders.values()) last_key, loops = None, 0 logging.getLogger('').info(world.fish.translate("cli", "cli", "generating.dungeon")) while len(sector_queue) > 0: builder = sector_queue.popleft() split_dungeon = builder.name.startswith('Desert Palace') or builder.name.startswith('Skull Woods') name = builder.name if split_dungeon: name = ' '.join(builder.name.split(' ')[:-1]) if len(builder.sectors) == 0: del dungeon_builders[builder.name] continue origin_list = list(builder.entrance_list) find_enabled_origins(builder.sectors, enabled_entrances, origin_list, entrances_map, name) split_dungeon = treat_split_as_whole_dungeon(split_dungeon, name, origin_list, world, player) if len(origin_list) <= 0 or not pre_validate(builder, origin_list, split_dungeon, world, player): if last_key == builder.name or loops > 1000: origin_name = world.get_region(origin_list[0], player).entrances[0].parent_region.name if len(origin_list) > 0 else 'no origin' raise GenerationException(f'Infinite loop detected for "{builder.name}" located at {origin_name}') sector_queue.append(builder) last_key = builder.name loops += 1 else: ds = generate_dungeon(builder, origin_list, split_dungeon, world, player) find_new_entrances(ds, entrances_map, connections, potentials, enabled_entrances, world, player) ds.name = name builder.master_sector = ds builder.layout_starts = origin_list if len(builder.entrance_list) <= 0 else builder.entrance_list last_key = None combine_layouts(recombinant_builders, dungeon_builders, entrances_map) world.dungeon_layouts[player] = {} for builder in dungeon_builders.values(): builder.entrance_list = builder.layout_starts = builder.path_entrances = find_accessible_entrances(world, player, builder) world.dungeon_layouts[player] = dungeon_builders def determine_entrance_list_vanilla(world, player): entrance_map = {} potential_entrances = {} connections = {} for key, r_names in region_starts.items(): entrance_map[key] = [] if world.mode[player] == 'standard' and key in standard_starts.keys(): r_names = ['Hyrule Castle Lobby'] for region_name in r_names: region = world.get_region(region_name, player) for ent in region.entrances: parent = ent.parent_region if (parent.type != RegionType.Dungeon and parent.name != 'Menu' and parent.name != 'Flute Sky') or parent.name == 'Sewer Drop': if parent.name not in world.inaccessible_regions[player]: entrance_map[key].append(region_name) else: if ent.parent_region not in potential_entrances.keys(): potential_entrances[parent] = [] potential_entrances[parent].append(region_name) connections[region_name] = parent return entrance_map, potential_entrances, connections def determine_entrance_list(world, player): entrance_map = {} potential_entrances = {} connections = {} for key, portal_list in dungeon_portals.items(): entrance_map[key] = [] r_names = {} if key in dungeon_drops.keys(): for drop in dungeon_drops[key]: r_names[drop] = None for portal_name in portal_list: portal = world.get_portal(portal_name, player) r_names[portal.door.entrance.parent_region.name] = portal for region_name, portal in r_names.items(): if portal: region = world.get_region(portal.name + ' Portal', player) else: region = world.get_region(region_name, player) for ent in region.entrances: parent = ent.parent_region if (parent.type != RegionType.Dungeon and parent.name != 'Menu' and parent.name != 'Flute Sky') or parent.name == 'Sewer Drop': std_inaccessible = is_standard_inaccessible(key, portal, world, player) if parent.name not in world.inaccessible_regions[player] and not std_inaccessible: entrance_map[key].append(region_name) else: if parent not in potential_entrances.keys(): potential_entrances[parent] = [] if region_name not in potential_entrances[parent]: potential_entrances[parent].append(region_name) connections[region_name] = parent return entrance_map, potential_entrances, connections def is_standard_inaccessible(key, portal, world, player): return world.mode[player] == 'standard' and key in standard_starts and (not portal or portal.name not in standard_starts[key]) def add_shuffled_entrances(sectors, region_list, entrance_list): for sector in sectors: for region in sector.regions: if region.name in region_list and region.name not in entrance_list: entrance_list.append(region.name) def find_enabled_origins(sectors, enabled, entrance_list, entrance_map, key): for sector in sectors: for region in sector.regions: if region.name in enabled.keys() and region.name not in entrance_list: entrance_list.append(region.name) origin_reg, origin_dungeon = enabled[region.name] if origin_reg != region.name and origin_dungeon != region.dungeon: if key not in entrance_map.keys(): key = ' '.join(key.split(' ')[:-1]) entrance_map[key].append(region.name) def find_new_entrances(sector, entrances_map, connections, potentials, enabled, world, player): for region in sector.regions: if region.name in connections.keys() and (connections[region.name] in potentials.keys() or connections[region.name].name in world.inaccessible_regions[player]): enable_new_entrances(region, connections, potentials, enabled, world, player, region) inverted_aga_check(entrances_map, connections, potentials, enabled, world, player) def enable_new_entrances(region, connections, potentials, enabled, world, player, region_enabler): new_region = connections[region.name] if new_region in potentials.keys(): for potential in potentials.pop(new_region): enabled[potential] = (region_enabler.name, region_enabler.dungeon) # see if this unexplored region connects elsewhere queue = deque(new_region.exits) visited = set() while len(queue) > 0: ext = queue.popleft() visited.add(ext) if ext.connected_region is None: continue region_name = ext.connected_region.name if region_name in connections.keys() and connections[region_name] in potentials.keys(): for potential in potentials.pop(connections[region_name]): enabled[potential] = (region.name, region.dungeon) if ext.connected_region.name in world.inaccessible_regions[player] or ext.connected_region.name.endswith(' Portal'): for new_exit in ext.connected_region.exits: if new_exit not in visited: queue.append(new_exit) def inverted_aga_check(entrances_map, connections, potentials, enabled, world, player): if world.mode[player] == 'inverted': if 'Agahnims Tower' in entrances_map.keys() or aga_tower_enabled(enabled): for region in list(potentials.keys()): if region.name == 'Hyrule Castle Ledge': enabler = world.get_region('Tower Agahnim 1', player) for r_name in potentials[region]: new_region = world.get_region(r_name, player) enable_new_entrances(new_region, connections, potentials, enabled, world, player, enabler) def aga_tower_enabled(enabled): for region_name, enabled_tuple in enabled.items(): entrance, dungeon = enabled_tuple if dungeon.name == 'Agahnims Tower': return True return False def treat_split_as_whole_dungeon(split_dungeon, name, origin_list, world, player): # what about ER dungeons? - find an example? (bad key doors 0 keys not valid) if split_dungeon and name in multiple_portal_map: possible_entrances = [] for portal_name in multiple_portal_map[name]: portal = world.get_portal(portal_name, player) portal_entrance = world.get_entrance(portal_map[portal_name][0], player) if not portal.destination and portal_entrance.parent_region.name not in world.inaccessible_regions[player]: possible_entrances.append(portal) if len(possible_entrances) == 1: single_portal = possible_entrances[0] if single_portal.door.entrance.parent_region.name in origin_list and len(origin_list) == 1: return False return split_dungeon # goals: # 1. have enough chests to be interesting (2 more than dungeon items) # 2. have a balanced amount of regions added (check) # 3. prevent soft locks due to key usage (algorithm written) # 4. rules in place to affect item placement (lamp, keys, etc. -- in rules) # 5. to be complete -- all doors linked (check, somewhat) # 6. avoid deadlocks/dead end dungeon (check) # 7. certain paths through dungeon must be possible - be able to reach goals (check) def cross_dungeon(world, player): add_inaccessible_doors(world, player) entrances_map, potentials, connections = determine_entrance_list(world, player) connections_tuple = (entrances_map, potentials, connections) all_sectors, all_regions = [], [] for key in dungeon_regions.keys(): all_regions += dungeon_regions[key] all_sectors.extend(convert_to_sectors(all_regions, world, player)) merge_sectors(all_sectors, world, player) entrances, splits = create_dungeon_entrances(world, player) dungeon_builders = create_dungeon_builders(all_sectors, connections_tuple, world, player, entrances, splits) for builder in dungeon_builders.values(): builder.entrance_list = list(entrances_map[builder.name]) dungeon_obj = world.get_dungeon(builder.name, player) for sector in builder.sectors: for region in sector.regions: region.dungeon = dungeon_obj for loc in region.locations: if loc.forced_item: key_name = dungeon_keys[builder.name] if loc.name != 'Hyrule Castle - Big Key Drop' else dungeon_bigs[builder.name] loc.forced_item = loc.item = ItemFactory(key_name, player) recombinant_builders = {} builder_info = entrances, splits, connections_tuple, world, player handle_split_dungeons(dungeon_builders, recombinant_builders, entrances_map, builder_info) main_dungeon_generation(dungeon_builders, recombinant_builders, connections_tuple, world, player) paths = determine_required_paths(world, player) check_required_paths(paths, world, player) hc = world.get_dungeon('Hyrule Castle', player) hc.dungeon_items.append(ItemFactory('Compass (Escape)', player)) at = world.get_dungeon('Agahnims Tower', player) at.dungeon_items.append(ItemFactory('Compass (Agahnims Tower)', player)) at.dungeon_items.append(ItemFactory('Map (Agahnims Tower)', player)) assign_cross_keys(dungeon_builders, world, player) all_dungeon_items_cnt = len(list(y for x in world.dungeons if x.player == player for y in x.all_items)) if world.keydropshuffle[player]: target_items = 35 if world.retro[player] else 96 else: target_items = 34 if world.retro[player] else 63 d_items = target_items - all_dungeon_items_cnt world.pool_adjustment[player] = d_items smooth_door_pairs(world, player) # Re-assign dungeon bosses gt = world.get_dungeon('Ganons Tower', player) for name, builder in dungeon_builders.items(): reassign_boss('GT Ice Armos', 'bottom', builder, gt, world, player) reassign_boss('GT Lanmolas 2', 'middle', builder, gt, world, player) reassign_boss('GT Moldorm', 'top', builder, gt, world, player) sanctuary = world.get_region('Sanctuary', player) d_name = sanctuary.dungeon.name if d_name != 'Hyrule Castle': possible_portals = [] for portal_name in dungeon_portals[d_name]: portal = world.get_portal(portal_name, player) if portal.door.name == 'Sanctuary S': possible_portals.clear() possible_portals.append(portal) break if not portal.destination and not portal.deadEnd: possible_portals.append(portal) if len(possible_portals) == 1: world.sanc_portal[player] = possible_portals[0] else: reachable_portals = [] for portal in possible_portals: start_area = portal.door.entrance.parent_region state = ExplorationState(dungeon=d_name) state.visit_region(start_area) state.add_all_doors_check_unattached(start_area, world, player) explore_state(state, world, player) if state.visited_at_all(sanctuary): reachable_portals.append(portal) world.sanc_portal[player] = random.choice(reachable_portals) if world.intensity[player] >= 3: if player in world.sanc_portal: portal = world.sanc_portal[player] else: portal = world.get_portal('Sanctuary', player) target = portal.door.entrance.parent_region connect_simple_door(world, 'Sanctuary Mirror Route', target, player) check_entrance_fixes(world, player) if world.standardize_palettes[player] == 'standardize': palette_assignment(world, player) refine_hints(dungeon_builders) refine_boss_exits(world, player) def assign_cross_keys(dungeon_builders, world, player): logging.getLogger('').info(world.fish.translate("cli", "cli", "shuffling.keydoors")) start = time.process_time() if world.retro[player]: remaining = 61 if world.keydropshuffle[player] else 29 else: remaining = len(list(x for dgn in world.dungeons if dgn.player == player for x in dgn.small_keys)) total_keys = remaining total_candidates = 0 start_regions_map = {} # Step 1: Find Small Key Door Candidates for name, builder in dungeon_builders.items(): dungeon = world.get_dungeon(name, player) if not builder.bk_required or builder.bk_provided: dungeon.big_key = None elif builder.bk_required and not builder.bk_provided: dungeon.big_key = ItemFactory(dungeon_bigs[name], player) start_regions = convert_regions(builder.path_entrances, world, player) find_small_key_door_candidates(builder, start_regions, world, player) builder.key_doors_num = max(0, len(builder.candidates) - builder.key_drop_cnt) total_candidates += builder.key_doors_num start_regions_map[name] = start_regions # Step 2: Initial Key Number Assignment & Calculate Flexibility for name, builder in dungeon_builders.items(): calculated = int(round(builder.key_doors_num*total_keys/total_candidates)) max_keys = builder.location_cnt - calc_used_dungeon_items(builder) cand_len = max(0, len(builder.candidates) - builder.key_drop_cnt) limit = min(max_keys, cand_len) suggested = min(calculated, limit) combo_size = ncr(len(builder.candidates), suggested + builder.key_drop_cnt) while combo_size > 500000 and suggested > 0: suggested -= 1 combo_size = ncr(len(builder.candidates), suggested + builder.key_drop_cnt) builder.key_doors_num = suggested + builder.key_drop_cnt remaining -= suggested builder.combo_size = combo_size if suggested < limit: builder.flex = limit - suggested # Step 3: Initial valid combination find - reduce flex if needed for name, builder in dungeon_builders.items(): suggested = builder.key_doors_num - builder.key_drop_cnt builder.total_keys = builder.key_doors_num find_valid_combination(builder, start_regions_map[name], world, player) actual_chest_keys = builder.key_doors_num - builder.key_drop_cnt if actual_chest_keys < suggested: remaining += suggested - actual_chest_keys builder.flex = 0 # Step 4: Try to assign remaining keys builder_order = [x for x in dungeon_builders.values() if x.flex > 0] builder_order.sort(key=lambda b: b.combo_size) queue = deque(builder_order) logger = logging.getLogger('') while len(queue) > 0 and remaining > 0: builder = queue.popleft() name = builder.name logger.debug('Cross Dungeon: Increasing key count by 1 for %s', name) builder.key_doors_num += 1 builder.total_keys = builder.key_doors_num result = find_valid_combination(builder, start_regions_map[name], world, player, drop_keys=False) if result: remaining -= 1 builder.flex -= 1 if builder.flex > 0: builder.combo_size = ncr(len(builder.candidates), builder.key_doors_num) queue.append(builder) queue = deque(sorted(queue, key=lambda b: b.combo_size)) else: logger.debug('Cross Dungeon: Increase failed for %s', name) builder.key_doors_num -= 1 builder.flex = 0 logger.debug('Cross Dungeon: Keys unable to assign in pool %s', remaining) # Last Step: Adjust Small Key Dungeon Pool for name, builder in dungeon_builders.items(): reassign_key_doors(builder, world, player) if not world.retro[player]: log_key_logic(builder.name, world.key_logic[player][builder.name]) actual_chest_keys = max(builder.key_doors_num - builder.key_drop_cnt, 0) dungeon = world.get_dungeon(name, player) if actual_chest_keys == 0: dungeon.small_keys = [] else: dungeon.small_keys = [ItemFactory(dungeon_keys[name], player)] * actual_chest_keys logger.info(f'{world.fish.translate('cli', 'cli', 'keydoor.shuffle.time.crossed')}: {time.process_time()-start}') def reassign_boss(boss_region, boss_key, builder, gt, world, player): if boss_region in builder.master_sector.region_set(): new_dungeon = world.get_dungeon(builder.name, player) if new_dungeon != gt: gt_boss = gt.bosses.pop(boss_key) new_dungeon.bosses[boss_key] = gt_boss def check_entrance_fixes(world, player): # I believe these modes will be fine if world.shuffle[player] not in ['insanity', 'insanity_legacy', 'madness_legacy']: checks = { 'Palace of Darkness': 'pod', 'Skull Woods Final Section': 'sw', 'Turtle Rock': 'tr', 'Ganons Tower': 'gt', } if world.mode[player] == 'inverted': del checks['Ganons Tower'] for ent_name, key in checks.items(): entrance = world.get_entrance(ent_name, player) dungeon = entrance.connected_region.dungeon if dungeon: layout = world.dungeon_layouts[player][dungeon.name] if 'Sanctuary' in layout.master_sector.region_set() or dungeon.name in ['Hyrule Castle', 'Desert Palace', 'Skull Woods', 'Turtle Rock']: portal = None for portal_name in dungeon_portals[dungeon.name]: test_portal = world.get_portal(portal_name, player) if entrance.connected_region == test_portal.door.entrance.connected_region: portal = test_portal break world.force_fix[player][key] = portal def palette_assignment(world, player): for portal in world.dungeon_portals[player]: if portal.door.roomIndex >= 0: room = world.get_room(portal.door.roomIndex, player) if room.palette is None: name = portal.door.entrance.parent_region.dungeon.name room.palette = palette_map[name][0] for name, builder in world.dungeon_layouts[player].items(): for region in builder.master_sector.regions: for ext in region.exits: if ext.door and ext.door.roomIndex >= 0 and ext.door.name not in palette_non_influencers: room = world.get_room(ext.door.roomIndex, player) if room.palette is None: room.palette = palette_map[name][0] for name, tuple in palette_map.items(): if tuple[1] is not None: door_name = boss_indicator[name][1] door = world.get_door(door_name, player) room = world.get_room(door.roomIndex, player) room.palette = tuple[1] if tuple[2]: leading_door = world.get_door(tuple[2], player) ent = next(iter(leading_door.entrance.parent_region.entrances)) if ent.door and door.roomIndex: room = world.get_room(door.roomIndex, player) room.palette = tuple[1] rat_path = world.get_region('Sewers Rat Path', player) visited_rooms = set() visited_regions = {rat_path} queue = deque([(rat_path, 0)]) while len(queue) > 0: region, dist = queue.popleft() if dist > 5: continue for ext in region.exits: if ext.door and ext.door.roomIndex >= 0 and ext.door.name not in palette_non_influencers: room_idx = ext.door.roomIndex if room_idx not in visited_rooms: room = world.get_room(room_idx, player) room.palette = 0x1 visited_rooms.add(room_idx) if ext.door and ext.door.type in [DoorType.SpiralStairs, DoorType.Ladder]: if ext.door.dest and ext.door.dest.roomIndex: visited_rooms.add(ext.door.dest.roomIndex) if ext.connected_region: visited_regions.add(ext.connected_region) elif ext.connected_region and ext.connected_region.type == RegionType.Dungeon and ext.connected_region not in visited_regions: queue.append((ext.connected_region, dist+1)) visited_regions.add(ext.connected_region) sanc = world.get_region('Sanctuary', player) if sanc.dungeon.name == 'Hyrule Castle': room = world.get_room(0x12, player) room.palette = 0x1d for connection in ['Sanctuary S', 'Sanctuary N']: adjacent = world.get_entrance(connection, player) adj_dest = adjacent.door.dest if adj_dest and isinstance(adj_dest, Door) and adj_dest.entrance.parent_region.type == RegionType.Dungeon: if adjacent.door and adjacent.door.dest and adjacent.door.dest.roomIndex >= 0: room = world.get_room(adjacent.door.dest.roomIndex, player) room.palette = 0x1d eastfairies = world.get_room(0x89, player) eastfairies.palette = palette_map[world.get_region('Eastern Courtyard', player).dungeon.name][0] # other ones that could use programmatic treatment: Skull Boss x29, Hera Fairies xa7, Ice Boss xde (Ice Fairies!) def refine_hints(dungeon_builders): for name, builder in dungeon_builders.items(): for region in builder.master_sector.regions: for location in region.locations: if not location.event and '- Boss' not in location.name and '- Prize' not in location.name and location.name != 'Sanctuary': location.hint_text = dungeon_hints[name] def refine_boss_exits(world, player): for d_name, d_boss in {'Desert Palace': 'Desert Boss', 'Skull Woods': 'Skull Boss', 'Turtle Rock': 'TR Boss'}.items(): possible_portals = [] current_boss = None for portal_name in dungeon_portals[d_name]: portal = world.get_portal(portal_name, player) if not portal.destination: possible_portals.append(portal) if portal.boss_exit_idx > -1: current_boss = portal if len(possible_portals) == 1: if possible_portals[0] != current_boss: possible_portals[0].change_boss_exit(current_boss.boss_exit_idx) current_boss.change_boss_exit(-1) else: reachable_portals = [] for portal in possible_portals: start_area = portal.door.entrance.parent_region state = ExplorationState(dungeon=d_name) state.visit_region(start_area) state.add_all_doors_check_unattached(start_area, world, player) explore_state_not_inaccessible(state, world, player) if state.visited_at_all(world.get_region(d_boss, player)): reachable_portals.append(portal) if len(reachable_portals) == 0: reachable_portals = possible_portals unreachable = world.inaccessible_regions[player] filtered = [x for x in reachable_portals if x.door.entrance.connected_region.name not in unreachable] if 0 < len(filtered) < len(reachable_portals): reachable_portals = filtered chosen_one = random.choice(reachable_portals) if len(reachable_portals) > 1 else reachable_portals[0] if chosen_one != current_boss: chosen_one.change_boss_exit(current_boss.boss_exit_idx) current_boss.change_boss_exit(-1) def convert_to_sectors(region_names, world, player): region_list = convert_regions(region_names, world, player) sectors = [] while len(region_list) > 0: region = region_list.pop() new_sector = True region_chunk = [region] exits = [] exits.extend(region.exits) outstanding_doors = [] matching_sectors = [] while len(exits) > 0: ext = exits.pop() door = ext.door if ext.connected_region is not None or door is not None and door.controller is not None: if door is not None and door.controller is not None: connect_region = world.get_entrance(door.controller.name, player).parent_region else: connect_region = ext.connected_region if connect_region not in region_chunk and connect_region in region_list: region_list.remove(connect_region) region_chunk.append(connect_region) exits.extend(connect_region.exits) if connect_region not in region_chunk: for existing in sectors: if connect_region in existing.regions: new_sector = False if existing not in matching_sectors: matching_sectors.append(existing) else: if door and not door.controller and not door.dest and not door.entranceFlag and door.type != DoorType.Logical: outstanding_doors.append(door) sector = Sector() if not new_sector: for match in matching_sectors: sector.regions.extend(match.regions) sector.outstanding_doors.extend(match.outstanding_doors) sectors.remove(match) sector.regions.extend(region_chunk) sector.outstanding_doors.extend(outstanding_doors) sectors.append(sector) return sectors def merge_sectors(all_sectors, world, player): if world.mixed_travel[player] == 'force': sectors_to_remove = {} merge_sectors = {} for sector in all_sectors: r_set = sector.region_set() if 'PoD Arena Ledge' in r_set: sectors_to_remove['Arenahover'] = sector elif 'PoD Big Chest Balcony' in r_set: sectors_to_remove['Hammerjump'] = sector elif 'Mire Chest View' in r_set: sectors_to_remove['Mire BJ'] = sector elif 'PoD Falling Bridge Ledge' in r_set: merge_sectors['Hammerjump'] = sector elif 'PoD Arena Bridge' in r_set: merge_sectors['Arenahover'] = sector elif 'Mire BK Chest Ledge' in r_set: merge_sectors['Mire BJ'] = sector for key, old_sector in sectors_to_remove.items(): merge_sectors[key].regions.extend(old_sector.regions) merge_sectors[key].outstanding_doors.extend(old_sector.outstanding_doors) all_sectors.remove(old_sector) # those with split region starts like Desert/Skull combine for key layouts def combine_layouts(recombinant_builders, dungeon_builders, entrances_map): for recombine in recombinant_builders.values(): queue = deque(dungeon_builders.values()) while len(queue) > 0: builder = queue.pop() if builder.name.startswith(recombine.name): del dungeon_builders[builder.name] if recombine.master_sector is None: recombine.master_sector = builder.master_sector recombine.master_sector.name = recombine.name else: recombine.master_sector.regions.extend(builder.master_sector.regions) recombine.layout_starts = list(entrances_map[recombine.name]) dungeon_builders[recombine.name] = recombine def valid_region_to_explore(region, world, player): return region and (region.type == RegionType.Dungeon or region.name in world.inaccessible_regions[player] or (region.name == 'Hyrule Castle Ledge' and world.mode[player] == 'standard')) def shuffle_key_doors(builder, world, player): start_regions = convert_regions(builder.path_entrances, world, player) # count number of key doors - this could be a table? num_key_doors = 0 skips = [] for region in builder.master_sector.regions: for ext in region.exits: d = world.check_for_door(ext.name, player) if d is not None and d.smallKey: if d not in skips: if d.type == DoorType.Interior: skips.append(d.dest) if d.type == DoorType.Normal: for dp in world.paired_doors[player]: if d.name == dp.door_a: skips.append(world.get_door(dp.door_b, player)) break elif d.name == dp.door_b: skips.append(world.get_door(dp.door_a, player)) break num_key_doors += 1 builder.key_doors_num = builder.total_keys = num_key_doors find_small_key_door_candidates(builder, start_regions, world, player) find_valid_combination(builder, start_regions, world, player) reassign_key_doors(builder, world, player) log_key_logic(builder.name, world.key_logic[player][builder.name]) def find_current_key_doors(builder): current_doors = [] for region in builder.master_sector.regions: for ext in region.exits: d = ext.door if d and d.smallKey: current_doors.append(d) return current_doors def find_small_key_door_candidates(builder, start_regions, world, player): # traverse dungeon and find candidates candidates = [] checked_doors = set() for region in start_regions: possible, checked = find_key_door_candidates(region, checked_doors, world, player) candidates.extend([x for x in possible if x not in candidates]) checked_doors.update(checked) flat_candidates = [] for candidate in candidates: # not valid if: Normal and Pair in is Checked and Pair is not in Candidates if candidate.type != DoorType.Normal or candidate.dest not in checked_doors or candidate.dest in candidates: flat_candidates.append(candidate) paired_candidates = build_pair_list(flat_candidates) builder.candidates = paired_candidates def calc_used_dungeon_items(builder): base = 4 if builder.bk_required and not builder.bk_provided: base += 1 # if builder.name == 'Hyrule Castle': # base -= 1 # Missing compass/map # if builder.name == 'Agahnims Tower': # base -= 2 # Missing both compass/map # gt can lose map once compasses work return base def find_valid_combination(builder, start_regions, world, player, drop_keys=True): logger = logging.getLogger('') # find valid combination of candidates if len(builder.candidates) < builder.key_doors_num: if not drop_keys: logger.info('No valid layouts for %s with %s doors', builder.name, builder.key_doors_num) return False builder.key_doors_num = len(builder.candidates) # reduce number of key doors logger.info('%s: %s', world.fish.translate("cli","cli","lowering.keys.candidates"), builder.name) combinations = ncr(len(builder.candidates), builder.key_doors_num) itr = 0 start = time.process_time() sample_list = list(range(0, int(combinations))) random.shuffle(sample_list) proposal = kth_combination(sample_list[itr], builder.candidates, builder.key_doors_num) # eliminate start region if portal marked as destination excluded = {} for region in start_regions: portal = next((x for x in world.dungeon_portals[player] if x.door.entrance.parent_region == region), None) if portal and portal.destination: excluded[region] = None start_regions = [x for x in start_regions if x not in excluded.keys()] key_layout = build_key_layout(builder, start_regions, proposal, world, player) determine_prize_lock(key_layout, world, player) while not validate_key_layout(key_layout, world, player): itr += 1 stop_early = False if itr % 1000 == 0: mark = time.process_time()-start if (mark > 10 and itr*100/combinations > 50) or (mark > 20 and itr*100/combinations > 25) or mark > 30: stop_early = True if itr >= combinations or stop_early: if not drop_keys: logger.info('No valid layouts for %s with %s doors', builder.name, builder.key_doors_num) return False logger.info('%s: %s', world.fish.translate("cli","cli","lowering.keys.layouts"), builder.name) builder.key_doors_num -= 1 if builder.key_doors_num < 0: raise Exception('Bad dungeon %s - 0 key doors not valid' % builder.name) combinations = ncr(len(builder.candidates), builder.key_doors_num) sample_list = list(range(0, int(combinations))) random.shuffle(sample_list) itr = 0 start = time.process_time() # reset time since itr reset proposal = kth_combination(sample_list[itr], builder.candidates, builder.key_doors_num) key_layout.reset(proposal, builder, world, player) if (itr+1) % 1000 == 0: mark = time.process_time()-start logger.info('%s time elapsed. %s iterations/s', mark, itr/mark) # make changes if player not in world.key_logic.keys(): world.key_logic[player] = {} analyze_dungeon(key_layout, world, player) builder.key_door_proposal = proposal world.key_logic[player][builder.name] = key_layout.key_logic world.key_layout[player][builder.name] = key_layout return True def log_key_logic(d_name, key_logic): logger = logging.getLogger('') if logger.isEnabledFor(logging.DEBUG): logger.debug('Key Logic for %s', d_name) if len(key_logic.bk_restricted) > 0: logger.debug('-BK Restrictions') for restriction in key_logic.bk_restricted: logger.debug(restriction) if len(key_logic.sm_restricted) > 0: logger.debug('-Small Restrictions') for restriction in key_logic.sm_restricted: logger.debug(restriction) for key in key_logic.door_rules.keys(): rule = key_logic.door_rules[key] logger.debug('--Rule for %s: Nrm:%s Allow:%s Loc:%s Alt:%s', key, rule.small_key_num, rule.allow_small, rule.small_location, rule.alternate_small_key) if rule.alternate_small_key is not None: for loc in rule.alternate_big_key_loc: logger.debug('---BK Loc %s', loc.name) logger.debug('Placement rules for %s', d_name) for rule in key_logic.placement_rules: logger.debug('*Rule for %s:', rule.door_reference) if rule.bk_conditional_set: logger.debug('**BK Checks %s', ','.join([x.name for x in rule.bk_conditional_set])) logger.debug('**BK Blocked (%s) : %s', rule.needed_keys_wo_bk, ','.join([x.name for x in rule.check_locations_wo_bk])) if rule.needed_keys_w_bk: logger.debug('**BK Available (%s) : %s', rule.needed_keys_w_bk, ','.join([x.name for x in rule.check_locations_w_bk])) def build_pair_list(flat_list): paired_list = [] queue = deque(flat_list) while len(queue) > 0: d = queue.pop() if d.dest in queue and d.type != DoorType.SpiralStairs: paired_list.append((d, d.dest)) queue.remove(d.dest) else: paired_list.append(d) return paired_list def flatten_pair_list(paired_list): flat_list = [] for d in paired_list: if type(d) is tuple: flat_list.append(d[0]) flat_list.append(d[1]) else: flat_list.append(d) return flat_list okay_normals = [DoorKind.Normal, DoorKind.SmallKey, DoorKind.Bombable, DoorKind.Dashable, DoorKind.DungeonChanger] def find_key_door_candidates(region, checked, world, player): dungeon = region.dungeon candidates = [] checked_doors = list(checked) queue = deque([(region, None, None)]) while len(queue) > 0: current, last_door, last_region = queue.pop() for ext in current.exits: d = ext.door if d and d.controller: d = d.controller if d and not d.blocked and not d.entranceFlag and d.dest is not last_door and d.dest is not last_region and d not in checked_doors: valid = False if 0 <= d.doorListPos < 4 and d.type in [DoorType.Interior, DoorType.Normal, DoorType.SpiralStairs]: room = world.get_room(d.roomIndex, player) position, kind = room.doorList[d.doorListPos] if d.type == DoorType.Interior: valid = kind in [DoorKind.Normal, DoorKind.SmallKey, DoorKind.Bombable, DoorKind.Dashable] elif d.type == DoorType.SpiralStairs: valid = kind in [DoorKind.StairKey, DoorKind.StairKey2, DoorKind.StairKeyLow] elif d.type == DoorType.Normal: d2 = d.dest if d2 not in candidates: if d2.type == DoorType.Normal: room_b = world.get_room(d2.roomIndex, player) pos_b, kind_b = room_b.doorList[d2.doorListPos] valid = kind in okay_normals and kind_b in okay_normals and valid_key_door_pair(d, d2) else: valid = kind in okay_normals if valid and 0 <= d2.doorListPos < 4: candidates.append(d2) else: valid = True if valid and d not in candidates: candidates.append(d) connected = ext.connected_region if connected and (connected.type != RegionType.Dungeon or connected.dungeon == dungeon): queue.append((ext.connected_region, d, current)) if d is not None: checked_doors.append(d) return candidates, checked_doors def valid_key_door_pair(door1, door2): if door1.roomIndex != door2.roomIndex: return True return len(door1.entrance.parent_region.exits) <= 1 or len(door2.entrance.parent_region.exits) <= 1 def reassign_key_doors(builder, world, player): logger = logging.getLogger('') logger.debug('Key doors for %s', builder.name) proposal = builder.key_door_proposal flat_proposal = flatten_pair_list(proposal) queue = deque(find_current_key_doors(builder)) while len(queue) > 0: d = queue.pop() if d.type is DoorType.SpiralStairs and d not in proposal: room = world.get_room(d.roomIndex, player) if room.doorList[d.doorListPos][1] == DoorKind.StairKeyLow: room.delete(d.doorListPos) else: if len(room.doorList) > 1: room.mirror(d.doorListPos) # I think this works for crossed now else: room.delete(d.doorListPos) d.smallKey = False elif d.type is DoorType.Interior and d not in flat_proposal and d.dest not in flat_proposal: if not d.entranceFlag: world.get_room(d.roomIndex, player).change(d.doorListPos, DoorKind.Normal) d.smallKey = False d.dest.smallKey = False queue.remove(d.dest) elif d.type is DoorType.Normal and d not in flat_proposal: if not d.entranceFlag: world.get_room(d.roomIndex, player).change(d.doorListPos, DoorKind.Normal) d.smallKey = False for dp in world.paired_doors[player]: if dp.door_a == d.name or dp.door_b == d.name: dp.pair = False for obj in proposal: if type(obj) is tuple: d1 = obj[0] d2 = obj[1] if d1.type is DoorType.Interior: change_door_to_small_key(d1, world, player) d2.smallKey = True # ensure flag is set else: names = [d1.name, d2.name] found = False for dp in world.paired_doors[player]: if dp.door_a in names and dp.door_b in names: dp.pair = True found = True elif dp.door_a in names: dp.pair = False elif dp.door_b in names: dp.pair = False if not found: world.paired_doors[player].append(PairedDoor(d1.name, d2.name)) change_door_to_small_key(d1, world, player) change_door_to_small_key(d2, world, player) world.spoiler.set_door_type(d1.name+' <-> '+d2.name, 'Key Door', player) logger.debug('Key Door: %s', d1.name+' <-> '+d2.name) else: d = obj if d.type is DoorType.Interior: change_door_to_small_key(d, world, player) d.dest.smallKey = True # ensure flag is set elif d.type is DoorType.SpiralStairs: pass # we don't have spiral stairs candidates yet that aren't already key doors elif d.type is DoorType.Normal: change_door_to_small_key(d, world, player) world.spoiler.set_door_type(d.name, 'Key Door', player) logger.debug('Key Door: %s', d.name) def change_door_to_small_key(d, world, player): d.smallKey = True room = world.get_room(d.roomIndex, player) if room.doorList[d.doorListPos][1] != DoorKind.SmallKey: room.change(d.doorListPos, DoorKind.SmallKey) def smooth_door_pairs(world, player): all_doors = [x for x in world.doors if x.player == player] skip = set() bd_candidates = defaultdict(list) for door in all_doors: if door.type in [DoorType.Normal, DoorType.Interior] and door not in skip and not door.entranceFlag: partner = door.dest skip.add(partner) room_a = world.get_room(door.roomIndex, player) type_a = room_a.kind(door) if partner.type in [DoorType.Normal, DoorType.Interior]: room_b = world.get_room(partner.roomIndex, player) type_b = room_b.kind(partner) valid_pair = stateful_door(door, type_a) and stateful_door(partner, type_b) else: valid_pair, room_b, type_b = False, None, None if door.type == DoorType.Normal: if type_a == DoorKind.SmallKey or type_b == DoorKind.SmallKey: if valid_pair: if type_a != DoorKind.SmallKey: room_a.change(door.doorListPos, DoorKind.SmallKey) if type_b != DoorKind.SmallKey: room_b.change(partner.doorListPos, DoorKind.SmallKey) add_pair(door, partner, world, player) else: if type_a == DoorKind.SmallKey: remove_pair(door, world, player) if type_b == DoorKind.SmallKey: remove_pair(door, world, player) else: if valid_pair: bd_candidates[door.entrance.parent_region.dungeon].append(door) elif type_a in [DoorKind.Bombable, DoorKind.Dashable] or type_b in [DoorKind.Bombable, DoorKind.Dashable]: if type_a in [DoorKind.Bombable, DoorKind.Dashable]: room_a.change(door.doorListPos, DoorKind.Normal) remove_pair(door, world, player) else: room_b.change(partner.doorListPos, DoorKind.Normal) remove_pair(partner, world, player) elif valid_pair and type_a != DoorKind.SmallKey and type_b != DoorKind.SmallKey: bd_candidates[door.entrance.parent_region.dungeon].append(door) shuffle_bombable_dashable(bd_candidates, world, player) world.paired_doors[player] = [x for x in world.paired_doors[player] if x.pair or x.original] def add_pair(door_a, door_b, world, player): pair_a, pair_b = None, None for paired_door in world.paired_doors[player]: if paired_door.door_a == door_a.name and paired_door.door_b == door_b.name: paired_door.pair = True return if paired_door.door_a == door_b.name and paired_door.door_b == door_a.name: paired_door.pair = True return if paired_door.door_a == door_a.name or paired_door.door_b == door_a.name: pair_a = paired_door if paired_door.door_a == door_b.name or paired_door.door_b == door_b.name: pair_b = paired_door if pair_a: pair_a.pair = False if pair_b: pair_b.pair = False world.paired_doors[player].append(PairedDoor(door_a, door_b)) def remove_pair(door, world, player): for paired_door in world.paired_doors[player]: if paired_door.door_a == door.name or paired_door.door_b == door.name: paired_door.pair = False break def stateful_door(door, kind): if 0 <= door.doorListPos < 4: return kind in [DoorKind.Normal, DoorKind.SmallKey, DoorKind.Bombable, DoorKind.Dashable] #, DoorKind.BigKey] return False def shuffle_bombable_dashable(bd_candidates, world, player): if world.doorShuffle[player] == 'basic': for dungeon, candidates in bd_candidates.items(): diff = bomb_dash_counts[dungeon.name][1] if diff > 0: for chosen in random.sample(candidates, min(diff, len(candidates))): change_pair_type(chosen, DoorKind.Dashable, world, player) candidates.remove(chosen) diff = bomb_dash_counts[dungeon.name][0] if diff > 0: for chosen in random.sample(candidates, min(diff, len(candidates))): change_pair_type(chosen, DoorKind.Bombable, world, player) candidates.remove(chosen) for excluded in candidates: remove_pair_type_if_present(excluded, world, player) elif world.doorShuffle[player] == 'crossed': all_candidates = sum(bd_candidates.values(), []) for chosen in random.sample(all_candidates, min(8, len(all_candidates))): change_pair_type(chosen, DoorKind.Dashable, world, player) all_candidates.remove(chosen) for chosen in random.sample(all_candidates, min(12, len(all_candidates))): change_pair_type(chosen, DoorKind.Bombable, world, player) all_candidates.remove(chosen) for excluded in all_candidates: remove_pair_type_if_present(excluded, world, player) def change_pair_type(door, new_type, world, player): room_a = world.get_room(door.roomIndex, player) room_a.change(door.doorListPos, new_type) if door.type != DoorType.Interior: room_b = world.get_room(door.dest.roomIndex, player) room_b.change(door.dest.doorListPos, new_type) add_pair(door, door.dest, world, player) spoiler_type = 'Bomb Door' if new_type == DoorKind.Bombable else 'Dash Door' world.spoiler.set_door_type(door.name + ' <-> ' + door.dest.name, spoiler_type, player) def remove_pair_type_if_present(door, world, player): room_a = world.get_room(door.roomIndex, player) if room_a.kind(door) in [DoorKind.Bombable, DoorKind.Dashable]: room_a.change(door.doorListPos, DoorKind.Normal) if door.type != DoorType.Interior: remove_pair(door, world, player) if door.type != DoorType.Interior: room_b = world.get_room(door.dest.roomIndex, player) if room_b.kind(door.dest) in [DoorKind.Bombable, DoorKind.Dashable]: room_b.change(door.dest.doorListPos, DoorKind.Normal) remove_pair(door.dest, world, player) def find_inaccessible_regions(world, player): world.inaccessible_regions[player] = [] if world.mode[player] != 'inverted': start_regions = ['Links House', 'Sanctuary'] else: start_regions = ['Links House', 'Dark Sanctuary Hint'] regs = convert_regions(start_regions, world, player) all_regions = [r for r in world.regions if r.player == player and r.type is not RegionType.Dungeon] visited_regions = set() queue = deque(regs) while len(queue) > 0: next_region = queue.popleft() visited_regions.add(next_region) if next_region.name == 'Dark Sanctuary Hint': # special spawn point in cave for ent in next_region.entrances: parent = ent.parent_region if parent and parent.type is not RegionType.Dungeon and parent not in queue and parent not in visited_regions: queue.append(parent) for ext in next_region.exits: connect = ext.connected_region if connect and connect not in queue and connect not in visited_regions: if connect.type is not RegionType.Dungeon or connect.name.endswith(' Portal'): queue.append(connect) world.inaccessible_regions[player].extend([r.name for r in all_regions if r not in visited_regions and valid_inaccessible_region(r)]) if (world.mode[player] == 'inverted') != (0x1b in world.owswaps[player][0] and world.owMixed[player]): ledge = world.get_region('Hyrule Castle Ledge', player) if any(x for x in ledge.exits if x.connected_region and x.connected_region.name == 'Agahnims Tower Portal'): world.inaccessible_regions[player].append('Hyrule Castle Ledge') logger = logging.getLogger('') logger.debug('Inaccessible Regions:') for r in world.inaccessible_regions[player]: logger.debug('%s', r) def find_accessible_entrances(world, player, builder): entrances = [region.name for region in (portal.door.entrance.parent_region for portal in world.dungeon_portals[player]) if region.dungeon.name == builder.name] entrances.extend(drop_entrances[builder.name]) if world.mode[player] == 'standard' and builder.name == 'Hyrule Castle': start_regions = ['Hyrule Castle Courtyard'] elif world.mode[player] != 'inverted': start_regions = ['Links House', 'Sanctuary'] else: start_regions = ['Links House', 'Dark Sanctuary Hint'] if (world.mode[player] == 'inverted') != (0x1b in world.owswaps[player][0] and world.owMixed[player]): start_regions.append('Hyrule Castle Ledge') regs = convert_regions(start_regions, world, player) visited_regions = set() visited_entrances = [] # Add Sanctuary as an additional entrance in open mode, since you can save and quit to there if world.mode[player] == 'open' and world.get_region('Sanctuary', player).dungeon.name == builder.name and 'Sanctuary' not in entrances: entrances.append('Sanctuary') visited_entrances.append('Sanctuary') regs.remove(world.get_region('Sanctuary', player)) queue = deque(regs) while len(queue) > 0: next_region = queue.popleft() visited_regions.add(next_region) if (world.mode[player] == 'inverted') != (0x1b in world.owswaps[player][0] and world.owMixed[player]) and next_region.name == 'Tower Agahnim 1': connect = world.get_region('Hyrule Castle Ledge', player) if connect not in queue and connect not in visited_regions: queue.append(connect) for ext in next_region.exits: connect = ext.connected_region if connect is None or ext.door and ext.door.blocked: continue if world.mode[player] == 'standard' and builder.name == 'Hyrule Castle' and (ext.name.startswith('Flute From') or ext.name in ['Hyrule Castle Main Gate (North)', 'Top of Pyramid (Inner)', 'Inverted Pyramid Entrance']): continue if connect.name in entrances and connect not in visited_entrances: visited_entrances.append(connect.name) elif connect and connect not in queue and connect not in visited_regions: queue.append(connect) return visited_entrances def valid_inaccessible_region(r): return r.type is not RegionType.Cave or (len(r.exits) > 0 and r.name not in ['Links House', 'Chris Houlihan Room']) def add_inaccessible_doors(world, player): if world.mode[player] == 'standard': create_doors_for_inaccessible_region('Hyrule Castle Ledge', world, player) # todo: ignore standard mode hyrule castle ledge? for inaccessible_region in world.inaccessible_regions[player]: create_doors_for_inaccessible_region(inaccessible_region, world, player) def create_doors_for_inaccessible_region(inaccessible_region, world, player): region = world.get_region(inaccessible_region, player) for ext in region.exits: create_door(world, player, ext.name, region.name) if ext.connected_region is None: logging.getLogger('').warning('Exit not connected to any region: %s', ext.name) elif ext.connected_region.name.endswith(' Portal'): for more_exts in ext.connected_region.exits: create_door(world, player, more_exts.name, ext.connected_region.name) def create_door(world, player, entName, region_name): entrance = world.get_entrance(entName, player) connect = entrance.connected_region if connect is not None: for ext in connect.exits: if ext.connected_region is not None and ext.connected_region.name == region_name: d = Door(player, ext.name, DoorType.Logical, ext), world.doors += d connect_door_only(world, ext.name, ext.connected_region, player) d = Door(player, entName, DoorType.Logical, entrance), world.doors += d connect_door_only(world, entName, connect, player) def check_required_paths(paths, world, player): for dungeon_name in paths.keys(): if dungeon_name in world.dungeon_layouts[player].keys(): builder = world.dungeon_layouts[player][dungeon_name] if len(paths[dungeon_name]) > 0: states_to_explore = {} for path in paths[dungeon_name]: if type(path) is tuple: states_to_explore[tuple([path[0]])] = (path[1], 'any') else: common_starts = tuple(builder.path_entrances) if common_starts not in states_to_explore: states_to_explore[common_starts] = ([], 'all') states_to_explore[common_starts][0].append(path) cached_initial_state = None for start_regs, info in states_to_explore.items(): dest_regs, path_type = info if type(dest_regs) is not list: dest_regs = [dest_regs] check_paths = convert_regions(dest_regs, world, player) start_regions = convert_regions(start_regs, world, player) initial = start_regs == tuple(builder.path_entrances) if not initial or cached_initial_state is None: init = determine_init_crystal(initial, cached_initial_state, start_regions) state = ExplorationState(init, dungeon_name) for region in start_regions: state.visit_region(region) state.add_all_doors_check_unattached(region, world, player) explore_state(state, world, player) if initial and cached_initial_state is None: cached_initial_state = state else: state = cached_initial_state if path_type == 'any': valid, bad_region = check_if_any_regions_visited(state, check_paths) else: valid, bad_region = check_if_all_regions_visited(state, check_paths) if not valid: if check_for_pinball_fix(state, bad_region, world, player): explore_state(state, world, player) if path_type == 'any': valid, bad_region = check_if_any_regions_visited(state, check_paths) else: valid, bad_region = check_if_all_regions_visited(state, check_paths) if not valid: raise Exception('%s cannot reach %s' % (dungeon_name, bad_region.name)) def determine_init_crystal(initial, state, start_regions): if initial or state is None: return CrystalBarrier.Orange if len(start_regions) > 1: raise NotImplementedError('Path checking for multiple start regions (not the entrances) not implemented, use more paths instead') start_region = start_regions[0] if start_region in state.visited_blue and start_region in state.visited_orange: return CrystalBarrier.Either elif start_region in state.visited_blue: return CrystalBarrier.Blue elif start_region in state.visited_orange: return CrystalBarrier.Orange else: raise Exception(f'Can\'t get to {start_region.name} from initial state') # raise Exception(f'Can\'t get to {start_region.name} from initial state\n{state.dungeon}\n{state.found_locations}') def explore_state(state, world, player): while len(state.avail_doors) > 0: door = state.next_avail_door().door connect_region = world.get_entrance(door.name, player).connected_region if state.can_traverse(door) and not state.visited(connect_region) and valid_region_to_explore(connect_region, world, player): state.visit_region(connect_region) state.add_all_doors_check_unattached(connect_region, world, player) def explore_state_not_inaccessible(state, world, player): while len(state.avail_doors) > 0: door = state.next_avail_door().door connect_region = world.get_entrance(door.name, player).connected_region if state.can_traverse(door) and not state.visited(connect_region) and connect_region.type == RegionType.Dungeon: state.visit_region(connect_region) state.add_all_doors_check_unattached(connect_region, world, player) def check_if_any_regions_visited(state, check_paths): valid = False breaking_region = None for region_target in check_paths: if state.visited_at_all(region_target): valid = True break elif not breaking_region: breaking_region = region_target return valid, breaking_region def check_if_all_regions_visited(state, check_paths): for region_target in check_paths: if not state.visited_at_all(region_target): return False, region_target return True, None def check_for_pinball_fix(state, bad_region, world, player): pinball_region = world.get_region('Skull Pinball', player) # todo: lobby shuffle if bad_region.name == 'Skull 2 West Lobby' and state.visited_at_all(pinball_region): # revisit this for entrance shuffle door = world.get_door('Skull Pinball WS', player) room = world.get_room(door.roomIndex, player) if room.doorList[door.doorListPos][1] == DoorKind.Trap: room.change(door.doorListPos, DoorKind.Normal) door.trapFlag = 0x0 door.blocked = False connect_two_way(world, door.name, door.dest.name, player) state.add_all_doors_check_unattached(pinball_region, world, player) return True return False @unique class DROptions(Flag): NoOptions = 0x00 Eternal_Mini_Bosses = 0x01 # If on, GT minibosses marked as defeated when they try to spawn a heart Town_Portal = 0x02 # If on, Players will start with mirror scroll Map_Info = 0x04 Debug = 0x08 Fix_EG = 0x10 # used to be Rails = 0x10 # Unused bit now OriginalPalettes = 0x20 # Open_PoD_Wall = 0x40 # No longer pre-opening pod wall - unused # Open_Desert_Wall = 0x80 # No longer pre-opening desert wall - unused Hide_Total = 0x100 DarkWorld_Spawns = 0x200 # DATA GOES DOWN HERE logical_connections = [ ('Hyrule Dungeon North Abyss Catwalk Dropdown', 'Hyrule Dungeon North Abyss'), ('Hyrule Dungeon Cellblock Door', 'Hyrule Dungeon Cell'), ('Hyrule Dungeon Cell Exit', 'Hyrule Dungeon Cellblock'), ('Hyrule Castle Throne Room Tapestry', 'Hyrule Castle Behind Tapestry'), ('Hyrule Castle Tapestry Backwards', 'Hyrule Castle Throne Room'), ('Sewers Secret Room Push Block', 'Sewers Secret Room Blocked Path'), ('Eastern Hint Tile Push Block', 'Eastern Hint Tile'), ('Eastern Map Balcony Hook Path', 'Eastern Map Room'), ('Eastern Map Room Drop Down', 'Eastern Map Balcony'), ('Desert Main Lobby Left Path', 'Desert Left Alcove'), ('Desert Main Lobby Right Path', 'Desert Right Alcove'), ('Desert Left Alcove Path', 'Desert Main Lobby'), ('Desert Right Alcove Path', 'Desert Main Lobby'), ('Hera Lobby to Front Barrier - Blue', 'Hera Front'), ('Hera Front to Lobby Barrier - Blue', 'Hera Lobby'), ('Hera Lobby to Crystal', 'Hera Lobby - Crystal'), ('Hera Lobby Crystal Exit', 'Hera Lobby'), ('Hera Front to Crystal', 'Hera Front - Crystal'), ('Hera Front to Back Bypass', 'Hera Back'), ('Hera Front Crystal Exit', 'Hera Front'), ('Hera Front to Down Stairs Barrier - Blue', 'Hera Down Stairs Landing'), ('Hera Front to Up Stairs Barrier - Orange', 'Hera Up Stairs Landing'), ('Hera Front to Back Barrier - Orange', 'Hera Back'), ('Hera Down Stairs to Front Barrier - Blue', 'Hera Front'), ('Hera Down Stairs Landing to Ranged Crystal', 'Hera Down Stairs Landing - Ranged Crystal'), ('Hera Down Stairs Landing Ranged Crystal Exit', 'Hera Down Stairs Landing'), ('Hera Up Stairs to Front Barrier - Orange', 'Hera Front'), ('Hera Up Stairs Landing to Ranged Crystal', 'Hera Up Stairs Landing - Ranged Crystal'), ('Hera Up Stairs Landing Ranged Crystal Exit', 'Hera Up Stairs Landing'), ('Hera Back to Front Barrier - Orange', 'Hera Front'), ('Hera Back to Ranged Crystal', 'Hera Back - Ranged Crystal'), ('Hera Back Ranged Crystal Exit', 'Hera Back'), ('Hera Basement Cage to Crystal', 'Hera Basement Cage - Crystal'), ('Hera Basement Cage Crystal Exit', 'Hera Basement Cage'), ('Hera Tridorm to Crystal', 'Hera Tridorm - Crystal'), ('Hera Tridorm Crystal Exit', 'Hera Tridorm'), ('Hera Startile Wide to Crystal', 'Hera Startile Wide - Crystal'), ('Hera Startile Wide Crystal Exit', 'Hera Startile Wide'), ('Hera Big Chest Hook Path', 'Hera Big Chest Landing'), ('Hera Big Chest Landing Exit', 'Hera 4F'), ('PoD Pit Room Block Path N', 'PoD Pit Room Blocked'), ('PoD Pit Room Block Path S', 'PoD Pit Room'), ('PoD Arena Landing Bonk Path', 'PoD Arena Bridge'), ('PoD Arena North Drop Down', 'PoD Arena Main'), ('PoD Arena Bridge Drop Down', 'PoD Arena Main'), ('PoD Arena North to Landing Barrier - Orange', 'PoD Arena Landing'), ('PoD Arena Main to Ranged Crystal', 'PoD Arena Main - Ranged Crystal'), ('PoD Arena Main to Landing Barrier - Blue', 'PoD Arena Landing'), ('PoD Arena Main to Landing Bypass', 'PoD Arena Landing'), ('PoD Arena Main to Right Bypass', 'PoD Arena Right'), ('PoD Arena Main Ranged Crystal Exit', 'PoD Arena Main'), ('PoD Arena Bridge to Ranged Crystal', 'PoD Arena Bridge - Ranged Crystal'), ('PoD Arena Bridge Ranged Crystal Exit', 'PoD Arena Bridge'), ('PoD Arena Landing to Main Barrier - Blue', 'PoD Arena Main'), ('PoD Arena Landing to Right Barrier - Blue', 'PoD Arena Right'), ('PoD Arena Landing to North Barrier - Orange', 'PoD Arena North'), ('PoD Arena Right to Landing Barrier - Blue', 'PoD Arena Landing'), ('PoD Arena Right to Ranged Crystal', 'PoD Arena Right - Ranged Crystal'), ('PoD Arena Right Ranged Crystal Exit', 'PoD Arena Right'), ('PoD Arena Ledge to Ranged Crystal', 'PoD Arena Ledge - Ranged Crystal'), ('PoD Arena Ledge Ranged Crystal Exit', 'PoD Arena Ledge'), ('PoD Map Balcony Drop Down', 'PoD Sexy Statue'), ('PoD Map Balcony to Ranged Crystal', 'PoD Map Balcony - Ranged Crystal'), ('PoD Map Balcony Ranged Crystal Exit', 'PoD Map Balcony'), ('PoD Basement Ledge Drop Down', 'PoD Stalfos Basement'), ('PoD Falling Bridge Path N', 'PoD Falling Bridge Ledge'), ('PoD Falling Bridge Path S', 'PoD Falling Bridge'), ('PoD Bow Statue Left to Right Barrier - Orange', 'PoD Bow Statue Right'), ('PoD Bow Statue Left to Right Bypass', 'PoD Bow Statue Right'), ('PoD Bow Statue Left to Crystal', 'PoD Bow Statue Left - Crystal'), ('PoD Bow Statue Left Crystal Exit', 'PoD Bow Statue Left'), ('PoD Bow Statue Right to Left Barrier - Orange', 'PoD Bow Statue Left'), ('PoD Bow Statue Right to Ranged Crystal', 'PoD Bow Statue Right - Ranged Crystal'), ('PoD Bow Statue Ranged Crystal Exit', 'PoD Bow Statue Right'), ('PoD Dark Pegs Landing to Right', 'PoD Dark Pegs Right'), ('PoD Dark Pegs Landing to Ranged Crystal', 'PoD Dark Pegs Landing - Ranged Crystal'), ('PoD Dark Pegs Right to Landing', 'PoD Dark Pegs Landing'), ('PoD Dark Pegs Right to Middle Barrier - Orange', 'PoD Dark Pegs Middle'), ('PoD Dark Pegs Right to Middle Bypass', 'PoD Dark Pegs Middle'), ('PoD Dark Pegs Middle to Right Barrier - Orange', 'PoD Dark Pegs Right'), ('PoD Dark Pegs Middle to Left Barrier - Blue', 'PoD Dark Pegs Left'), ('PoD Dark Pegs Middle to Ranged Crystal', 'PoD Dark Pegs Middle - Ranged Crystal'), ('PoD Dark Pegs Left to Middle Barrier - Blue', 'PoD Dark Pegs Middle'), ('PoD Dark Pegs Left to Ranged Crystal', 'PoD Dark Pegs Left - Ranged Crystal'), ('PoD Dark Pegs Landing Ranged Crystal Exit', 'PoD Dark Pegs Landing'), ('PoD Dark Pegs Middle Ranged Crystal Exit', 'PoD Dark Pegs Middle'), ('PoD Dark Pegs Middle to Left Bypass', 'PoD Dark Pegs Left'), ('PoD Dark Pegs Left Ranged Crystal Exit', 'PoD Dark Pegs Left'), ('Swamp Lobby Moat', 'Swamp Entrance'), ('Swamp Entrance Moat', 'Swamp Lobby'), ('Swamp Trench 1 Approach Dry', 'Swamp Trench 1 Nexus'), ('Swamp Trench 1 Approach Key', 'Swamp Trench 1 Key Ledge'), ('Swamp Trench 1 Approach Swim Depart', 'Swamp Trench 1 Departure'), ('Swamp Trench 1 Nexus Approach', 'Swamp Trench 1 Approach'), ('Swamp Trench 1 Nexus Key', 'Swamp Trench 1 Key Ledge'), ('Swamp Trench 1 Key Ledge Dry', 'Swamp Trench 1 Nexus'), ('Swamp Trench 1 Key Approach', 'Swamp Trench 1 Approach'), ('Swamp Trench 1 Key Ledge Depart', 'Swamp Trench 1 Departure'), ('Swamp Trench 1 Departure Dry', 'Swamp Trench 1 Nexus'), ('Swamp Trench 1 Departure Approach', 'Swamp Trench 1 Approach'), ('Swamp Trench 1 Departure Key', 'Swamp Trench 1 Key Ledge'), ('Swamp Hub Hook Path', 'Swamp Hub North Ledge'), ('Swamp Hub North Ledge Drop Down', 'Swamp Hub'), ('Swamp Crystal Switch Outer to Inner Barrier - Blue', 'Swamp Crystal Switch Inner'), ('Swamp Crystal Switch Outer to Ranged Crystal', 'Swamp Crystal Switch Outer - Ranged Crystal'), ('Swamp Crystal Switch Outer to Inner Bypass', 'Swamp Crystal Switch Inner'), ('Swamp Crystal Switch Outer Ranged Crystal Exit', 'Swamp Crystal Switch Outer'), ('Swamp Crystal Switch Inner to Outer Barrier - Blue', 'Swamp Crystal Switch Outer'), ('Swamp Crystal Switch Inner to Outer Bypass', 'Swamp Crystal Switch Outer'), ('Swamp Crystal Switch Inner to Crystal', 'Swamp Crystal Switch Inner - Crystal'), ('Swamp Crystal Switch Inner Crystal Exit', 'Swamp Crystal Switch Inner'), ('Swamp Compass Donut Push Block', 'Swamp Donut Top'), ('Swamp Shortcut Blue Barrier', 'Swamp Trench 2 Pots'), ('Swamp Trench 2 Pots Blue Barrier', 'Swamp Shortcut'), ('Swamp Trench 2 Pots Dry', 'Swamp Trench 2 Blocks'), ('Swamp Trench 2 Pots Wet', 'Swamp Trench 2 Departure'), ('Swamp Trench 2 Blocks Pots', 'Swamp Trench 2 Pots'), ('Swamp Trench 2 Departure Wet', 'Swamp Trench 2 Pots'), ('Swamp West Shallows Push Blocks', 'Swamp West Block Path'), ('Swamp West Block Path Drop Down', 'Swamp West Shallows'), ('Swamp West Ledge Drop Down', 'Swamp West Shallows'), ('Swamp West Ledge Hook Path', 'Swamp Barrier Ledge'), ('Swamp Barrier Ledge Drop Down', 'Swamp West Shallows'), ('Swamp Barrier Ledge - Orange', 'Swamp Barrier'), ('Swamp Barrier - Orange', 'Swamp Barrier Ledge'), ('Swamp Barrier Ledge Hook Path', 'Swamp West Ledge'), ('Swamp Drain Right Switch', 'Swamp Drain Left'), ('Swamp Flooded Spot Ladder', 'Swamp Flooded Room'), ('Swamp Flooded Room Ladder', 'Swamp Flooded Spot'), ('Skull Pot Circle Star Path', 'Skull Map Room'), ('Skull Big Chest Hookpath', 'Skull 1 Lobby'), ('Skull Back Drop Star Path', 'Skull Small Hall'), ('Thieves Rail Ledge Drop Down', 'Thieves BK Corner'), ('Thieves Hellway Orange Barrier', 'Thieves Hellway S Crystal'), ('Thieves Hellway Crystal Orange Barrier', 'Thieves Hellway'), ('Thieves Hellway Blue Barrier', 'Thieves Hellway N Crystal'), ('Thieves Hellway Crystal Blue Barrier', 'Thieves Hellway'), ('Thieves Attic Orange Barrier', 'Thieves Attic Hint'), ('Thieves Attic Hint Orange Barrier', 'Thieves Attic'), ('Thieves Basement Block Path', 'Thieves Blocked Entry'), ('Thieves Blocked Entry Path', 'Thieves Basement Block'), ('Thieves Conveyor Bridge Block Path', 'Thieves Conveyor Block'), ('Thieves Conveyor Block Path', 'Thieves Conveyor Bridge'), ("Thieves Blind's Cell Door", "Thieves Blind's Cell Interior"), ("Thieves Blind's Cell Exit", "Thieves Blind's Cell"), ('Ice Cross Bottom Push Block Left', 'Ice Floor Switch'), ('Ice Cross Right Push Block Top', 'Ice Bomb Drop'), ('Ice Conveyor to Crystal', 'Ice Conveyor - Crystal'), ('Ice Conveyor Crystal Exit', 'Ice Conveyor'), ('Ice Big Key Push Block', 'Ice Dead End'), ('Ice Bomb Jump Ledge Orange Barrier', 'Ice Bomb Jump Catwalk'), ('Ice Bomb Jump Catwalk Orange Barrier', 'Ice Bomb Jump Ledge'), ('Ice Hookshot Ledge Path', 'Ice Hookshot Balcony'), ('Ice Hookshot Balcony Path', 'Ice Hookshot Ledge'), ('Ice Crystal Right Orange Barrier', 'Ice Crystal Left'), ('Ice Crystal Left Orange Barrier', 'Ice Crystal Right'), ('Ice Crystal Left Blue Barrier', 'Ice Crystal Block'), ('Ice Crystal Block Exit', 'Ice Crystal Left'), ('Ice Big Chest Landing Push Blocks', 'Ice Big Chest View'), ('Ice Refill to Crystal', 'Ice Refill - Crystal'), ('Ice Refill Crystal Exit', 'Ice Refill'), ('Mire Lobby Gap', 'Mire Post-Gap'), ('Mire Post-Gap Gap', 'Mire Lobby'), ('Mire Hub Upper Blue Barrier', 'Mire Hub Switch'), ('Mire Hub Lower Blue Barrier', 'Mire Hub Right'), ('Mire Hub Right Blue Barrier', 'Mire Hub'), ('Mire Hub Top Blue Barrier', 'Mire Hub Switch'), ('Mire Hub Switch Blue Barrier N', 'Mire Hub Top'), ('Mire Hub Switch Blue Barrier S', 'Mire Hub'), ('Mire Map Spike Side Drop Down', 'Mire Lone Shooter'), ('Mire Map Spike Side Blue Barrier', 'Mire Crystal Dead End'), ('Mire Map Spot Blue Barrier', 'Mire Crystal Dead End'), ('Mire Crystal Dead End Left Barrier', 'Mire Map Spot'), ('Mire Crystal Dead End Right Barrier', 'Mire Map Spike Side'), ('Mire Hidden Shooters Block Path S', 'Mire Hidden Shooters'), ('Mire Hidden Shooters Block Path N', 'Mire Hidden Shooters Blocked'), ('Mire Conveyor to Crystal', 'Mire Conveyor - Crystal'), ('Mire Conveyor Crystal Exit', 'Mire Conveyor Crystal'), ('Mire Left Bridge Hook Path', 'Mire Right Bridge'), ('Mire Tall Dark and Roomy to Ranged Crystal', 'Mire Tall Dark and Roomy - Ranged Crystal'), ('Mire Tall Dark and Roomy Ranged Crystal Exit', 'Mire Tall Dark and Roomy'), ('Mire Crystal Right Orange Barrier', 'Mire Crystal Mid'), ('Mire Crystal Mid Orange Barrier', 'Mire Crystal Right'), ('Mire Crystal Mid Blue Barrier', 'Mire Crystal Left'), ('Mire Crystal Left Blue Barrier', 'Mire Crystal Mid'), ('Mire Firesnake Skip Orange Barrier', 'Mire Antechamber'), ('Mire Antechamber Orange Barrier', 'Mire Firesnake Skip'), ('Mire Compass Blue Barrier', 'Mire Compass Chest'), ('Mire Compass Chest Exit', 'Mire Compass Room'), ('Mire South Fish Blue Barrier', 'Mire Fishbone'), ('Mire Fishbone Blue Barrier', 'Mire South Fish'), ('Mire Fishbone Blue Barrier Bypass', 'Mire South Fish'), ('TR Main Lobby Gap', 'TR Lobby Ledge'), ('TR Lobby Ledge Gap', 'TR Main Lobby'), ('TR Pipe Ledge Drop Down', 'TR Pipe Pit'), ('TR Big Chest Gap', 'TR Big Chest Entrance'), ('TR Big Chest Entrance Gap', 'TR Big Chest'), ('TR Chain Chomps Top to Bottom Barrier - Orange', 'TR Chain Chomps Bottom'), ('TR Chain Chomps Top to Crystal', 'TR Chain Chomps Top - Crystal'), ('TR Chain Chomps Top Crystal Exit', 'TR Chain Chomps Top'), ('TR Chain Chomps Bottom to Top Barrier - Orange', 'TR Chain Chomps Top'), ('TR Chain Chomps Bottom to Ranged Crystal', 'TR Chain Chomps Bottom - Ranged Crystal'), ('TR Chain Chomps Bottom Ranged Crystal Exit', 'TR Chain Chomps Bottom'), ('TR Pokey 2 Top to Bottom Barrier - Blue', 'TR Pokey 2 Bottom'), ('TR Pokey 2 Top to Crystal', 'TR Pokey 2 Top - Crystal'), ('TR Pokey 2 Top Crystal Exit', 'TR Pokey 2 Top'), ('TR Pokey 2 Bottom to Top Barrier - Blue', 'TR Pokey 2 Top'), ('TR Pokey 2 Bottom to Ranged Crystal', 'TR Pokey 2 Bottom - Ranged Crystal'), ('TR Pokey 2 Bottom Ranged Crystal Exit', 'TR Pokey 2 Bottom'), ('TR Crystaroller Bottom to Middle Barrier - Orange', 'TR Crystaroller Middle'), ('TR Crystaroller Bottom to Ranged Crystal', 'TR Crystaroller Bottom - Ranged Crystal'), ('TR Crystaroller Middle to Bottom Barrier - Orange', 'TR Crystaroller Bottom'), ('TR Crystaroller Middle to Bottom Bypass', 'TR Crystaroller Bottom'), ('TR Crystaroller Middle to Chest Barrier - Blue', 'TR Crystaroller Chest'), ('TR Crystaroller Middle to Top Barrier - Orange', 'TR Crystaroller Top'), ('TR Crystaroller Middle to Ranged Crystal', 'TR Crystaroller Middle - Ranged Crystal'), ('TR Crystaroller Top to Middle Barrier - Orange', 'TR Crystaroller Middle'), ('TR Crystaroller Top to Crystal', 'TR Crystaroller Top - Crystal'), ('TR Crystaroller Top Crystal Exit', 'TR Crystaroller Top'), ('TR Crystaroller Chest to Middle Barrier - Blue', 'TR Crystaroller Middle'), ('TR Crystaroller Middle Ranged Crystal Exit', 'TR Crystaroller Middle'), ('TR Crystaroller Bottom Ranged Crystal Exit', 'TR Crystaroller Bottom'), ('TR Crystal Maze Start to Interior Barrier - Blue', 'TR Crystal Maze Interior'), ('TR Crystal Maze Start to Crystal', 'TR Crystal Maze Start - Crystal'), ('TR Crystal Maze Start Crystal Exit', 'TR Crystal Maze Start'), ('TR Crystal Maze Interior to End Barrier - Blue', 'TR Crystal Maze End'), ('TR Crystal Maze Interior to Start Barrier - Blue', 'TR Crystal Maze Start'), ('TR Crystal Maze Interior to End Bypass', 'TR Crystal Maze End'), ('TR Crystal Maze Interior to Start Bypass', 'TR Crystal Maze Start'), ('TR Crystal Maze End to Interior Barrier - Blue', 'TR Crystal Maze Interior'), ('TR Crystal Maze End to Ranged Crystal', 'TR Crystal Maze End - Ranged Crystal'), ('TR Crystal Maze End Ranged Crystal Exit', 'TR Crystal Maze End'), ('GT Blocked Stairs Block Path', 'GT Big Chest'), ('GT Speed Torch South Path', 'GT Speed Torch'), ('GT Speed Torch North Path', 'GT Speed Torch Upper'), ('GT Hookshot East-North Path', 'GT Hookshot North Platform'), ('GT Hookshot East-South Path', 'GT Hookshot South Platform'), ('GT Hookshot North-East Path', 'GT Hookshot East Platform'), ('GT Hookshot North-South Path', 'GT Hookshot South Platform'), ('GT Hookshot South-East Path', 'GT Hookshot East Platform'), ('GT Hookshot South-North Path', 'GT Hookshot North Platform'), ('GT Hookshot Platform Blue Barrier', 'GT Hookshot South Entry'), ('GT Hookshot Platform Barrier Bypass', 'GT Hookshot South Entry'), ('GT Hookshot Entry Blue Barrier', 'GT Hookshot South Platform'), ('GT Hookshot South Entry to Ranged Crystal', 'GT Hookshot South Entry - Ranged Crystal'), ('GT HookShot South Entry Ranged Crystal Exit', 'GT Hookshot South Entry'), ('GT Double Switch Entry to Pot Corners Barrier - Orange', 'GT Double Switch Pot Corners'), ('GT Double Switch Entry to Left Barrier - Orange', 'GT Double Switch Left'), ('GT Double Switch Entry to Ranged Switches', 'GT Double Switch Entry - Ranged Switches'), ('GT Double Switch Entry Ranged Switches Exit', 'GT Double Switch Entry'), ('GT Double Switch Left to Crystal', 'GT Double Switch Left - Crystal'), ('GT Double Switch Left Crystal Exit', 'GT Double Switch Left'), ('GT Double Switch Left to Entry Barrier - Orange', 'GT Double Switch Entry'), ('GT Double Switch Left to Entry Bypass', 'GT Double Switch Entry'), ('GT Double Switch Left to Pot Corners Bypass', 'GT Double Switch Pot Corners'), ('GT Double Switch Left to Exit Bypass', 'GT Double Switch Exit'), ('GT Double Switch Pot Corners to Entry Barrier - Orange', 'GT Double Switch Entry'), ('GT Double Switch Pot Corners to Exit Barrier - Blue', 'GT Double Switch Exit'), ('GT Double Switch Pot Corners to Ranged Switches', 'GT Double Switch Pot Corners - Ranged Switches'), ('GT Double Switch Pot Corners Ranged Switches Exit', 'GT Double Switch Pot Corners'), ('GT Double Switch Exit to Blue Barrier', 'GT Double Switch Pot Corners'), ('GT Spike Crystal Left to Right Barrier - Orange', 'GT Spike Crystal Right'), ('GT Spike Crystal Right to Left Barrier - Orange', 'GT Spike Crystal Left'), ('GT Spike Crystal Left to Right Bypass', 'GT Spike Crystal Right'), ('GT Warp Maze - Pit Section Warp Spot', 'GT Warp Maze - Pit Exit Warp Spot'), ('GT Warp Maze Exit Section Warp Spot', 'GT Warp Maze - Pit Exit Warp Spot'), ('GT Firesnake Room Hook Path', 'GT Firesnake Room Ledge'), ('GT Crystal Conveyor to Corner Barrier - Blue', 'GT Crystal Conveyor Corner'), ('GT Crystal Conveyor to Ranged Crystal', 'GT Crystal Conveyor - Ranged Crystal'), ('GT Crystal Conveyor Corner to Left Bypass', 'GT Crystal Conveyor Left'), ('GT Crystal Conveyor Corner to Barrier - Blue', 'GT Crystal Conveyor Left'), ('GT Crystal Conveyor Corner to Barrier - Orange', 'GT Crystal Conveyor'), ('GT Crystal Conveyor Corner to Ranged Crystal', 'GT Crystal Conveyor Corner - Ranged Crystal'), ('GT Crystal Conveyor Left to Corner Barrier - Orange', 'GT Crystal Conveyor Corner'), ('GT Crystal Conveyor Ranged Crystal Exit', 'GT Crystal Conveyor'), ('GT Crystal Conveyor Corner Ranged Crystal Exit', 'GT Crystal Conveyor Corner'), ('GT Left Moldorm Ledge Drop Down', 'GT Moldorm'), ('GT Right Moldorm Ledge Drop Down', 'GT Moldorm'), ('GT Crystal Circles Barrier - Orange', 'GT Crystal Inner Circle'), ('GT Crystal Circles to Ranged Crystal', 'GT Crystal Circles - Ranged Crystal'), ('GT Crystal Inner Circle Barrier - Orange', 'GT Crystal Circles'), ('GT Crystal Circles Ranged Crystal Exit', 'GT Crystal Circles'), ('GT Moldorm Gap', 'GT Validation'), ('GT Validation Block Path', 'GT Validation Door') ] vanilla_logical_connections = [ ('Ice Cross Left Push Block', 'Ice Compass Room'), ('Ice Cross Right Push Block Bottom', 'Ice Compass Room'), ('Ice Cross Bottom Push Block Right', 'Ice Pengator Switch'), ('Ice Cross Top Push Block Right', 'Ice Pengator Switch'), ] spiral_staircases = [ ('Hyrule Castle Back Hall Down Stairs', 'Hyrule Dungeon Map Room Up Stairs'), ('Hyrule Dungeon Armory Down Stairs', 'Hyrule Dungeon Staircase Up Stairs'), ('Hyrule Dungeon Staircase Down Stairs', 'Hyrule Dungeon Cellblock Up Stairs'), ('Sewers Behind Tapestry Down Stairs', 'Sewers Rope Room Up Stairs'), ('Sewers Secret Room Up Stairs', 'Sewers Pull Switch Down Stairs'), ('Eastern Darkness Up Stairs', 'Eastern Attic Start Down Stairs'), ('Desert Tiles 1 Up Stairs', 'Desert Bridge Down Stairs'), ('Hera Lobby Down Stairs', 'Hera Basement Cage Up Stairs'), ('Hera Lobby Key Stairs', 'Hera Tile Room Up Stairs'), ('Hera Lobby Up Stairs', 'Hera Beetles Down Stairs'), ('Hera Startile Wide Up Stairs', 'Hera 4F Down Stairs'), ('Hera 4F Up Stairs', 'Hera 5F Down Stairs'), ('Hera 5F Up Stairs', 'Hera Boss Down Stairs'), ('Tower Room 03 Up Stairs', 'Tower Lone Statue Down Stairs'), ('Tower Dark Chargers Up Stairs', 'Tower Dual Statues Down Stairs'), ('Tower Dark Archers Up Stairs', 'Tower Red Spears Down Stairs'), ('Tower Pacifist Run Up Stairs', 'Tower Push Statue Down Stairs'), ('PoD Left Cage Down Stairs', 'PoD Shooter Room Up Stairs'), ('PoD Middle Cage Down Stairs', 'PoD Warp Room Up Stairs'), ('PoD Basement Ledge Up Stairs', 'PoD Big Key Landing Down Stairs'), ('PoD Compass Room W Down Stairs', 'PoD Dark Basement W Up Stairs'), ('PoD Compass Room E Down Stairs', 'PoD Dark Basement E Up Stairs'), ('Swamp Entrance Down Stairs', 'Swamp Pot Row Up Stairs'), ('Swamp West Block Path Up Stairs', 'Swamp Attic Down Stairs'), ('Swamp Push Statue Down Stairs', 'Swamp Flooded Room Up Stairs'), ('Swamp Left Elbow Down Stairs', 'Swamp Drain Left Up Stairs'), ('Swamp Right Elbow Down Stairs', 'Swamp Drain Right Up Stairs'), ('Swamp Behind Waterfall Up Stairs', 'Swamp C Down Stairs'), ('Thieves Spike Switch Up Stairs', 'Thieves Attic Down Stairs'), ('Thieves Conveyor Maze Down Stairs', 'Thieves Basement Block Up Stairs'), ('Ice Jelly Key Down Stairs', 'Ice Floor Switch Up Stairs'), ('Ice Narrow Corridor Down Stairs', 'Ice Pengator Trap Up Stairs'), ('Ice Spike Room Up Stairs', 'Ice Hammer Block Down Stairs'), ('Ice Spike Room Down Stairs', 'Ice Spikeball Up Stairs'), ('Ice Lonely Freezor Down Stairs', 'Iced T Up Stairs'), ('Ice Backwards Room Down Stairs', 'Ice Anti-Fairy Up Stairs'), ('Mire Post-Gap Down Stairs', 'Mire 2 Up Stairs'), ('Mire Left Bridge Down Stairs', 'Mire Dark Shooters Up Stairs'), ('Mire Conveyor Barrier Up Stairs', 'Mire Torches Top Down Stairs'), ('Mire Falling Foes Up Stairs', 'Mire Firesnake Skip Down Stairs'), ('TR Chain Chomps Down Stairs', 'TR Pipe Pit Up Stairs'), ('TR Crystaroller Down Stairs', 'TR Dark Ride Up Stairs'), ('GT Lobby Left Down Stairs', 'GT Torch Up Stairs'), ('GT Lobby Up Stairs', 'GT Crystal Paths Down Stairs'), ('GT Lobby Right Down Stairs', 'GT Hope Room Up Stairs'), ('GT Blocked Stairs Down Stairs', 'GT Four Torches Up Stairs'), ('GT Cannonball Bridge Up Stairs', 'GT Gauntlet 1 Down Stairs'), ('GT Quad Pot Up Stairs', 'GT Wizzrobes 1 Down Stairs'), ('GT Moldorm Pit Up Stairs', 'GT Right Moldorm Ledge Down Stairs'), ('GT Frozen Over Up Stairs', 'GT Brightly Lit Hall Down Stairs') ] straight_staircases = [ ('Hyrule Castle Lobby North Stairs', 'Hyrule Castle Throne Room South Stairs'), ('Sewers Rope Room North Stairs', 'Sewers Dark Cross South Stairs'), ('Tower Catwalk North Stairs', 'Tower Antechamber South Stairs'), ('PoD Conveyor North Stairs', 'PoD Map Balcony South Stairs'), ('TR Crystal Maze North Stairs', 'TR Final Abyss South Stairs') ] open_edges = [ ('Hyrule Dungeon North Abyss South Edge', 'Hyrule Dungeon South Abyss North Edge'), ('Hyrule Dungeon North Abyss Catwalk Edge', 'Hyrule Dungeon South Abyss Catwalk North Edge'), ('Hyrule Dungeon South Abyss West Edge', 'Hyrule Dungeon Guardroom Abyss Edge'), ('Hyrule Dungeon South Abyss Catwalk West Edge', 'Hyrule Dungeon Guardroom Catwalk Edge'), ('Desert Main Lobby NW Edge', 'Desert North Hall SW Edge'), ('Desert Main Lobby N Edge', 'Desert Dead End Edge'), ('Desert Main Lobby NE Edge', 'Desert North Hall SE Edge'), ('Desert Main Lobby E Edge', 'Desert East Wing W Edge'), ('Desert East Wing N Edge', 'Desert Arrow Pot Corner S Edge'), ('Desert Arrow Pot Corner W Edge', 'Desert North Hall E Edge'), ('Desert West Wing N Edge', 'Desert Sandworm Corner S Edge'), ('Desert Sandworm Corner E Edge', 'Desert North Hall W Edge'), ('Thieves Lobby N Edge', 'Thieves Ambush S Edge'), ('Thieves Lobby NE Edge', 'Thieves Ambush SE Edge'), ('Thieves Ambush ES Edge', 'Thieves BK Corner WS Edge'), ('Thieves Ambush EN Edge', 'Thieves BK Corner WN Edge'), ('Thieves BK Corner S Edge', 'Thieves Compass Room N Edge'), ('Thieves BK Corner SW Edge', 'Thieves Compass Room NW Edge'), ('Thieves Compass Room WS Edge', 'Thieves Big Chest Nook ES Edge'), ('Thieves Cricket Hall Left Edge', 'Thieves Cricket Hall Right Edge') ] falldown_pits = [ ('Eastern Courtyard Potholes', 'Eastern Fairies'), ('Hera Beetles Holes Front', 'Hera Front'), ('Hera Beetles Holes Landing', 'Hera Up Stairs Landing'), ('Hera Startile Corner Holes Front', 'Hera Front'), ('Hera Startile Corner Holes Landing', 'Hera Down Stairs Landing'), ('Hera Startile Wide Holes', 'Hera Back'), ('Hera 4F Holes', 'Hera Back'), # failed bomb jump ('Hera Big Chest Landing Holes', 'Hera Startile Wide'), # the other holes near big chest ('Hera 5F Star Hole', 'Hera Big Chest Landing'), ('Hera 5F Pothole Chain', 'Hera Fairies'), ('Hera 5F Normal Holes', 'Hera 4F'), ('Hera Boss Outer Hole', 'Hera 5F'), ('Hera Boss Inner Hole', 'Hera 4F'), ('PoD Pit Room Freefall', 'PoD Stalfos Basement'), ('PoD Pit Room Bomb Hole', 'PoD Basement Ledge'), ('PoD Big Key Landing Hole', 'PoD Stalfos Basement'), ('Swamp Attic Right Pit', 'Swamp Barrier Ledge'), ('Swamp Attic Left Pit', 'Swamp West Ledge'), ('Skull Final Drop Hole', 'Skull Boss'), ('Ice Bomb Drop Hole', 'Ice Stalfos Hint'), ('Ice Falling Square Hole', 'Ice Tall Hint'), ('Ice Freezors Hole', 'Ice Big Chest View'), ('Ice Freezors Ledge Hole', 'Ice Big Chest View'), ('Ice Freezors Bomb Hole', 'Ice Big Chest Landing'), ('Ice Crystal Block Hole', 'Ice Switch Room'), ('Ice Crystal Right Blue Hole', 'Ice Switch Room'), ('Ice Backwards Room Hole', 'Ice Fairy'), ('Ice Antechamber Hole', 'Ice Boss'), ('Mire Attic Hint Hole', 'Mire BK Chest Ledge'), ('Mire Torches Top Holes', 'Mire Conveyor Barrier'), ('Mire Torches Bottom Holes', 'Mire Warping Pool'), ('GT Bob\'s Room Hole', 'GT Ice Armos'), ('GT Falling Torches Hole', 'GT Staredown'), ('GT Moldorm Hole', 'GT Moldorm Pit') ] dungeon_warps = [ ('Eastern Fairies\' Warp', 'Eastern Courtyard'), ('Hera Fairies\' Warp', 'Hera 5F'), ('PoD Warp Hint Warp', 'PoD Warp Room'), ('PoD Warp Room Warp', 'PoD Warp Hint'), ('PoD Stalfos Basement Warp', 'PoD Warp Room'), ('PoD Callback Warp', 'PoD Dark Alley'), ('Ice Fairy Warp', 'Ice Anti-Fairy'), ('Mire Lone Warp Warp', 'Mire BK Door Room'), ('Mire Warping Pool Warp', 'Mire Square Rail'), ('GT Compass Room Warp', 'GT Conveyor Star Pits'), ('GT Spike Crystals Warp', 'GT Firesnake Room'), ('GT Warp Maze - Left Section Warp', 'GT Warp Maze - Rando Rail'), ('GT Warp Maze - Mid Section Left Warp', 'GT Warp Maze - Main Rails'), ('GT Warp Maze - Mid Section Right Warp', 'GT Warp Maze - Main Rails'), ('GT Warp Maze - Right Section Warp', 'GT Warp Maze - Main Rails'), ('GT Warp Maze - Pit Exit Warp', 'GT Warp Maze - Pot Rail'), ('GT Warp Maze - Rail Choice Left Warp', 'GT Warp Maze - Left Section'), ('GT Warp Maze - Rail Choice Right Warp', 'GT Warp Maze - Mid Section'), ('GT Warp Maze - Rando Rail Warp', 'GT Warp Maze - Mid Section'), ('GT Warp Maze - Main Rails Best Warp', 'GT Warp Maze - Pit Section'), ('GT Warp Maze - Main Rails Mid Left Warp', 'GT Warp Maze - Mid Section'), ('GT Warp Maze - Main Rails Mid Right Warp', 'GT Warp Maze - Mid Section'), ('GT Warp Maze - Main Rails Right Top Warp', 'GT Warp Maze - Right Section'), ('GT Warp Maze - Main Rails Right Mid Warp', 'GT Warp Maze - Right Section'), ('GT Warp Maze - Pot Rail Warp', 'GT Warp Maze Exit Section'), ('GT Hidden Star Warp', 'GT Invisible Bridges') ] ladders = [ ('PoD Bow Statue Down Ladder', 'PoD Dark Pegs Up Ladder'), ('Ice Big Key Down Ladder', 'Ice Tongue Pull Up Ladder'), ('Ice Firebar Down Ladder', 'Ice Freezors Up Ladder'), ('GT Staredown Up Ladder', 'GT Falling Torches Down Ladder') ] interior_doors = [ ('Hyrule Dungeon Armory Interior Key Door S', 'Hyrule Dungeon Armory Interior Key Door N'), ('Hyrule Dungeon Armory ES', 'Hyrule Dungeon Armory Boomerang WS'), ('Hyrule Dungeon Map Room Key Door S', 'Hyrule Dungeon North Abyss Key Door N'), ('Sewers Rat Path WS', 'Sewers Secret Room ES'), ('Sewers Rat Path WN', 'Sewers Secret Room EN'), ('Sewers Yet More Rats S', 'Sewers Pull Switch N'), ('Eastern Lobby N', 'Eastern Lobby Bridge S'), ('Eastern Lobby NW', 'Eastern Lobby Left Ledge SW'), ('Eastern Lobby NE', 'Eastern Lobby Right Ledge SE'), ('Eastern East Wing EN', 'Eastern Pot Switch WN'), ('Eastern East Wing ES', 'Eastern Map Balcony WS'), ('Eastern Pot Switch SE', 'Eastern Map Room NE'), ('Eastern West Wing WS', 'Eastern Stalfos Spawn ES'), ('Eastern Stalfos Spawn NW', 'Eastern Compass Room SW'), ('Eastern Compass Room EN', 'Eastern Hint Tile WN'), ('Eastern Dark Square EN', 'Eastern Dark Pots WN'), ('Eastern Darkness NE', 'Eastern Rupees SE'), ('Eastern False Switches WS', 'Eastern Cannonball Hell ES'), ('Eastern Single Eyegore NE', 'Eastern Duo Eyegores SE'), ('Desert East Lobby WS', 'Desert East Wing ES'), ('Desert East Wing Key Door EN', 'Desert Compass Key Door WN'), ('Desert North Hall NW', 'Desert Map SW'), ('Desert North Hall NE', 'Desert Map SE'), ('Desert Arrow Pot Corner NW', 'Desert Trap Room SW'), ('Desert Sandworm Corner NE', 'Desert Bonk Torch SE'), ('Desert Sandworm Corner WS', 'Desert Circle of Pots ES'), ('Desert Circle of Pots NW', 'Desert Big Chest SW'), ('Desert West Wing WS', 'Desert West Lobby ES'), ('Desert Fairy Fountain SW', 'Desert West Lobby NW'), ('Desert Back Lobby NW', 'Desert Tiles 1 SW'), ('Desert Bridge SW', 'Desert Four Statues NW'), ('Desert Four Statues ES', 'Desert Beamos Hall WS'), ('Desert Tiles 2 NE', 'Desert Wall Slide SE'), ('Hera Tile Room EN', 'Hera Tridorm WN'), ('Hera Tridorm SE', 'Hera Torches NE'), ('Hera Beetles WS', 'Hera Startile Corner ES'), ('Hera Startile Corner NW', 'Hera Startile Wide SW'), ('Tower Lobby NW', 'Tower Gold Knights SW'), ('Tower Gold Knights EN', 'Tower Room 03 WN'), ('Tower Lone Statue WN', 'Tower Dark Maze EN'), ('Tower Dark Maze ES', 'Tower Dark Chargers WS'), ('Tower Dual Statues WS', 'Tower Dark Pits ES'), ('Tower Dark Pits EN', 'Tower Dark Archers WN'), ('Tower Red Spears WN', 'Tower Red Guards EN'), ('Tower Red Guards SW', 'Tower Circle of Pots NW'), ('Tower Circle of Pots ES', 'Tower Pacifist Run WS'), ('Tower Push Statue WS', 'Tower Catwalk ES'), ('Tower Antechamber NW', 'Tower Altar SW'), ('PoD Lobby N', 'PoD Middle Cage S'), ('PoD Lobby NW', 'PoD Left Cage SW'), ('PoD Lobby NE', 'PoD Middle Cage SE'), ('PoD Warp Hint SE', 'PoD Jelly Hall NE'), ('PoD Jelly Hall NW', 'PoD Mimics 1 SW'), ('PoD Falling Bridge EN', 'PoD Compass Room WN'), ('PoD Compass Room SE', 'PoD Harmless Hellway NE'), ('PoD Mimics 2 NW', 'PoD Bow Statue SW'), ('PoD Dark Pegs WN', 'PoD Lonely Turtle EN'), ('PoD Lonely Turtle SW', 'PoD Turtle Party NW'), ('PoD Turtle Party ES', 'PoD Callback WS'), ('Swamp Trench 1 Nexus N', 'Swamp Trench 1 Alcove S'), ('Swamp Trench 1 Key Ledge NW', 'Swamp Hammer Switch SW'), ('Swamp Donut Top SE', 'Swamp Donut Bottom NE'), ('Swamp Donut Bottom NW', 'Swamp Compass Donut SW'), ('Swamp Crystal Switch SE', 'Swamp Shortcut NE'), ('Swamp Trench 2 Blocks N', 'Swamp Trench 2 Alcove S'), ('Swamp Push Statue NW', 'Swamp Shooters SW'), ('Swamp Push Statue NE', 'Swamp Right Elbow SE'), ('Swamp Shooters EN', 'Swamp Left Elbow WN'), ('Swamp Drain WN', 'Swamp Basement Shallows EN'), ('Swamp Flooded Room WS', 'Swamp Basement Shallows ES'), ('Swamp Waterfall Room NW', 'Swamp Refill SW'), ('Swamp Waterfall Room NE', 'Swamp Behind Waterfall SE'), ('Swamp C SE', 'Swamp Waterway NE'), ('Swamp Waterway N', 'Swamp I S'), ('Swamp Waterway NW', 'Swamp T SW'), ('Skull 1 Lobby ES', 'Skull Map Room WS'), ('Skull Pot Circle WN', 'Skull Pull Switch EN'), ('Skull Pull Switch S', 'Skull Big Chest N'), ('Skull Left Drop ES', 'Skull Compass Room WS'), ('Skull 2 East Lobby NW', 'Skull Big Key SW'), ('Skull Big Key EN', 'Skull Lone Pot WN'), ('Skull Small Hall WS', 'Skull 2 West Lobby ES'), ('Skull 2 West Lobby NW', 'Skull X Room SW'), ('Skull 3 Lobby EN', 'Skull East Bridge WN'), ('Skull East Bridge WS', 'Skull West Bridge Nook ES'), ('Skull Star Pits ES', 'Skull Torch Room WS'), ('Skull Torch Room WN', 'Skull Vines EN'), ('Skull Spike Corner ES', 'Skull Final Drop WS'), ('Thieves Hallway WS', 'Thieves Pot Alcove Mid ES'), ('Thieves Conveyor Maze SW', 'Thieves Pot Alcove Top NW'), ('Thieves Conveyor Maze EN', 'Thieves Hallway WN'), ('Thieves Spike Track NE', 'Thieves Triple Bypass SE'), ('Thieves Spike Track WS', 'Thieves Hellway Crystal ES'), ('Thieves Hellway Crystal EN', 'Thieves Triple Bypass WN'), ('Thieves Attic ES', 'Thieves Cricket Hall Left WS'), ('Thieves Cricket Hall Right ES', 'Thieves Attic Window WS'), ('Thieves Blocked Entry SW', 'Thieves Lonely Zazak NW'), ('Thieves Lonely Zazak ES', 'Thieves Blind\'s Cell WS'), ('Thieves Conveyor Bridge WS', 'Thieves Big Chest Room ES'), ('Thieves Conveyor Block WN', 'Thieves Trap EN'), ('Ice Lobby WS', 'Ice Jelly Key ES'), ('Ice Floor Switch ES', 'Ice Cross Left WS'), ('Ice Cross Top NE', 'Ice Bomb Drop SE'), ('Ice Pengator Switch ES', 'Ice Dead End WS'), ('Ice Stalfos Hint SE', 'Ice Conveyor NE'), ('Ice Bomb Jump EN', 'Ice Narrow Corridor WN'), ('Ice Spike Cross WS', 'Ice Firebar ES'), ('Ice Spike Cross NE', 'Ice Falling Square SE'), ('Ice Hammer Block ES', 'Ice Tongue Pull WS'), ('Ice Freezors Ledge ES', 'Ice Tall Hint WS'), ('Ice Hookshot Balcony SW', 'Ice Spikeball NW'), ('Ice Crystal Right NE', 'Ice Backwards Room SE'), ('Ice Crystal Left WS', 'Ice Big Chest View ES'), ('Ice Anti-Fairy SE', 'Ice Switch Room NE'), ('Mire Lone Shooter ES', 'Mire Falling Bridge WS'), # technically one-way ('Mire Falling Bridge W', 'Mire Failure Bridge E'), # technically one-way ('Mire Falling Bridge WN', 'Mire Map Spike Side EN'), # technically one-way ('Mire Hidden Shooters WS', 'Mire Cross ES'), # technically one-way ('Mire Hidden Shooters NE', 'Mire Minibridge SE'), ('Mire Spikes NW', 'Mire Ledgehop SW'), ('Mire Spike Barrier ES', 'Mire Square Rail WS'), ('Mire Square Rail NW', 'Mire Lone Warp SW'), ('Mire Wizzrobe Bypass WN', 'Mire Compass Room EN'), # technically one-way ('Mire Conveyor Crystal WS', 'Mire Tile Room ES'), ('Mire Tile Room NW', 'Mire Compass Room SW'), ('Mire Neglected Room SE', 'Mire Chest View NE'), ('Mire BK Chest Ledge WS', 'Mire Warping Pool ES'), # technically one-way ('Mire Torches Top SW', 'Mire Torches Bottom NW'), ('Mire Torches Bottom WS', 'Mire Attic Hint ES'), ('Mire Dark Shooters SE', 'Mire Key Rupees NE'), ('Mire Dark Shooters SW', 'Mire Block X NW'), ('Mire Tall Dark and Roomy WS', 'Mire Crystal Right ES'), ('Mire Tall Dark and Roomy WN', 'Mire Shooter Rupees EN'), ('Mire Crystal Mid NW', 'Mire Crystal Top SW'), ('TR Tile Room NE', 'TR Refill SE'), ('TR Pokey 1 NW', 'TR Chain Chomps SW'), ('TR Twin Pokeys EN', 'TR Dodgers WN'), ('TR Twin Pokeys SW', 'TR Hallway NW'), ('TR Hallway ES', 'TR Big View WS'), ('TR Big Chest NE', 'TR Dodgers SE'), ('TR Dash Room ES', 'TR Tongue Pull WS'), ('TR Dash Room NW', 'TR Crystaroller SW'), ('TR Tongue Pull NE', 'TR Rupees SE'), ('GT Torch EN', 'GT Hope Room WN'), ('GT Torch SW', 'GT Big Chest NW'), ('GT Tile Room EN', 'GT Speed Torch WN'), ('GT Speed Torch WS', 'GT Pots n Blocks ES'), ('GT Crystal Conveyor WN', 'GT Compass Room EN'), ('GT Conveyor Cross WN', 'GT Hookshot EN'), ('GT Hookshot ES', 'GT Map Room WS'), ('GT Double Switch EN', 'GT Spike Crystals WN'), ('GT Firesnake Room SW', 'GT Warp Maze (Rails) NW'), ('GT Ice Armos NE', 'GT Big Key Room SE'), ('GT Ice Armos WS', 'GT Four Torches ES'), ('GT Four Torches NW', 'GT Fairy Abyss SW'), ('GT Crystal Paths SW', 'GT Mimics 1 NW'), ('GT Mimics 1 ES', 'GT Mimics 2 WS'), ('GT Mimics 2 NE', 'GT Dash Hall SE'), ('GT Cannonball Bridge SE', 'GT Refill NE'), ('GT Gauntlet 1 WN', 'GT Gauntlet 2 EN'), ('GT Gauntlet 2 SW', 'GT Gauntlet 3 NW'), ('GT Gauntlet 4 SW', 'GT Gauntlet 5 NW'), ('GT Beam Dash WS', 'GT Lanmolas 2 ES'), ('GT Lanmolas 2 NW', 'GT Quad Pot SW'), ('GT Wizzrobes 1 SW', 'GT Dashing Bridge NW'), ('GT Dashing Bridge NE', 'GT Wizzrobes 2 SE'), ('GT Torch Cross ES', 'GT Staredown WS'), ('GT Falling Torches NE', 'GT Mini Helmasaur Room SE'), ('GT Mini Helmasaur Room WN', 'GT Bomb Conveyor EN'), ('GT Bomb Conveyor SW', 'GT Crystal Circles NW') ] key_doors = [ ('Sewers Key Rat Key Door N', 'Sewers Secret Room Key Door S'), ('Sewers Dark Cross Key Door N', 'Sewers Water S'), ('Eastern Dark Square Key Door WN', 'Eastern Cannonball Ledge Key Door EN'), ('Eastern Darkness Up Stairs', 'Eastern Attic Start Down Stairs'), ('Eastern Big Key NE', 'Eastern Hint Tile Blocked Path SE'), ('Eastern Darkness S', 'Eastern Courtyard N'), ('Desert East Wing Key Door EN', 'Desert Compass Key Door WN'), ('Desert Tiles 1 Up Stairs', 'Desert Bridge Down Stairs'), ('Desert Beamos Hall NE', 'Desert Tiles 2 SE'), ('Desert Tiles 2 NE', 'Desert Wall Slide SE'), ('Desert Wall Slide NW', 'Desert Boss SW'), ('Hera Lobby Key Stairs', 'Hera Tile Room Up Stairs'), ('Hera Startile Corner NW', 'Hera Startile Wide SW'), ('PoD Middle Cage N', 'PoD Pit Room S'), ('PoD Arena Main NW', 'PoD Falling Bridge SW'), ('PoD Falling Bridge WN', 'PoD Dark Maze EN'), ] default_small_key_doors = { 'Hyrule Castle': [ ('Sewers Key Rat Key Door N', 'Sewers Secret Room Key Door S'), ('Sewers Dark Cross Key Door N', 'Sewers Water S'), ('Hyrule Dungeon Map Room Key Door S', 'Hyrule Dungeon North Abyss Key Door N'), ('Hyrule Dungeon Armory Interior Key Door N', 'Hyrule Dungeon Armory Interior Key Door S') ], 'Eastern Palace': [ ('Eastern Dark Square Key Door WN', 'Eastern Cannonball Ledge Key Door EN'), 'Eastern Darkness Up Stairs', ], 'Desert Palace': [ ('Desert East Wing Key Door EN', 'Desert Compass Key Door WN'), 'Desert Tiles 1 Up Stairs', ('Desert Beamos Hall NE', 'Desert Tiles 2 SE'), ('Desert Tiles 2 NE', 'Desert Wall Slide SE'), ], 'Tower of Hera': [ 'Hera Lobby Key Stairs' ], 'Agahnims Tower': [ 'Tower Room 03 Up Stairs', ('Tower Dark Maze ES', 'Tower Dark Chargers WS'), 'Tower Dark Archers Up Stairs', ('Tower Circle of Pots ES', 'Tower Pacifist Run WS'), ], 'Palace of Darkness': [ ('PoD Middle Cage N', 'PoD Pit Room S'), ('PoD Arena Main NW', 'PoD Falling Bridge SW'), ('PoD Falling Bridge WN', 'PoD Dark Maze EN'), 'PoD Basement Ledge Up Stairs', ('PoD Compass Room SE', 'PoD Harmless Hellway NE'), ('PoD Dark Pegs WN', 'PoD Lonely Turtle EN') ], 'Swamp Palace': [ 'Swamp Entrance Down Stairs', ('Swamp Pot Row WS', 'Swamp Trench 1 Approach ES'), ('Swamp Trench 1 Key Ledge NW', 'Swamp Hammer Switch SW'), ('Swamp Hub WN', 'Swamp Crystal Switch EN'), ('Swamp Hub North Ledge N', 'Swamp Push Statue S'), ('Swamp Waterway NW', 'Swamp T SW') ], 'Skull Woods': [ ('Skull 1 Lobby WS', 'Skull Pot Prison ES'), ('Skull Map Room SE', 'Skull Pinball NE'), ('Skull 2 West Lobby NW', 'Skull X Room SW'), ('Skull 3 Lobby NW', 'Skull Star Pits SW'), ('Skull Spike Corner ES', 'Skull Final Drop WS') ], 'Thieves Town': [ ('Thieves Hallway WS', 'Thieves Pot Alcove Mid ES'), 'Thieves Spike Switch Up Stairs', ('Thieves Conveyor Bridge WS', 'Thieves Big Chest Room ES') ], 'Ice Palace': [ 'Ice Jelly Key Down Stairs', ('Ice Conveyor SW', 'Ice Bomb Jump NW'), ('Ice Spike Cross ES', 'Ice Spike Room WS'), ('Ice Tall Hint SE', 'Ice Lonely Freezor NE'), 'Ice Backwards Room Down Stairs', ('Ice Switch Room ES', 'Ice Refill WS') ], 'Misery Mire': [ ('Mire Hub WS', 'Mire Conveyor Crystal ES'), ('Mire Hub Right EN', 'Mire Map Spot WN'), ('Mire Spikes NW', 'Mire Ledgehop SW'), ('Mire Fishbone SE', 'Mire Spike Barrier NE'), ('Mire Conveyor Crystal WS', 'Mire Tile Room ES'), ('Mire Dark Shooters SE', 'Mire Key Rupees NE') ], 'Turtle Rock': [ ('TR Hub NW', 'TR Pokey 1 SW'), ('TR Pokey 1 NW', 'TR Chain Chomps SW'), 'TR Chain Chomps Down Stairs', ('TR Pokey 2 ES', 'TR Lava Island WS'), 'TR Crystaroller Down Stairs', ('TR Dash Bridge WS', 'TR Crystal Maze ES') ], 'Ganons Tower': [ ('GT Torch EN', 'GT Hope Room WN'), ('GT Tile Room EN', 'GT Speed Torch WN'), ('GT Hookshot ES', 'GT Map Room WS'), ('GT Double Switch EN', 'GT Spike Crystals WN'), ('GT Firesnake Room SW', 'GT Warp Maze (Rails) NW'), ('GT Conveyor Star Pits EN', 'GT Falling Bridge WN'), ('GT Mini Helmasaur Room WN', 'GT Bomb Conveyor EN'), ('GT Crystal Circles SW', 'GT Left Moldorm Ledge NW') ] } default_door_connections = [ ('Hyrule Castle Lobby W', 'Hyrule Castle West Lobby E'), ('Hyrule Castle Lobby E', 'Hyrule Castle East Lobby W'), ('Hyrule Castle Lobby WN', 'Hyrule Castle West Lobby EN'), ('Hyrule Castle West Lobby N', 'Hyrule Castle West Hall S'), ('Hyrule Castle East Lobby N', 'Hyrule Castle East Hall S'), ('Hyrule Castle East Lobby NW', 'Hyrule Castle East Hall SW'), ('Hyrule Castle East Hall W', 'Hyrule Castle Back Hall E'), ('Hyrule Castle West Hall E', 'Hyrule Castle Back Hall W'), ('Hyrule Castle Throne Room N', 'Sewers Behind Tapestry S'), ('Hyrule Dungeon Guardroom N', 'Hyrule Dungeon Armory S'), ('Sewers Dark Cross Key Door N', 'Sewers Water S'), ('Sewers Water W', 'Sewers Key Rat E'), ('Sewers Key Rat Key Door N', 'Sewers Secret Room Key Door S'), ('Eastern Lobby Bridge N', 'Eastern Cannonball S'), ('Eastern Cannonball N', 'Eastern Courtyard Ledge S'), ('Eastern Cannonball Ledge WN', 'Eastern Big Key EN'), ('Eastern Cannonball Ledge Key Door EN', 'Eastern Dark Square Key Door WN'), ('Eastern Courtyard Ledge W', 'Eastern West Wing E'), ('Eastern Courtyard Ledge E', 'Eastern East Wing W'), ('Eastern Hint Tile EN', 'Eastern Courtyard WN'), ('Eastern Big Key NE', 'Eastern Hint Tile Blocked Path SE'), ('Eastern Courtyard EN', 'Eastern Map Valley WN'), ('Eastern Courtyard N', 'Eastern Darkness S'), ('Eastern Map Valley SW', 'Eastern Dark Square NW'), ('Eastern Attic Start WS', 'Eastern False Switches ES'), ('Eastern Cannonball Hell WS', 'Eastern Single Eyegore ES'), ('Desert Compass NW', 'Desert Cannonball S'), ('Desert Beamos Hall NE', 'Desert Tiles 2 SE'), ('PoD Middle Cage N', 'PoD Pit Room S'), ('PoD Pit Room NW', 'PoD Arena Main SW'), ('PoD Pit Room NE', 'PoD Arena Bridge SE'), ('PoD Arena Main NW', 'PoD Falling Bridge SW'), ('PoD Arena Crystals E', 'PoD Sexy Statue W'), ('PoD Mimics 1 NW', 'PoD Conveyor SW'), ('PoD Map Balcony WS', 'PoD Arena Ledge ES'), ('PoD Falling Bridge WN', 'PoD Dark Maze EN'), ('PoD Dark Maze E', 'PoD Big Chest Balcony W'), ('PoD Sexy Statue NW', 'PoD Mimics 2 SW'), ('Swamp Pot Row WN', 'Swamp Map Ledge EN'), ('Swamp Pot Row WS', 'Swamp Trench 1 Approach ES'), ('Swamp Trench 1 Departure WS', 'Swamp Hub ES'), ('Swamp Hammer Switch WN', 'Swamp Hub Dead Ledge EN'), ('Swamp Hub S', 'Swamp Donut Top N'), ('Swamp Hub WS', 'Swamp Trench 2 Pots ES'), ('Swamp Hub WN', 'Swamp Crystal Switch EN'), ('Swamp Hub North Ledge N', 'Swamp Push Statue S'), ('Swamp Trench 2 Departure WS', 'Swamp West Shallows ES'), ('Swamp Big Key Ledge WN', 'Swamp Barrier EN'), ('Swamp Basement Shallows NW', 'Swamp Waterfall Room SW'), ('Skull 1 Lobby WS', 'Skull Pot Prison ES'), ('Skull Map Room SE', 'Skull Pinball NE'), ('Skull Pinball WS', 'Skull Compass Room ES'), ('Skull Compass Room NE', 'Skull Pot Prison SE'), ('Skull 2 East Lobby WS', 'Skull Small Hall ES'), ('Skull 3 Lobby NW', 'Skull Star Pits SW'), ('Skull Vines NW', 'Skull Spike Corner SW'), ('Thieves Lobby E', 'Thieves Compass Room W'), ('Thieves Ambush E', 'Thieves Rail Ledge W'), ('Thieves Rail Ledge NW', 'Thieves Pot Alcove Bottom SW'), ('Thieves BK Corner NE', 'Thieves Hallway SE'), ('Thieves Pot Alcove Mid WS', 'Thieves Spike Track ES'), ('Thieves Hellway NW', 'Thieves Spike Switch SW'), ('Thieves Triple Bypass EN', 'Thieves Conveyor Maze WN'), ('Thieves Basement Block WN', 'Thieves Conveyor Bridge EN'), ('Thieves Lonely Zazak WS', 'Thieves Conveyor Bridge ES'), ('Ice Cross Bottom SE', 'Ice Compass Room NE'), ('Ice Cross Right ES', 'Ice Pengator Switch WS'), ('Ice Conveyor SW', 'Ice Bomb Jump NW'), ('Ice Pengator Trap NE', 'Ice Spike Cross SE'), ('Ice Spike Cross ES', 'Ice Spike Room WS'), ('Ice Tall Hint SE', 'Ice Lonely Freezor NE'), ('Ice Tall Hint EN', 'Ice Hookshot Ledge WN'), ('Iced T EN', 'Ice Catwalk WN'), ('Ice Catwalk NW', 'Ice Many Pots SW'), ('Ice Many Pots WS', 'Ice Crystal Right ES'), ('Ice Switch Room ES', 'Ice Refill WS'), ('Ice Switch Room SE', 'Ice Antechamber NE'), ('Mire 2 NE', 'Mire Hub SE'), ('Mire Hub ES', 'Mire Lone Shooter WS'), ('Mire Hub E', 'Mire Failure Bridge W'), ('Mire Hub NE', 'Mire Hidden Shooters SE'), ('Mire Hub WN', 'Mire Wizzrobe Bypass EN'), ('Mire Hub WS', 'Mire Conveyor Crystal ES'), ('Mire Hub Right EN', 'Mire Map Spot WN'), ('Mire Hub Top NW', 'Mire Cross SW'), ('Mire Hidden Shooters ES', 'Mire Spikes WS'), ('Mire Minibridge NE', 'Mire Right Bridge SE'), ('Mire BK Door Room EN', 'Mire Ledgehop WN'), ('Mire BK Door Room N', 'Mire Left Bridge S'), ('Mire Spikes SW', 'Mire Crystal Dead End NW'), ('Mire Ledgehop NW', 'Mire Bent Bridge SW'), ('Mire Bent Bridge W', 'Mire Over Bridge E'), ('Mire Over Bridge W', 'Mire Fishbone E'), ('Mire Fishbone SE', 'Mire Spike Barrier NE'), ('Mire Spike Barrier SE', 'Mire Wizzrobe Bypass NE'), ('Mire Conveyor Crystal SE', 'Mire Neglected Room NE'), ('Mire Tile Room SW', 'Mire Conveyor Barrier NW'), ('Mire Block X WS', 'Mire Tall Dark and Roomy ES'), ('Mire Crystal Left WS', 'Mire Falling Foes ES'), ('TR Lobby Ledge NE', 'TR Hub SE'), ('TR Compass Room NW', 'TR Hub SW'), ('TR Hub ES', 'TR Torches Ledge WS'), ('TR Hub EN', 'TR Torches WN'), ('TR Hub NW', 'TR Pokey 1 SW'), ('TR Hub NE', 'TR Tile Room SE'), ('TR Torches NW', 'TR Roller Room SW'), ('TR Pipe Pit WN', 'TR Lava Dual Pipes EN'), ('TR Lava Island ES', 'TR Pipe Ledge WS'), ('TR Lava Dual Pipes SW', 'TR Twin Pokeys NW'), ('TR Lava Dual Pipes WN', 'TR Pokey 2 EN'), ('TR Pokey 2 ES', 'TR Lava Island WS'), ('TR Dodgers NE', 'TR Lava Escape SE'), ('TR Lava Escape NW', 'TR Dash Room SW'), ('TR Hallway WS', 'TR Lazy Eyes ES'), ('TR Dark Ride SW', 'TR Dash Bridge NW'), ('TR Dash Bridge SW', 'TR Eye Bridge NW'), ('TR Dash Bridge WS', 'TR Crystal Maze ES'), ('GT Torch WN', 'GT Conveyor Cross EN'), ('GT Hope Room EN', 'GT Tile Room WN'), ('GT Big Chest SW', 'GT Invisible Catwalk NW'), ('GT Bob\'s Room SE', 'GT Invisible Catwalk NE'), ('GT Speed Torch NE', 'GT Petting Zoo SE'), ('GT Speed Torch SE', 'GT Crystal Conveyor NE'), ('GT Warp Maze (Pits) ES', 'GT Invisible Catwalk WS'), ('GT Hookshot NW', 'GT DMs Room SW'), ('GT Hookshot SW', 'GT Double Switch NW'), ('GT Warp Maze (Rails) WS', 'GT Randomizer Room ES'), ('GT Conveyor Star Pits EN', 'GT Falling Bridge WN'), ('GT Falling Bridge WS', 'GT Hidden Star ES'), ('GT Dash Hall NE', 'GT Hidden Spikes SE'), ('GT Hidden Spikes EN', 'GT Cannonball Bridge WN'), ('GT Gauntlet 3 SW', 'GT Gauntlet 4 NW'), ('GT Gauntlet 5 WS', 'GT Beam Dash ES'), ('GT Wizzrobes 2 NE', 'GT Conveyor Bridge SE'), ('GT Conveyor Bridge EN', 'GT Torch Cross WN'), ('GT Crystal Circles SW', 'GT Left Moldorm Ledge NW') ] default_one_way_connections = [ ('Sewers Pull Switch S', 'Sanctuary N'), ('Eastern Duo Eyegores NE', 'Eastern Boss SE'), ('Desert Wall Slide NW', 'Desert Boss SW'), ('Tower Altar NW', 'Tower Agahnim 1 SW'), ('PoD Harmless Hellway SE', 'PoD Arena Main NE'), ('PoD Dark Alley NE', 'PoD Boss SE'), ('Swamp T NW', 'Swamp Boss SW'), ('Thieves Hallway NE', 'Thieves Boss SE'), ('Mire Antechamber NW', 'Mire Boss SW'), ('TR Final Abyss NW', 'TR Boss SW'), ('GT Invisible Bridges WS', 'GT Invisible Catwalk ES'), ('GT Validation WS', 'GT Frozen Over ES'), ('GT Brightly Lit Hall NW', 'GT Agahnim 2 SW') ] # For crossed # offset from 0x122e17, sram storage, write offset from compass_w_addr, 0 = jmp or # of nops, dungeon_id compass_data = { 'Hyrule Castle': (0x1, 0xc0, 0x16, 0, 0x02), 'Eastern Palace': (0x1C, 0xc1, 0x28, 0, 0x04), 'Desert Palace': (0x35, 0xc2, 0x4a, 0, 0x06), 'Agahnims Tower': (0x51, 0xc3, 0x5c, 0, 0x08), 'Swamp Palace': (0x6A, 0xc4, 0x7e, 0, 0x0a), 'Palace of Darkness': (0x83, 0xc5, 0xa4, 0, 0x0c), 'Misery Mire': (0x9C, 0xc6, 0xca, 0, 0x0e), 'Skull Woods': (0xB5, 0xc7, 0xf0, 0, 0x10), 'Ice Palace': (0xD0, 0xc8, 0x102, 0, 0x12), 'Tower of Hera': (0xEB, 0xc9, 0x114, 0, 0x14), 'Thieves Town': (0x106, 0xca, 0x138, 0, 0x16), 'Turtle Rock': (0x11F, 0xcb, 0x15e, 0, 0x18), 'Ganons Tower': (0x13A, 0xcc, 0x170, 2, 0x1a) } # For compass boss indicator boss_indicator = { 'Eastern Palace': (0x04, 'Eastern Boss SE'), 'Desert Palace': (0x06, 'Desert Boss SW'), 'Agahnims Tower': (0x08, 'Tower Agahnim 1 SW'), 'Swamp Palace': (0x0a, 'Swamp Boss SW'), 'Palace of Darkness': (0x0c, 'PoD Boss SE'), 'Misery Mire': (0x0e, 'Mire Boss SW'), 'Skull Woods': (0x10, 'Skull Spike Corner SW'), 'Ice Palace': (0x12, 'Ice Antechamber NE'), 'Tower of Hera': (0x14, 'Hera Boss Down Stairs'), 'Thieves Town': (0x16, 'Thieves Boss SE'), 'Turtle Rock': (0x18, 'TR Boss SW'), 'Ganons Tower': (0x1a, 'GT Agahnim 2 SW') } # tuples: (non-boss, boss) # see Utils for other notes palette_map = { 'Hyrule Castle': (0x0, None), 'Eastern Palace': (0xb, None), 'Desert Palace': (0x9, 0x4, 'Desert Boss SW'), 'Agahnims Tower': (0x0, 0xc, 'Tower Agahnim 1 SW'), # ancillary 0x26 for F1, F4 'Swamp Palace': (0xa, 0x8, 'Swamp Boss SW'), 'Palace of Darkness': (0xf, 0x10, 'PoD Boss SE'), 'Misery Mire': (0x11, 0x12, 'Mire Boss SW'), 'Skull Woods': (0xd, 0xe, 'Skull Spike Corner SW'), 'Ice Palace': (0x13, 0x14, 'Ice Antechamber NE'), 'Tower of Hera': (0x6, None), 'Thieves Town': (0x17, None), # the attic uses 0x23 'Turtle Rock': (0x18, 0x19, 'TR Boss SW'), 'Ganons Tower': (0x28, 0x1b, 'GT Agahnim 2 SW'), # other palettes: 0x1a (other) 0x24 (Gauntlet - Lanmo) 0x25 (conveyor-torch-wizzrode moldorm pit f5?) } # implications: # pipe room -> where lava chest is # dark alley -> where pod basement is # conveyor star or hidden star -> where DMs room is # falling bridge -> where Rando room is # petting zoo -> where firesnake is # basement cage -> where tile room is # bob's room -> where big chest/hope/torch are # invis bridges -> compass room palette_non_influencers = { 'PoD Shooter Room Up Stairs', 'TR Lava Dual Pipes EN', 'TR Lava Dual Pipes WN', 'TR Lava Dual Pipes SW', 'TR Lava Escape SE', 'TR Lava Escape NW', 'PoD Arena Ledge ES', 'Swamp Big Key Ledge WN', 'Swamp Hub Dead Ledge EN', 'Swamp Map Ledge EN', 'Skull Pot Prison ES', 'Skull Pot Prison SE', 'PoD Dark Alley NE', 'GT Conveyor Star Pits EN', 'GT Hidden Star ES', 'GT Falling Bridge WN', 'GT Falling Bridge WS', 'GT Petting Zoo SE', 'Hera Basement Cage Up Stairs', "GT Bob's Room SE", 'GT Warp Maze (Pits) ES', 'GT Invisible Bridges WS', 'Mire Over Bridge E', 'Mire Over Bridge W', 'Eastern Courtyard Ledge S', 'Eastern Courtyard Ledge W', 'Eastern Courtyard Ledge E', 'Eastern Map Valley WN', 'Eastern Map Valley SW', 'Mire BK Door Room EN', 'Mire BK Door Room N', 'TR Tile Room SE', 'TR Tile Room NE', 'TR Refill SE', 'Eastern Cannonball Ledge WN', 'Eastern Cannonball Ledge Key Door EN', 'Mire Neglected Room SE', 'Mire Neglected Room NE', 'Mire Chest View NE', 'TR Compass Room NW', 'Desert Dead End Edge', 'Hyrule Dungeon South Abyss Catwalk North Edge', 'Hyrule Dungeon South Abyss Catwalk West Edge' } portal_map = { 'Sanctuary': ('Sanctuary', 'Sanctuary Exit', 'Enter HC (Sanc)'), 'Hyrule Castle West': ('Hyrule Castle Entrance (West)', 'Hyrule Castle Exit (West)', 'Enter HC (West)'), 'Hyrule Castle South': ('Hyrule Castle Entrance (South)', 'Hyrule Castle Exit (South)', 'Enter HC (South)'), 'Hyrule Castle East': ('Hyrule Castle Entrance (East)', 'Hyrule Castle Exit (East)', 'Enter HC (East)'), 'Eastern': ('Eastern Palace', 'Eastern Palace Exit', 'Enter Eastern Palace'), 'Desert West': ('Desert Palace Entrance (West)', 'Desert Palace Exit (West)', 'Enter Desert (West)'), 'Desert South': ('Desert Palace Entrance (South)', 'Desert Palace Exit (South)', 'Enter Desert (South)'), 'Desert East': ('Desert Palace Entrance (East)', 'Desert Palace Exit (East)', 'Enter Desert (East)'), 'Desert Back': ('Desert Palace Entrance (North)', 'Desert Palace Exit (North)', 'Enter Desert (North)'), 'Turtle Rock Lazy Eyes': ('Dark Death Mountain Ledge (West)', 'Turtle Rock Ledge Exit (West)', 'Enter Turtle Rock (Lazy Eyes)'), 'Turtle Rock Eye Bridge': ('Turtle Rock Isolated Ledge Entrance', 'Turtle Rock Isolated Ledge Exit', 'Enter Turtle Rock (Laser Bridge)'), 'Turtle Rock Chest': ('Dark Death Mountain Ledge (East)', 'Turtle Rock Ledge Exit (East)', 'Enter Turtle Rock (Chest)'), 'Agahnims Tower': ('Agahnims Tower', 'Agahnims Tower Exit', 'Enter Agahnims Tower'), 'Swamp': ('Swamp Palace', 'Swamp Palace Exit', 'Enter Swamp'), 'Palace of Darkness': ('Palace of Darkness', 'Palace of Darkness Exit', 'Enter Palace of Darkness'), 'Mire': ('Misery Mire', 'Misery Mire Exit', 'Enter Misery Mire'), 'Skull 2 West': ('Skull Woods Second Section Door (West)', 'Skull Woods Second Section Exit (West)', 'Enter Skull Woods 2 (West)'), 'Skull 2 East': ('Skull Woods Second Section Door (East)', 'Skull Woods Second Section Exit (East)', 'Enter Skull Woods 2 (East)'), 'Skull 1': ('Skull Woods First Section Door', 'Skull Woods First Section Exit', 'Enter Skull Woods 1'), 'Skull 3': ('Skull Woods Final Section', 'Skull Woods Final Section Exit', 'Enter Skull Woods 3'), 'Ice': ('Ice Palace', 'Ice Palace Exit', 'Enter Ice Palace'), 'Hera': ('Tower of Hera', 'Tower of Hera Exit', 'Enter Hera'), 'Thieves Town': ('Thieves Town', 'Thieves Town Exit', 'Enter Thieves Town'), 'Turtle Rock Main': ('Turtle Rock', 'Turtle Rock Exit (Front)', 'Enter Turtle Rock (Main)'), 'Ganons Tower': ('Ganons Tower', 'Ganons Tower Exit', 'Enter Ganons Tower'), } multiple_portal_map = { 'Hyrule Castle': ['Sanctuary', 'Hyrule Castle West', 'Hyrule Castle South', 'Hyrule Castle East'], 'Desert Palace': ['Desert West', 'Desert South', 'Desert East', 'Desert Back'], 'Skull Woods': ['Skull 1', 'Skull 2 West', 'Skull 2 East', 'Skull 3'], 'Turtle Rock': ['Turtle Rock Lazy Eyes', 'Turtle Rock Eye Bridge', 'Turtle Rock Chest', 'Turtle Rock Main'], } split_portals = { 'Desert Palace': ['Back', 'Main'], 'Skull Woods': ['1', '2', '3'] } split_portal_defaults = { 'Desert Palace': { 'Desert Back Lobby': 'Back', 'Desert Main Lobby': 'Main', 'Desert West Lobby': 'Main', 'Desert East Lobby': 'Main' }, 'Skull Woods': { 'Skull 1 Lobby': '1', 'Skull 2 East Lobby': '2', 'Skull 2 West Lobby': '2', 'Skull 3 Lobby': '3' } } bomb_dash_counts = { 'Hyrule Castle': (0, 2), 'Eastern Palace': (0, 0), 'Desert Palace': (0, 0), 'Agahnims Tower': (0, 0), 'Swamp Palace': (2, 0), 'Palace of Darkness': (3, 2), 'Misery Mire': (2, 0), 'Skull Woods': (2, 0), 'Ice Palace': (0, 0), 'Tower of Hera': (0, 0), 'Thieves Town': (1, 1), 'Turtle Rock': (0, 2), # 2 bombs kind of for entrances 'Ganons Tower': (2, 1) }
import RaceRandom as random from collections import defaultdict, deque import logging import time from enum import unique, Flag from typing import DefaultDict, Dict, List from BaseClasses import RegionType, Region, Door, DoorType, Direction, Sector, CrystalBarrier, DungeonInfo, dungeon_keys from Doors import reset_portals from Dungeons import dungeon_regions, region_starts, standard_starts, split_region_starts from Dungeons import dungeon_bigs, dungeon_hints from Items import ItemFactory from RoomData import DoorKind, PairedDoor, reset_rooms from DungeonGenerator import ExplorationState, convert_regions, generate_dungeon, pre_validate, determine_required_paths, drop_entrances from DungeonGenerator import create_dungeon_builders, split_dungeon_builder, simple_dungeon_builder, default_dungeon_entrances from DungeonGenerator import dungeon_portals, dungeon_drops, GenerationException from KeyDoorShuffle import analyze_dungeon, build_key_layout, validate_key_layout, determine_prize_lock from Utils import ncr, kth_combination def link_doors(world, player): orig_swamp_patch = world.swamp_patch_required[player] attempt, valid = 1, False while not valid: try: link_doors_main(world, player) valid = True except GenerationException as e: logging.getLogger('').debug(f'Irreconcilable generation. {str(e)} Starting a new attempt.') attempt += 1 if attempt > 10: raise Exception('Could not create world in 10 attempts. Generation algorithms need more work', e) for door in world.doors: if door.player == player: door.dest = None door.entranceFlag = False ent = door.entrance if (door.type != DoorType.Logical or door.controller) and ent.connected_region is not None: ent.connected_region.entrances = [x for x in ent.connected_region.entrances if x != ent] ent.connected_region = None for portal in world.dungeon_portals[player]: disconnect_portal(portal, world, player) reset_portals(world, player) reset_rooms(world, player) world.get_door("Skull Pinball WS", player).no_exit() world.swamp_patch_required[player] = orig_swamp_patch def link_doors_main(world, player): # Drop-down connections & push blocks for exitName, regionName in logical_connections: connect_simple_door(world, exitName, regionName, player) # These should all be connected for now as normal connections for edge_a, edge_b in interior_doors: connect_interior_doors(edge_a, edge_b, world, player) # These connections are here because they are currently unable to be shuffled for exitName, regionName in falldown_pits: connect_simple_door(world, exitName, regionName, player) for exitName, regionName in dungeon_warps: connect_simple_door(world, exitName, regionName, player) if world.intensity[player] < 2: for entrance, ext in open_edges: connect_two_way(world, entrance, ext, player) for entrance, ext in straight_staircases: connect_two_way(world, entrance, ext, player) for entrance, ext in ladders: connect_two_way(world, entrance, ext, player) if world.intensity[player] < 3 or world.doorShuffle[player] == 'vanilla': mirror_route = world.get_entrance('Sanctuary Mirror Route', player) mr_door = mirror_route.door sanctuary = mirror_route.parent_region if mirror_route in sanctuary.exits: sanctuary.exits.remove(mirror_route) world.remove_entrance(mirror_route, player) world.remove_door(mr_door, player) connect_custom(world, player) find_inaccessible_regions(world, player) if world.intensity[player] >= 3 and world.doorShuffle[player] in ['basic', 'crossed']: choose_portals(world, player) else: if world.shuffle[player] == 'vanilla': if world.mode[player] == 'standard': world.get_portal('Sanctuary', player).destination = True world.get_portal('Desert East', player).destination = True if (world.mode[player] == 'inverted') != (0x30 in world.owswaps[player][0] and world.owMixed[player]): world.get_portal('Desert West', player).destination = True if (world.mode[player] == 'inverted') == (0x00 in world.owswaps[player][0] and world.owMixed[player]): world.get_portal('Skull 2 West', player).destination = True if (world.mode[player] == 'inverted') == (0x05 in world.owswaps[player][0] and world.owMixed[player]): world.get_portal('Turtle Rock Lazy Eyes', player).destination = True world.get_portal('Turtle Rock Eye Bridge', player).destination = True else: analyze_portals(world, player) for portal in world.dungeon_portals[player]: connect_portal(portal, world, player) if not world.doorShuffle[player] == 'vanilla': fix_big_key_doors_with_ugly_smalls(world, player) else: unmark_ugly_smalls(world, player) if world.doorShuffle[player] == 'vanilla': for entrance, ext in open_edges: connect_two_way(world, entrance, ext, player) for entrance, ext in straight_staircases: connect_two_way(world, entrance, ext, player) for exitName, regionName in vanilla_logical_connections: connect_simple_door(world, exitName, regionName, player) for entrance, ext in spiral_staircases: connect_two_way(world, entrance, ext, player) for entrance, ext in ladders: connect_two_way(world, entrance, ext, player) for entrance, ext in default_door_connections: connect_two_way(world, entrance, ext, player) for ent, ext in default_one_way_connections: connect_one_way(world, ent, ext, player) vanilla_key_logic(world, player) elif world.doorShuffle[player] == 'basic': within_dungeon(world, player) elif world.doorShuffle[player] == 'crossed': cross_dungeon(world, player) else: logging.getLogger('').error('Invalid door shuffle setting: %s' % world.doorShuffle[player]) raise Exception('Invalid door shuffle setting: %s' % world.doorShuffle[player]) if world.doorShuffle[player] != 'vanilla': create_door_spoiler(world, player) # todo: I think this function is not necessary def mark_regions(world, player): # traverse dungeons and make sure dungeon property is assigned player_dungeons = [dungeon for dungeon in world.dungeons if dungeon.player == player] for dungeon in player_dungeons: queue = deque(dungeon.regions) while len(queue) > 0: region = world.get_region(queue.popleft(), player) if region.name not in dungeon.regions: dungeon.regions.append(region.name) region.dungeon = dungeon for ext in region.exits: d = world.check_for_door(ext.name, player) connected = ext.connected_region if d is not None and connected is not None: if d.dest is not None and connected.name not in dungeon.regions and connected.type == RegionType.Dungeon and connected.name not in queue: queue.append(connected) # needs to be added elif connected is not None and connected.name not in dungeon.regions and connected.type == RegionType.Dungeon and connected.name not in queue: queue.append(connected) # needs to be added def create_door_spoiler(world, player): logger = logging.getLogger('') queue = deque(world.dungeon_layouts[player].values()) while len(queue) > 0: builder = queue.popleft() done = set() start_regions = set(convert_regions(builder.layout_starts, world, player)) # todo: set all_entrances for basic reg_queue = deque(start_regions) visited = set(start_regions) while len(reg_queue) > 0: next = reg_queue.pop() for ext in next.exits: door_a = ext.door connect = ext.connected_region if door_a and door_a.type in [DoorType.Normal, DoorType.SpiralStairs, DoorType.Open, DoorType.StraightStairs, DoorType.Ladder] and door_a not in done: done.add(door_a) door_b = door_a.dest if door_b and not isinstance(door_b, Region): done.add(door_b) if not door_a.blocked and not door_b.blocked: world.spoiler.set_door(door_a.name, door_b.name, 'both', player, builder.name) elif door_a.blocked: world.spoiler.set_door(door_b.name, door_a.name, 'entrance', player, builder.name) elif door_b.blocked: world.spoiler.set_door(door_a.name, door_b.name, 'entrance', player, builder.name) else: logger.warning('This is a bug during door spoiler') elif not isinstance(door_b, Region): logger.warning('Door not connected: %s', door_a.name) if connect and connect.type == RegionType.Dungeon and connect not in visited: visited.add(connect) reg_queue.append(connect) def vanilla_key_logic(world, player): builders = [] world.dungeon_layouts[player] = {} for dungeon in [dungeon for dungeon in world.dungeons if dungeon.player == player]: sector = Sector() sector.name = dungeon.name sector.regions.extend(convert_regions(dungeon.regions, world, player)) builder = simple_dungeon_builder(sector.name, [sector]) builder.master_sector = sector builders.append(builder) world.dungeon_layouts[player][builder.name] = builder add_inaccessible_doors(world, player) for builder in builders: origin_list = find_accessible_entrances(world, player, builder) start_regions = convert_regions(origin_list, world, player) doors = convert_key_doors(default_small_key_doors[builder.name], world, player) key_layout = build_key_layout(builder, start_regions, doors, world, player) valid = validate_key_layout(key_layout, world, player) if not valid: logging.getLogger('').warning('Vanilla key layout not valid %s', builder.name) builder.key_door_proposal = doors if player not in world.key_logic.keys(): world.key_logic[player] = {} analyze_dungeon(key_layout, world, player) world.key_logic[player][builder.name] = key_layout.key_logic log_key_logic(builder.name, key_layout.key_logic) # if world.shuffle[player] == 'vanilla' and world.owShuffle[player] == 'vanilla' and world.owCrossed[player] == 'none' and not world.owMixed[player] and world.accessibility[player] == 'items' and not world.retro[player] and not world.keydropshuffle[player]: # validate_vanilla_key_logic(world, player) # some useful functions oppositemap = { Direction.South: Direction.North, Direction.North: Direction.South, Direction.West: Direction.East, Direction.East: Direction.West, Direction.Up: Direction.Down, Direction.Down: Direction.Up, } def switch_dir(direction): return oppositemap[direction] def convert_key_doors(k_doors, world, player): result = [] for d in k_doors: if type(d) is tuple: result.append((world.get_door(d[0], player), world.get_door(d[1], player))) else: result.append(world.get_door(d, player)) return result def connect_custom(world, player): if hasattr(world, 'custom_doors') and world.custom_doors[player]: for entrance, ext in world.custom_doors[player]: connect_two_way(world, entrance, ext, player) def connect_simple_door(world, exit_name, region_name, player): region = world.get_region(region_name, player) world.get_entrance(exit_name, player).connect(region) d = world.check_for_door(exit_name, player) if d is not None: d.dest = region def connect_door_only(world, exit_name, region, player): d = world.check_for_door(exit_name, player) if d is not None: d.dest = region def connect_interior_doors(a, b, world, player): door_a = world.get_door(a, player) door_b = world.get_door(b, player) if door_a.blocked: connect_one_way(world, b, a, player) elif door_b.blocked: connect_one_way(world, a, b, player) else: connect_two_way(world, a, b, player) def connect_two_way(world, entrancename, exitname, player): entrance = world.get_entrance(entrancename, player) ext = world.get_entrance(exitname, player) # if these were already connected somewhere, remove the backreference if entrance.connected_region is not None: entrance.connected_region.entrances.remove(entrance) if ext.connected_region is not None: ext.connected_region.entrances.remove(ext) entrance.connect(ext.parent_region) ext.connect(entrance.parent_region) if entrance.parent_region.dungeon: ext.parent_region.dungeon = entrance.parent_region.dungeon x = world.check_for_door(entrancename, player) y = world.check_for_door(exitname, player) if x is not None: x.dest = y if y is not None: y.dest = x def connect_one_way(world, entrancename, exitname, player): entrance = world.get_entrance(entrancename, player) ext = world.get_entrance(exitname, player) # if these were already connected somewhere, remove the backreference if entrance.connected_region is not None: entrance.connected_region.entrances.remove(entrance) if ext.connected_region is not None: ext.connected_region.entrances.remove(ext) entrance.connect(ext.parent_region) if entrance.parent_region.dungeon: ext.parent_region.dungeon = entrance.parent_region.dungeon x = world.check_for_door(entrancename, player) y = world.check_for_door(exitname, player) if x is not None: x.dest = y if y is not None: y.dest = x def unmark_ugly_smalls(world, player): for d in ['Eastern Hint Tile Blocked Path SE', 'Eastern Darkness S', 'Thieves Hallway SE', 'Mire Left Bridge S', 'TR Lava Escape SE', 'GT Hidden Spikes SE']: door = world.get_door(d, player) door.smallKey = False def fix_big_key_doors_with_ugly_smalls(world, player): remove_ugly_small_key_doors(world, player) unpair_big_key_doors(world, player) def remove_ugly_small_key_doors(world, player): for d in ['Eastern Hint Tile Blocked Path SE', 'Eastern Darkness S', 'Thieves Hallway SE', 'Mire Left Bridge S', 'TR Lava Escape SE', 'GT Hidden Spikes SE']: door = world.get_door(d, player) room = world.get_room(door.roomIndex, player) if not door.entranceFlag: room.change(door.doorListPos, DoorKind.Normal) door.smallKey = False door.ugly = False def unpair_big_key_doors(world, player): problematic_bk_doors = ['Eastern Courtyard N', 'Eastern Big Key NE', 'Thieves BK Corner NE', 'Mire BK Door Room N', 'TR Dodgers NE', 'GT Dash Hall NE'] for paired_door in world.paired_doors[player]: if paired_door.door_a in problematic_bk_doors or paired_door.door_b in problematic_bk_doors: paired_door.pair = False def pair_existing_key_doors(world, player, door_a, door_b): already_paired = False door_names = [door_a.name, door_b.name] for pd in world.paired_doors[player]: if pd.door_a in door_names and pd.door_b in door_names: already_paired = True break if already_paired: return for paired_door in world.paired_doors[player]: if paired_door.door_a in door_names or paired_door.door_b in door_names: paired_door.pair = False world.paired_doors[player].append(PairedDoor(door_a, door_b)) def choose_portals(world, player): if world.doorShuffle[player] in ['basic', 'crossed']: cross_flag = world.doorShuffle[player] == 'crossed' # key drops allow the big key in the right place in Desert Tiles 2 bk_shuffle = world.bigkeyshuffle[player] or world.keydropshuffle[player] std_flag = world.mode[player] == 'standard' # roast incognito doors world.get_room(0x60, player).delete(5) world.get_room(0x60, player).change(2, DoorKind.DungeonEntrance) world.get_room(0x62, player).delete(5) world.get_room(0x62, player).change(1, DoorKind.DungeonEntrance) info_map = {} for dungeon, portal_list in dungeon_portals.items(): info = DungeonInfo(dungeon) region_map = defaultdict(list) reachable_portals = [] inaccessible_portals = [] hc_flag = std_flag and dungeon == 'Hyrule Castle' for portal in portal_list: placeholder = world.get_region(portal + ' Portal', player) portal_region = placeholder.exits[0].connected_region name = portal_region.name if portal_region.type == RegionType.LightWorld: world.get_portal(portal, player).light_world = True if name in world.inaccessible_regions[player] or (hc_flag and portal != 'Hyrule Castle South'): name_key = 'Desert Ledge' if name == 'Desert Palace Entrance (North) Spot' else name region_map[name_key].append(portal) inaccessible_portals.append(portal) else: reachable_portals.append(portal) info.total = len(portal_list) info.required_passage = region_map if len(reachable_portals) == 0: if len(inaccessible_portals) == 1: info.sole_entrance = inaccessible_portals[0] info.required_passage.clear() else: raise Exception('please inspect this case') if len(reachable_portals) == 1: info.sole_entrance = reachable_portals[0] info_map[dungeon] = info master_door_list = [x for x in world.doors if x.player == player and x.portalAble] portal_assignment = defaultdict(list) shuffled_info = list(info_map.items()) if cross_flag: random.shuffle(shuffled_info) for dungeon, info in shuffled_info: outstanding_portals = list(dungeon_portals[dungeon]) hc_flag = std_flag and dungeon == 'Hyrule Castle' rupee_bow_flag = hc_flag and world.retro[player] # rupee bow if hc_flag: sanc = world.get_portal('Sanctuary', player) sanc.destination = True clean_up_portal_assignment(portal_assignment, dungeon, sanc, master_door_list, outstanding_portals) for target_region, possible_portals in info.required_passage.items(): info.required_passage[target_region] = [x for x in possible_portals if x != sanc.name] info.required_passage = {x: y for x, y in info.required_passage.items() if len(y) > 0} for target_region, possible_portals in info.required_passage.items(): candidates = find_portal_candidates(master_door_list, dungeon, need_passage=True, crossed=cross_flag, bk_shuffle=bk_shuffle, rupee_bow=rupee_bow_flag) choice, portal = assign_portal(candidates, possible_portals, world, player) portal.destination = True clean_up_portal_assignment(portal_assignment, dungeon, portal, master_door_list, outstanding_portals) dead_end_choices = info.total - 1 - len(portal_assignment[dungeon]) for i in range(0, dead_end_choices): candidates = find_portal_candidates(master_door_list, dungeon, dead_end_allowed=True, crossed=cross_flag, bk_shuffle=bk_shuffle, rupee_bow=rupee_bow_flag) possible_portals = outstanding_portals if not info.sole_entrance else [x for x in outstanding_portals if x != info.sole_entrance] choice, portal = assign_portal(candidates, possible_portals, world, player) if choice.deadEnd: if choice.passage: portal.destination = True else: portal.deadEnd = True clean_up_portal_assignment(portal_assignment, dungeon, portal, master_door_list, outstanding_portals) the_rest = info.total - len(portal_assignment[dungeon]) for i in range(0, the_rest): candidates = find_portal_candidates(master_door_list, dungeon, crossed=cross_flag, bk_shuffle=bk_shuffle, standard=hc_flag, rupee_bow=rupee_bow_flag) choice, portal = assign_portal(candidates, outstanding_portals, world, player) clean_up_portal_assignment(portal_assignment, dungeon, portal, master_door_list, outstanding_portals) for portal in world.dungeon_portals[player]: connect_portal(portal, world, player) hc_south = world.get_door('Hyrule Castle Lobby S', player) if not hc_south.entranceFlag: world.get_room(0x61, player).delete(6) world.get_room(0x61, player).change(4, DoorKind.NormalLow) else: world.get_room(0x61, player).change(4, DoorKind.DungeonEntrance) world.get_room(0x61, player).change(6, DoorKind.CaveEntranceLow) sanctuary_door = world.get_door('Sanctuary S', player) if not sanctuary_door.entranceFlag: world.get_room(0x12, player).delete(3) world.get_room(0x12, player).change(2, DoorKind.NormalLow) else: world.get_room(0x12, player).change(2, DoorKind.DungeonEntrance) world.get_room(0x12, player).change(3, DoorKind.CaveEntranceLow) hera_door = world.get_door('Hera Lobby S', player) if not hera_door.entranceFlag: world.get_room(0x77, player).change(0, DoorKind.NormalLow2) # tr rock bomb entrances for portal in world.dungeon_portals[player]: if not portal.destination and not portal.deadEnd: if portal.door.name == 'TR Lazy Eyes SE': world.get_room(0x23, player).change(0, DoorKind.DungeonEntrance) if portal.door.name == 'TR Eye Bridge SW': world.get_room(0xd5, player).change(0, DoorKind.DungeonEntrance) if not world.swamp_patch_required[player]: swamp_portal = world.get_portal('Swamp', player) if swamp_portal.door.name != 'Swamp Lobby S': world.swamp_patch_required[player] = True def analyze_portals(world, player): info_map = {} for dungeon, portal_list in dungeon_portals.items(): info = DungeonInfo(dungeon) region_map = defaultdict(list) reachable_portals = [] inaccessible_portals = [] for portal in portal_list: placeholder = world.get_region(portal + ' Portal', player) portal_region = placeholder.exits[0].connected_region name = portal_region.name if portal_region.type == RegionType.LightWorld: world.get_portal(portal, player).light_world = True if name in world.inaccessible_regions[player]: name_key = 'Desert Ledge' if name == 'Desert Palace Entrance (North) Spot' else name region_map[name_key].append(portal) inaccessible_portals.append(portal) else: reachable_portals.append(portal) info.total = len(portal_list) info.required_passage = region_map if len(reachable_portals) == 0: if len(inaccessible_portals) == 1: info.sole_entrance = inaccessible_portals[0] info.required_passage.clear() else: raise Exception('please inspect this case') if len(reachable_portals) == 1: info.sole_entrance = reachable_portals[0] if world.intensity[player] < 2 and world.doorShuffle[player] == 'basic' and dungeon == 'Desert Palace': if len(inaccessible_portals) == 1 and inaccessible_portals[0] == 'Desert Back': info.required_passage.clear() # can't make a passage at this intensity level, something else must exit info_map[dungeon] = info for dungeon, info in info_map.items(): if dungeon == 'Hyrule Castle' and world.mode[player] == 'standard': sanc = world.get_portal('Sanctuary', player) sanc.destination = True for target_region, possible_portals in info.required_passage.items(): if len(possible_portals) == 1: world.get_portal(possible_portals[0], player).destination = True elif len(possible_portals) > 1: dest_portal = random.choice(possible_portals) access_portal = world.get_portal(dest_portal, player) access_portal.destination = True for other_portal in possible_portals: if other_portal != dest_portal: world.get_portal(dest_portal, player).dependent = access_portal def connect_portal(portal, world, player): ent, ext, entrance_name = portal_map[portal.name] portal_entrance = world.get_entrance(portal.door.entrance.name, player) # ensures I get the right one for copying target_exit = world.get_entrance(ext, player) portal_entrance.connected_region = target_exit.parent_region portal_region = world.get_region(portal.name + ' Portal', player) portal_region.entrances.append(portal_entrance) edit_entrance = world.get_entrance(entrance_name, player) edit_entrance.connected_region = portal_entrance.parent_region chosen_door = world.get_door(portal_entrance.name, player) chosen_door.blocked = False connect_door_only(world, chosen_door, portal_region, player) portal_entrance.parent_region.entrances.append(edit_entrance) def disconnect_portal(portal, world, player): ent, ext, entrance_name = portal_map[portal.name] portal_entrance = world.get_entrance(portal.door.entrance.name, player) # portal_region = world.get_region(portal.name + ' Portal', player) edit_entrance = world.get_entrance(entrance_name, player) chosen_door = world.get_door(portal_entrance.name, player) # reverse work if edit_entrance in portal_entrance.parent_region.entrances: portal_entrance.parent_region.entrances.remove(edit_entrance) chosen_door.blocked = chosen_door.blocked_orig chosen_door.entranceFlag = False def find_portal_candidates(door_list, dungeon, need_passage=False, dead_end_allowed=False, crossed=False, bk_shuffle=False, standard=False, rupee_bow=False): ret = [x for x in door_list if bk_shuffle or not x.bk_shuffle_req] if crossed: ret = [x for x in ret if not x.dungeonLink or x.dungeonLink == dungeon or x.dungeonLink.startswith('link')] else: ret = [x for x in ret if x.entrance.parent_region.dungeon.name == dungeon] if need_passage: ret = [x for x in ret if x.passage] if not dead_end_allowed: ret = [x for x in ret if not x.deadEnd] if standard: ret = [x for x in ret if not x.standard_restricted] if rupee_bow: ret = [x for x in ret if not x.rupee_bow_restricted] return ret def assign_portal(candidates, possible_portals, world, player): candidate = random.choice(candidates) portal_choice = random.choice(possible_portals) portal = world.get_portal(portal_choice, player) while candidate.lw_restricted and not portal.light_world: candidates.remove(candidate) candidate = random.choice(candidates) if candidate != portal.door: if candidate.entranceFlag: for other_portal in world.dungeon_portals[player]: if other_portal.door == candidate: other_portal.door = None break old_door = portal.door if old_door: old_door.entranceFlag = False if old_door.name not in ['Hyrule Castle Lobby S', 'Sanctuary S', 'Hera Lobby S']: old_door_kind = DoorKind.NormalLow if old_door.layer or old_door.pseudo_bg else DoorKind.Normal world.get_room(old_door.roomIndex, player).change(old_door.doorListPos, old_door_kind) portal.change_door(candidate) if candidate.name not in ['Hyrule Castle Lobby S', 'Sanctuary S']: if candidate.name == 'Swamp Hub S': new_door_kind = DoorKind.CaveEntranceLow elif candidate.layer or candidate.pseudo_bg: new_door_kind = DoorKind.DungeonEntranceLow else: new_door_kind = DoorKind.DungeonEntrance world.get_room(candidate.roomIndex, player).change(candidate.doorListPos, new_door_kind) candidate.entranceFlag = True return candidate, portal def clean_up_portal_assignment(portal_assignment, dungeon, portal, master_door_list, outstanding_portals): portal_assignment[dungeon].append(portal) master_door_list[:] = [x for x in master_door_list if x.roomIndex != portal.door.roomIndex] if portal.door.dungeonLink and portal.door.dungeonLink.startswith('link'): match_link = portal.door.dungeonLink for door in master_door_list: if door.dungeonLink == match_link: door.dungeonLink = dungeon outstanding_portals.remove(portal.name) def create_dungeon_entrances(world, player): entrance_map = defaultdict(list) split_map: DefaultDict[str, DefaultDict[str, List]] = defaultdict(lambda: defaultdict(list)) originating: DefaultDict[str, DefaultDict[str, Dict]] = defaultdict(lambda: defaultdict(dict)) for key, portal_list in dungeon_portals.items(): if key in dungeon_drops.keys(): entrance_map[key].extend(dungeon_drops[key]) if key in split_portals.keys(): dead_ends = [] destinations = [] the_rest = [] for portal_name in portal_list: portal = world.get_portal(portal_name, player) entrance_map[key].append(portal.door.entrance.parent_region.name) if portal.deadEnd: dead_ends.append(portal) elif portal.destination: destinations.append(portal) else: the_rest.append(portal) choices = list(split_portals[key]) for portal in dead_ends: choice = random.choice(choices) choices.remove(choice) r_name = portal.door.entrance.parent_region.name split_map[key][choice].append(r_name) for portal in the_rest: if len(choices) == 0: choices.append('Extra') choice = random.choice(choices) p_entrance = portal.door.entrance r_name = p_entrance.parent_region.name split_map[key][choice].append(r_name) entrance_region = find_entrance_region(portal) originating[key][choice][entrance_region.name] = None dest_choices = [x for x in choices if len(split_map[key][x]) > 0] for portal in destinations: entrance_region = find_entrance_region(portal) restricted = entrance_region.name in world.inaccessible_regions[player] if restricted: filtered_choices = [x for x in choices if any(y not in world.inaccessible_regions[player] for y in originating[key][x].keys())] else: filtered_choices = dest_choices if len(filtered_choices) == 0: raise Exception('No valid destinations') choice = random.choice(filtered_choices) r_name = portal.door.entrance.parent_region.name split_map[key][choice].append(r_name) else: for portal_name in portal_list: portal = world.get_portal(portal_name, player) r_name = portal.door.entrance.parent_region.name entrance_map[key].append(r_name) return entrance_map, split_map def find_entrance_region(portal): for entrance in portal.door.entrance.connected_region.entrances: if entrance.parent_region.type != RegionType.Dungeon: return entrance.parent_region return None # def unpair_all_doors(world, player): # for paired_door in world.paired_doors[player]: # paired_door.pair = False def within_dungeon(world, player): add_inaccessible_doors(world, player) entrances_map, potentials, connections = determine_entrance_list(world, player) connections_tuple = (entrances_map, potentials, connections) dungeon_builders = {} for key in dungeon_regions.keys(): sector_list = convert_to_sectors(dungeon_regions[key], world, player) dungeon_builders[key] = simple_dungeon_builder(key, sector_list) dungeon_builders[key].entrance_list = list(entrances_map[key]) recombinant_builders = {} entrances, splits = create_dungeon_entrances(world, player) builder_info = entrances, splits, connections_tuple, world, player handle_split_dungeons(dungeon_builders, recombinant_builders, entrances_map, builder_info) main_dungeon_generation(dungeon_builders, recombinant_builders, connections_tuple, world, player) paths = determine_required_paths(world, player) check_required_paths(paths, world, player) # shuffle_key_doors for dungeons logging.getLogger('').info(world.fish.translate("cli", "cli", "shuffling.keydoors")) start = time.process_time() for builder in world.dungeon_layouts[player].values(): shuffle_key_doors(builder, world, player) logging.getLogger('').info('%s: %s', world.fish.translate("cli", "cli", "keydoor.shuffle.time"), time.process_time()-start) smooth_door_pairs(world, player) if world.intensity[player] >= 3: portal = world.get_portal('Sanctuary', player) target = portal.door.entrance.parent_region connect_simple_door(world, 'Sanctuary Mirror Route', target, player) refine_boss_exits(world, player) def handle_split_dungeons(dungeon_builders, recombinant_builders, entrances_map, builder_info): dungeon_entrances, split_dungeon_entrances, c_tuple, world, player = builder_info if dungeon_entrances is None: dungeon_entrances = default_dungeon_entrances if split_dungeon_entrances is None: split_dungeon_entrances = split_region_starts builder_info = dungeon_entrances, split_dungeon_entrances, c_tuple, world, player for name, split_list in split_dungeon_entrances.items(): builder = dungeon_builders.pop(name) recombinant_builders[name] = builder split_builders = split_dungeon_builder(builder, split_list, builder_info) dungeon_builders.update(split_builders) for sub_name, split_entrances in split_list.items(): key = name+' '+sub_name if key not in dungeon_builders: continue sub_builder = dungeon_builders[key] sub_builder.split_flag = True entrance_list = list(split_entrances) for ent in entrances_map[name]: add_shuffled_entrances(sub_builder.sectors, ent, entrance_list) filtered_entrance_list = [x for x in entrance_list if x in entrances_map[name]] sub_builder.entrance_list = filtered_entrance_list def main_dungeon_generation(dungeon_builders, recombinant_builders, connections_tuple, world, player): entrances_map, potentials, connections = connections_tuple enabled_entrances = world.enabled_entrances[player] = {} sector_queue = deque(dungeon_builders.values()) last_key, loops = None, 0 logging.getLogger('').info(world.fish.translate("cli", "cli", "generating.dungeon")) while len(sector_queue) > 0: builder = sector_queue.popleft() split_dungeon = builder.name.startswith('Desert Palace') or builder.name.startswith('Skull Woods') name = builder.name if split_dungeon: name = ' '.join(builder.name.split(' ')[:-1]) if len(builder.sectors) == 0: del dungeon_builders[builder.name] continue origin_list = list(builder.entrance_list) find_enabled_origins(builder.sectors, enabled_entrances, origin_list, entrances_map, name) split_dungeon = treat_split_as_whole_dungeon(split_dungeon, name, origin_list, world, player) if len(origin_list) <= 0 or not pre_validate(builder, origin_list, split_dungeon, world, player): if last_key == builder.name or loops > 1000: origin_name = world.get_region(origin_list[0], player).entrances[0].parent_region.name if len(origin_list) > 0 else 'no origin' raise GenerationException(f'Infinite loop detected for "{builder.name}" located at {origin_name}') sector_queue.append(builder) last_key = builder.name loops += 1 else: ds = generate_dungeon(builder, origin_list, split_dungeon, world, player) find_new_entrances(ds, entrances_map, connections, potentials, enabled_entrances, world, player) ds.name = name builder.master_sector = ds builder.layout_starts = origin_list if len(builder.entrance_list) <= 0 else builder.entrance_list last_key = None combine_layouts(recombinant_builders, dungeon_builders, entrances_map) world.dungeon_layouts[player] = {} for builder in dungeon_builders.values(): builder.entrance_list = builder.layout_starts = builder.path_entrances = find_accessible_entrances(world, player, builder) world.dungeon_layouts[player] = dungeon_builders def determine_entrance_list_vanilla(world, player): entrance_map = {} potential_entrances = {} connections = {} for key, r_names in region_starts.items(): entrance_map[key] = [] if world.mode[player] == 'standard' and key in standard_starts.keys(): r_names = ['Hyrule Castle Lobby'] for region_name in r_names: region = world.get_region(region_name, player) for ent in region.entrances: parent = ent.parent_region if (parent.type != RegionType.Dungeon and parent.name != 'Menu' and parent.name != 'Flute Sky') or parent.name == 'Sewer Drop': if parent.name not in world.inaccessible_regions[player]: entrance_map[key].append(region_name) else: if ent.parent_region not in potential_entrances.keys(): potential_entrances[parent] = [] potential_entrances[parent].append(region_name) connections[region_name] = parent return entrance_map, potential_entrances, connections def determine_entrance_list(world, player): entrance_map = {} potential_entrances = {} connections = {} for key, portal_list in dungeon_portals.items(): entrance_map[key] = [] r_names = {} if key in dungeon_drops.keys(): for drop in dungeon_drops[key]: r_names[drop] = None for portal_name in portal_list: portal = world.get_portal(portal_name, player) r_names[portal.door.entrance.parent_region.name] = portal for region_name, portal in r_names.items(): if portal: region = world.get_region(portal.name + ' Portal', player) else: region = world.get_region(region_name, player) for ent in region.entrances: parent = ent.parent_region if (parent.type != RegionType.Dungeon and parent.name != 'Menu' and parent.name != 'Flute Sky') or parent.name == 'Sewer Drop': std_inaccessible = is_standard_inaccessible(key, portal, world, player) if parent.name not in world.inaccessible_regions[player] and not std_inaccessible: entrance_map[key].append(region_name) else: if parent not in potential_entrances.keys(): potential_entrances[parent] = [] if region_name not in potential_entrances[parent]: potential_entrances[parent].append(region_name) connections[region_name] = parent return entrance_map, potential_entrances, connections def is_standard_inaccessible(key, portal, world, player): return world.mode[player] == 'standard' and key in standard_starts and (not portal or portal.name not in standard_starts[key]) def add_shuffled_entrances(sectors, region_list, entrance_list): for sector in sectors: for region in sector.regions: if region.name in region_list and region.name not in entrance_list: entrance_list.append(region.name) def find_enabled_origins(sectors, enabled, entrance_list, entrance_map, key): for sector in sectors: for region in sector.regions: if region.name in enabled.keys() and region.name not in entrance_list: entrance_list.append(region.name) origin_reg, origin_dungeon = enabled[region.name] if origin_reg != region.name and origin_dungeon != region.dungeon: if key not in entrance_map.keys(): key = ' '.join(key.split(' ')[:-1]) entrance_map[key].append(region.name) def find_new_entrances(sector, entrances_map, connections, potentials, enabled, world, player): for region in sector.regions: if region.name in connections.keys() and (connections[region.name] in potentials.keys() or connections[region.name].name in world.inaccessible_regions[player]): enable_new_entrances(region, connections, potentials, enabled, world, player, region) inverted_aga_check(entrances_map, connections, potentials, enabled, world, player) def enable_new_entrances(region, connections, potentials, enabled, world, player, region_enabler): new_region = connections[region.name] if new_region in potentials.keys(): for potential in potentials.pop(new_region): enabled[potential] = (region_enabler.name, region_enabler.dungeon) # see if this unexplored region connects elsewhere queue = deque(new_region.exits) visited = set() while len(queue) > 0: ext = queue.popleft() visited.add(ext) if ext.connected_region is None: continue region_name = ext.connected_region.name if region_name in connections.keys() and connections[region_name] in potentials.keys(): for potential in potentials.pop(connections[region_name]): enabled[potential] = (region.name, region.dungeon) if ext.connected_region.name in world.inaccessible_regions[player] or ext.connected_region.name.endswith(' Portal'): for new_exit in ext.connected_region.exits: if new_exit not in visited: queue.append(new_exit) def inverted_aga_check(entrances_map, connections, potentials, enabled, world, player): if world.mode[player] == 'inverted': if 'Agahnims Tower' in entrances_map.keys() or aga_tower_enabled(enabled): for region in list(potentials.keys()): if region.name == 'Hyrule Castle Ledge': enabler = world.get_region('Tower Agahnim 1', player) for r_name in potentials[region]: new_region = world.get_region(r_name, player) enable_new_entrances(new_region, connections, potentials, enabled, world, player, enabler) def aga_tower_enabled(enabled): for region_name, enabled_tuple in enabled.items(): entrance, dungeon = enabled_tuple if dungeon.name == 'Agahnims Tower': return True return False def treat_split_as_whole_dungeon(split_dungeon, name, origin_list, world, player): # what about ER dungeons? - find an example? (bad key doors 0 keys not valid) if split_dungeon and name in multiple_portal_map: possible_entrances = [] for portal_name in multiple_portal_map[name]: portal = world.get_portal(portal_name, player) portal_entrance = world.get_entrance(portal_map[portal_name][0], player) if not portal.destination and portal_entrance.parent_region.name not in world.inaccessible_regions[player]: possible_entrances.append(portal) if len(possible_entrances) == 1: single_portal = possible_entrances[0] if single_portal.door.entrance.parent_region.name in origin_list and len(origin_list) == 1: return False return split_dungeon # goals: # 1. have enough chests to be interesting (2 more than dungeon items) # 2. have a balanced amount of regions added (check) # 3. prevent soft locks due to key usage (algorithm written) # 4. rules in place to affect item placement (lamp, keys, etc. -- in rules) # 5. to be complete -- all doors linked (check, somewhat) # 6. avoid deadlocks/dead end dungeon (check) # 7. certain paths through dungeon must be possible - be able to reach goals (check) def cross_dungeon(world, player): add_inaccessible_doors(world, player) entrances_map, potentials, connections = determine_entrance_list(world, player) connections_tuple = (entrances_map, potentials, connections) all_sectors, all_regions = [], [] for key in dungeon_regions.keys(): all_regions += dungeon_regions[key] all_sectors.extend(convert_to_sectors(all_regions, world, player)) merge_sectors(all_sectors, world, player) entrances, splits = create_dungeon_entrances(world, player) dungeon_builders = create_dungeon_builders(all_sectors, connections_tuple, world, player, entrances, splits) for builder in dungeon_builders.values(): builder.entrance_list = list(entrances_map[builder.name]) dungeon_obj = world.get_dungeon(builder.name, player) for sector in builder.sectors: for region in sector.regions: region.dungeon = dungeon_obj for loc in region.locations: if loc.forced_item: key_name = dungeon_keys[builder.name] if loc.name != 'Hyrule Castle - Big Key Drop' else dungeon_bigs[builder.name] loc.forced_item = loc.item = ItemFactory(key_name, player) recombinant_builders = {} builder_info = entrances, splits, connections_tuple, world, player handle_split_dungeons(dungeon_builders, recombinant_builders, entrances_map, builder_info) main_dungeon_generation(dungeon_builders, recombinant_builders, connections_tuple, world, player) paths = determine_required_paths(world, player) check_required_paths(paths, world, player) hc = world.get_dungeon('Hyrule Castle', player) hc.dungeon_items.append(ItemFactory('Compass (Escape)', player)) at = world.get_dungeon('Agahnims Tower', player) at.dungeon_items.append(ItemFactory('Compass (Agahnims Tower)', player)) at.dungeon_items.append(ItemFactory('Map (Agahnims Tower)', player)) assign_cross_keys(dungeon_builders, world, player) all_dungeon_items_cnt = len(list(y for x in world.dungeons if x.player == player for y in x.all_items)) if world.keydropshuffle[player]: target_items = 35 if world.retro[player] else 96 else: target_items = 34 if world.retro[player] else 63 d_items = target_items - all_dungeon_items_cnt world.pool_adjustment[player] = d_items smooth_door_pairs(world, player) # Re-assign dungeon bosses gt = world.get_dungeon('Ganons Tower', player) for name, builder in dungeon_builders.items(): reassign_boss('GT Ice Armos', 'bottom', builder, gt, world, player) reassign_boss('GT Lanmolas 2', 'middle', builder, gt, world, player) reassign_boss('GT Moldorm', 'top', builder, gt, world, player) sanctuary = world.get_region('Sanctuary', player) d_name = sanctuary.dungeon.name if d_name != 'Hyrule Castle': possible_portals = [] for portal_name in dungeon_portals[d_name]: portal = world.get_portal(portal_name, player) if portal.door.name == 'Sanctuary S': possible_portals.clear() possible_portals.append(portal) break if not portal.destination and not portal.deadEnd: possible_portals.append(portal) if len(possible_portals) == 1: world.sanc_portal[player] = possible_portals[0] else: reachable_portals = [] for portal in possible_portals: start_area = portal.door.entrance.parent_region state = ExplorationState(dungeon=d_name) state.visit_region(start_area) state.add_all_doors_check_unattached(start_area, world, player) explore_state(state, world, player) if state.visited_at_all(sanctuary): reachable_portals.append(portal) world.sanc_portal[player] = random.choice(reachable_portals) if world.intensity[player] >= 3: if player in world.sanc_portal: portal = world.sanc_portal[player] else: portal = world.get_portal('Sanctuary', player) target = portal.door.entrance.parent_region connect_simple_door(world, 'Sanctuary Mirror Route', target, player) check_entrance_fixes(world, player) if world.standardize_palettes[player] == 'standardize': palette_assignment(world, player) refine_hints(dungeon_builders) refine_boss_exits(world, player) def assign_cross_keys(dungeon_builders, world, player): logging.getLogger('').info(world.fish.translate("cli", "cli", "shuffling.keydoors")) start = time.process_time() if world.retro[player]: remaining = 61 if world.keydropshuffle[player] else 29 else: remaining = len(list(x for dgn in world.dungeons if dgn.player == player for x in dgn.small_keys)) total_keys = remaining total_candidates = 0 start_regions_map = {} # Step 1: Find Small Key Door Candidates for name, builder in dungeon_builders.items(): dungeon = world.get_dungeon(name, player) if not builder.bk_required or builder.bk_provided: dungeon.big_key = None elif builder.bk_required and not builder.bk_provided: dungeon.big_key = ItemFactory(dungeon_bigs[name], player) start_regions = convert_regions(builder.path_entrances, world, player) find_small_key_door_candidates(builder, start_regions, world, player) builder.key_doors_num = max(0, len(builder.candidates) - builder.key_drop_cnt) total_candidates += builder.key_doors_num start_regions_map[name] = start_regions # Step 2: Initial Key Number Assignment & Calculate Flexibility for name, builder in dungeon_builders.items(): calculated = int(round(builder.key_doors_num*total_keys/total_candidates)) max_keys = builder.location_cnt - calc_used_dungeon_items(builder) cand_len = max(0, len(builder.candidates) - builder.key_drop_cnt) limit = min(max_keys, cand_len) suggested = min(calculated, limit) combo_size = ncr(len(builder.candidates), suggested + builder.key_drop_cnt) while combo_size > 500000 and suggested > 0: suggested -= 1 combo_size = ncr(len(builder.candidates), suggested + builder.key_drop_cnt) builder.key_doors_num = suggested + builder.key_drop_cnt remaining -= suggested builder.combo_size = combo_size if suggested < limit: builder.flex = limit - suggested # Step 3: Initial valid combination find - reduce flex if needed for name, builder in dungeon_builders.items(): suggested = builder.key_doors_num - builder.key_drop_cnt builder.total_keys = builder.key_doors_num find_valid_combination(builder, start_regions_map[name], world, player) actual_chest_keys = builder.key_doors_num - builder.key_drop_cnt if actual_chest_keys < suggested: remaining += suggested - actual_chest_keys builder.flex = 0 # Step 4: Try to assign remaining keys builder_order = [x for x in dungeon_builders.values() if x.flex > 0] builder_order.sort(key=lambda b: b.combo_size) queue = deque(builder_order) logger = logging.getLogger('') while len(queue) > 0 and remaining > 0: builder = queue.popleft() name = builder.name logger.debug('Cross Dungeon: Increasing key count by 1 for %s', name) builder.key_doors_num += 1 builder.total_keys = builder.key_doors_num result = find_valid_combination(builder, start_regions_map[name], world, player, drop_keys=False) if result: remaining -= 1 builder.flex -= 1 if builder.flex > 0: builder.combo_size = ncr(len(builder.candidates), builder.key_doors_num) queue.append(builder) queue = deque(sorted(queue, key=lambda b: b.combo_size)) else: logger.debug('Cross Dungeon: Increase failed for %s', name) builder.key_doors_num -= 1 builder.flex = 0 logger.debug('Cross Dungeon: Keys unable to assign in pool %s', remaining) # Last Step: Adjust Small Key Dungeon Pool for name, builder in dungeon_builders.items(): reassign_key_doors(builder, world, player) if not world.retro[player]: log_key_logic(builder.name, world.key_logic[player][builder.name]) actual_chest_keys = max(builder.key_doors_num - builder.key_drop_cnt, 0) dungeon = world.get_dungeon(name, player) if actual_chest_keys == 0: dungeon.small_keys = [] else: dungeon.small_keys = [ItemFactory(dungeon_keys[name], player)] * actual_chest_keys logger.info(f'{world.fish.translate("cli", "cli", "keydoor.shuffle.time.crossed")}: {time.process_time()-start}') def reassign_boss(boss_region, boss_key, builder, gt, world, player): if boss_region in builder.master_sector.region_set(): new_dungeon = world.get_dungeon(builder.name, player) if new_dungeon != gt: gt_boss = gt.bosses.pop(boss_key) new_dungeon.bosses[boss_key] = gt_boss def check_entrance_fixes(world, player): # I believe these modes will be fine if world.shuffle[player] not in ['insanity', 'insanity_legacy', 'madness_legacy']: checks = { 'Palace of Darkness': 'pod', 'Skull Woods Final Section': 'sw', 'Turtle Rock': 'tr', 'Ganons Tower': 'gt', } if world.mode[player] == 'inverted': del checks['Ganons Tower'] for ent_name, key in checks.items(): entrance = world.get_entrance(ent_name, player) dungeon = entrance.connected_region.dungeon if dungeon: layout = world.dungeon_layouts[player][dungeon.name] if 'Sanctuary' in layout.master_sector.region_set() or dungeon.name in ['Hyrule Castle', 'Desert Palace', 'Skull Woods', 'Turtle Rock']: portal = None for portal_name in dungeon_portals[dungeon.name]: test_portal = world.get_portal(portal_name, player) if entrance.connected_region == test_portal.door.entrance.connected_region: portal = test_portal break world.force_fix[player][key] = portal def palette_assignment(world, player): for portal in world.dungeon_portals[player]: if portal.door.roomIndex >= 0: room = world.get_room(portal.door.roomIndex, player) if room.palette is None: name = portal.door.entrance.parent_region.dungeon.name room.palette = palette_map[name][0] for name, builder in world.dungeon_layouts[player].items(): for region in builder.master_sector.regions: for ext in region.exits: if ext.door and ext.door.roomIndex >= 0 and ext.door.name not in palette_non_influencers: room = world.get_room(ext.door.roomIndex, player) if room.palette is None: room.palette = palette_map[name][0] for name, tuple in palette_map.items(): if tuple[1] is not None: door_name = boss_indicator[name][1] door = world.get_door(door_name, player) room = world.get_room(door.roomIndex, player) room.palette = tuple[1] if tuple[2]: leading_door = world.get_door(tuple[2], player) ent = next(iter(leading_door.entrance.parent_region.entrances)) if ent.door and door.roomIndex: room = world.get_room(door.roomIndex, player) room.palette = tuple[1] rat_path = world.get_region('Sewers Rat Path', player) visited_rooms = set() visited_regions = {rat_path} queue = deque([(rat_path, 0)]) while len(queue) > 0: region, dist = queue.popleft() if dist > 5: continue for ext in region.exits: if ext.door and ext.door.roomIndex >= 0 and ext.door.name not in palette_non_influencers: room_idx = ext.door.roomIndex if room_idx not in visited_rooms: room = world.get_room(room_idx, player) room.palette = 0x1 visited_rooms.add(room_idx) if ext.door and ext.door.type in [DoorType.SpiralStairs, DoorType.Ladder]: if ext.door.dest and ext.door.dest.roomIndex: visited_rooms.add(ext.door.dest.roomIndex) if ext.connected_region: visited_regions.add(ext.connected_region) elif ext.connected_region and ext.connected_region.type == RegionType.Dungeon and ext.connected_region not in visited_regions: queue.append((ext.connected_region, dist+1)) visited_regions.add(ext.connected_region) sanc = world.get_region('Sanctuary', player) if sanc.dungeon.name == 'Hyrule Castle': room = world.get_room(0x12, player) room.palette = 0x1d for connection in ['Sanctuary S', 'Sanctuary N']: adjacent = world.get_entrance(connection, player) adj_dest = adjacent.door.dest if adj_dest and isinstance(adj_dest, Door) and adj_dest.entrance.parent_region.type == RegionType.Dungeon: if adjacent.door and adjacent.door.dest and adjacent.door.dest.roomIndex >= 0: room = world.get_room(adjacent.door.dest.roomIndex, player) room.palette = 0x1d eastfairies = world.get_room(0x89, player) eastfairies.palette = palette_map[world.get_region('Eastern Courtyard', player).dungeon.name][0] # other ones that could use programmatic treatment: Skull Boss x29, Hera Fairies xa7, Ice Boss xde (Ice Fairies!) def refine_hints(dungeon_builders): for name, builder in dungeon_builders.items(): for region in builder.master_sector.regions: for location in region.locations: if not location.event and '- Boss' not in location.name and '- Prize' not in location.name and location.name != 'Sanctuary': location.hint_text = dungeon_hints[name] def refine_boss_exits(world, player): for d_name, d_boss in {'Desert Palace': 'Desert Boss', 'Skull Woods': 'Skull Boss', 'Turtle Rock': 'TR Boss'}.items(): possible_portals = [] current_boss = None for portal_name in dungeon_portals[d_name]: portal = world.get_portal(portal_name, player) if not portal.destination: possible_portals.append(portal) if portal.boss_exit_idx > -1: current_boss = portal if len(possible_portals) == 1: if possible_portals[0] != current_boss: possible_portals[0].change_boss_exit(current_boss.boss_exit_idx) current_boss.change_boss_exit(-1) else: reachable_portals = [] for portal in possible_portals: start_area = portal.door.entrance.parent_region state = ExplorationState(dungeon=d_name) state.visit_region(start_area) state.add_all_doors_check_unattached(start_area, world, player) explore_state_not_inaccessible(state, world, player) if state.visited_at_all(world.get_region(d_boss, player)): reachable_portals.append(portal) if len(reachable_portals) == 0: reachable_portals = possible_portals unreachable = world.inaccessible_regions[player] filtered = [x for x in reachable_portals if x.door.entrance.connected_region.name not in unreachable] if 0 < len(filtered) < len(reachable_portals): reachable_portals = filtered chosen_one = random.choice(reachable_portals) if len(reachable_portals) > 1 else reachable_portals[0] if chosen_one != current_boss: chosen_one.change_boss_exit(current_boss.boss_exit_idx) current_boss.change_boss_exit(-1) def convert_to_sectors(region_names, world, player): region_list = convert_regions(region_names, world, player) sectors = [] while len(region_list) > 0: region = region_list.pop() new_sector = True region_chunk = [region] exits = [] exits.extend(region.exits) outstanding_doors = [] matching_sectors = [] while len(exits) > 0: ext = exits.pop() door = ext.door if ext.connected_region is not None or door is not None and door.controller is not None: if door is not None and door.controller is not None: connect_region = world.get_entrance(door.controller.name, player).parent_region else: connect_region = ext.connected_region if connect_region not in region_chunk and connect_region in region_list: region_list.remove(connect_region) region_chunk.append(connect_region) exits.extend(connect_region.exits) if connect_region not in region_chunk: for existing in sectors: if connect_region in existing.regions: new_sector = False if existing not in matching_sectors: matching_sectors.append(existing) else: if door and not door.controller and not door.dest and not door.entranceFlag and door.type != DoorType.Logical: outstanding_doors.append(door) sector = Sector() if not new_sector: for match in matching_sectors: sector.regions.extend(match.regions) sector.outstanding_doors.extend(match.outstanding_doors) sectors.remove(match) sector.regions.extend(region_chunk) sector.outstanding_doors.extend(outstanding_doors) sectors.append(sector) return sectors def merge_sectors(all_sectors, world, player): if world.mixed_travel[player] == 'force': sectors_to_remove = {} merge_sectors = {} for sector in all_sectors: r_set = sector.region_set() if 'PoD Arena Ledge' in r_set: sectors_to_remove['Arenahover'] = sector elif 'PoD Big Chest Balcony' in r_set: sectors_to_remove['Hammerjump'] = sector elif 'Mire Chest View' in r_set: sectors_to_remove['Mire BJ'] = sector elif 'PoD Falling Bridge Ledge' in r_set: merge_sectors['Hammerjump'] = sector elif 'PoD Arena Bridge' in r_set: merge_sectors['Arenahover'] = sector elif 'Mire BK Chest Ledge' in r_set: merge_sectors['Mire BJ'] = sector for key, old_sector in sectors_to_remove.items(): merge_sectors[key].regions.extend(old_sector.regions) merge_sectors[key].outstanding_doors.extend(old_sector.outstanding_doors) all_sectors.remove(old_sector) # those with split region starts like Desert/Skull combine for key layouts def combine_layouts(recombinant_builders, dungeon_builders, entrances_map): for recombine in recombinant_builders.values(): queue = deque(dungeon_builders.values()) while len(queue) > 0: builder = queue.pop() if builder.name.startswith(recombine.name): del dungeon_builders[builder.name] if recombine.master_sector is None: recombine.master_sector = builder.master_sector recombine.master_sector.name = recombine.name else: recombine.master_sector.regions.extend(builder.master_sector.regions) recombine.layout_starts = list(entrances_map[recombine.name]) dungeon_builders[recombine.name] = recombine def valid_region_to_explore(region, world, player): return region and (region.type == RegionType.Dungeon or region.name in world.inaccessible_regions[player] or (region.name == 'Hyrule Castle Ledge' and world.mode[player] == 'standard')) def shuffle_key_doors(builder, world, player): start_regions = convert_regions(builder.path_entrances, world, player) # count number of key doors - this could be a table? num_key_doors = 0 skips = [] for region in builder.master_sector.regions: for ext in region.exits: d = world.check_for_door(ext.name, player) if d is not None and d.smallKey: if d not in skips: if d.type == DoorType.Interior: skips.append(d.dest) if d.type == DoorType.Normal: for dp in world.paired_doors[player]: if d.name == dp.door_a: skips.append(world.get_door(dp.door_b, player)) break elif d.name == dp.door_b: skips.append(world.get_door(dp.door_a, player)) break num_key_doors += 1 builder.key_doors_num = builder.total_keys = num_key_doors find_small_key_door_candidates(builder, start_regions, world, player) find_valid_combination(builder, start_regions, world, player) reassign_key_doors(builder, world, player) log_key_logic(builder.name, world.key_logic[player][builder.name]) def find_current_key_doors(builder): current_doors = [] for region in builder.master_sector.regions: for ext in region.exits: d = ext.door if d and d.smallKey: current_doors.append(d) return current_doors def find_small_key_door_candidates(builder, start_regions, world, player): # traverse dungeon and find candidates candidates = [] checked_doors = set() for region in start_regions: possible, checked = find_key_door_candidates(region, checked_doors, world, player) candidates.extend([x for x in possible if x not in candidates]) checked_doors.update(checked) flat_candidates = [] for candidate in candidates: # not valid if: Normal and Pair in is Checked and Pair is not in Candidates if candidate.type != DoorType.Normal or candidate.dest not in checked_doors or candidate.dest in candidates: flat_candidates.append(candidate) paired_candidates = build_pair_list(flat_candidates) builder.candidates = paired_candidates def calc_used_dungeon_items(builder): base = 4 if builder.bk_required and not builder.bk_provided: base += 1 # if builder.name == 'Hyrule Castle': # base -= 1 # Missing compass/map # if builder.name == 'Agahnims Tower': # base -= 2 # Missing both compass/map # gt can lose map once compasses work return base def find_valid_combination(builder, start_regions, world, player, drop_keys=True): logger = logging.getLogger('') # find valid combination of candidates if len(builder.candidates) < builder.key_doors_num: if not drop_keys: logger.info('No valid layouts for %s with %s doors', builder.name, builder.key_doors_num) return False builder.key_doors_num = len(builder.candidates) # reduce number of key doors logger.info('%s: %s', world.fish.translate("cli","cli","lowering.keys.candidates"), builder.name) combinations = ncr(len(builder.candidates), builder.key_doors_num) itr = 0 start = time.process_time() sample_list = list(range(0, int(combinations))) random.shuffle(sample_list) proposal = kth_combination(sample_list[itr], builder.candidates, builder.key_doors_num) # eliminate start region if portal marked as destination excluded = {} for region in start_regions: portal = next((x for x in world.dungeon_portals[player] if x.door.entrance.parent_region == region), None) if portal and portal.destination: excluded[region] = None start_regions = [x for x in start_regions if x not in excluded.keys()] key_layout = build_key_layout(builder, start_regions, proposal, world, player) determine_prize_lock(key_layout, world, player) while not validate_key_layout(key_layout, world, player): itr += 1 stop_early = False if itr % 1000 == 0: mark = time.process_time()-start if (mark > 10 and itr*100/combinations > 50) or (mark > 20 and itr*100/combinations > 25) or mark > 30: stop_early = True if itr >= combinations or stop_early: if not drop_keys: logger.info('No valid layouts for %s with %s doors', builder.name, builder.key_doors_num) return False logger.info('%s: %s', world.fish.translate("cli","cli","lowering.keys.layouts"), builder.name) builder.key_doors_num -= 1 if builder.key_doors_num < 0: raise Exception('Bad dungeon %s - 0 key doors not valid' % builder.name) combinations = ncr(len(builder.candidates), builder.key_doors_num) sample_list = list(range(0, int(combinations))) random.shuffle(sample_list) itr = 0 start = time.process_time() # reset time since itr reset proposal = kth_combination(sample_list[itr], builder.candidates, builder.key_doors_num) key_layout.reset(proposal, builder, world, player) if (itr+1) % 1000 == 0: mark = time.process_time()-start logger.info('%s time elapsed. %s iterations/s', mark, itr/mark) # make changes if player not in world.key_logic.keys(): world.key_logic[player] = {} analyze_dungeon(key_layout, world, player) builder.key_door_proposal = proposal world.key_logic[player][builder.name] = key_layout.key_logic world.key_layout[player][builder.name] = key_layout return True def log_key_logic(d_name, key_logic): logger = logging.getLogger('') if logger.isEnabledFor(logging.DEBUG): logger.debug('Key Logic for %s', d_name) if len(key_logic.bk_restricted) > 0: logger.debug('-BK Restrictions') for restriction in key_logic.bk_restricted: logger.debug(restriction) if len(key_logic.sm_restricted) > 0: logger.debug('-Small Restrictions') for restriction in key_logic.sm_restricted: logger.debug(restriction) for key in key_logic.door_rules.keys(): rule = key_logic.door_rules[key] logger.debug('--Rule for %s: Nrm:%s Allow:%s Loc:%s Alt:%s', key, rule.small_key_num, rule.allow_small, rule.small_location, rule.alternate_small_key) if rule.alternate_small_key is not None: for loc in rule.alternate_big_key_loc: logger.debug('---BK Loc %s', loc.name) logger.debug('Placement rules for %s', d_name) for rule in key_logic.placement_rules: logger.debug('*Rule for %s:', rule.door_reference) if rule.bk_conditional_set: logger.debug('**BK Checks %s', ','.join([x.name for x in rule.bk_conditional_set])) logger.debug('**BK Blocked (%s) : %s', rule.needed_keys_wo_bk, ','.join([x.name for x in rule.check_locations_wo_bk])) if rule.needed_keys_w_bk: logger.debug('**BK Available (%s) : %s', rule.needed_keys_w_bk, ','.join([x.name for x in rule.check_locations_w_bk])) def build_pair_list(flat_list): paired_list = [] queue = deque(flat_list) while len(queue) > 0: d = queue.pop() if d.dest in queue and d.type != DoorType.SpiralStairs: paired_list.append((d, d.dest)) queue.remove(d.dest) else: paired_list.append(d) return paired_list def flatten_pair_list(paired_list): flat_list = [] for d in paired_list: if type(d) is tuple: flat_list.append(d[0]) flat_list.append(d[1]) else: flat_list.append(d) return flat_list okay_normals = [DoorKind.Normal, DoorKind.SmallKey, DoorKind.Bombable, DoorKind.Dashable, DoorKind.DungeonChanger] def find_key_door_candidates(region, checked, world, player): dungeon = region.dungeon candidates = [] checked_doors = list(checked) queue = deque([(region, None, None)]) while len(queue) > 0: current, last_door, last_region = queue.pop() for ext in current.exits: d = ext.door if d and d.controller: d = d.controller if d and not d.blocked and not d.entranceFlag and d.dest is not last_door and d.dest is not last_region and d not in checked_doors: valid = False if 0 <= d.doorListPos < 4 and d.type in [DoorType.Interior, DoorType.Normal, DoorType.SpiralStairs]: room = world.get_room(d.roomIndex, player) position, kind = room.doorList[d.doorListPos] if d.type == DoorType.Interior: valid = kind in [DoorKind.Normal, DoorKind.SmallKey, DoorKind.Bombable, DoorKind.Dashable] elif d.type == DoorType.SpiralStairs: valid = kind in [DoorKind.StairKey, DoorKind.StairKey2, DoorKind.StairKeyLow] elif d.type == DoorType.Normal: d2 = d.dest if d2 not in candidates: if d2.type == DoorType.Normal: room_b = world.get_room(d2.roomIndex, player) pos_b, kind_b = room_b.doorList[d2.doorListPos] valid = kind in okay_normals and kind_b in okay_normals and valid_key_door_pair(d, d2) else: valid = kind in okay_normals if valid and 0 <= d2.doorListPos < 4: candidates.append(d2) else: valid = True if valid and d not in candidates: candidates.append(d) connected = ext.connected_region if connected and (connected.type != RegionType.Dungeon or connected.dungeon == dungeon): queue.append((ext.connected_region, d, current)) if d is not None: checked_doors.append(d) return candidates, checked_doors def valid_key_door_pair(door1, door2): if door1.roomIndex != door2.roomIndex: return True return len(door1.entrance.parent_region.exits) <= 1 or len(door2.entrance.parent_region.exits) <= 1 def reassign_key_doors(builder, world, player): logger = logging.getLogger('') logger.debug('Key doors for %s', builder.name) proposal = builder.key_door_proposal flat_proposal = flatten_pair_list(proposal) queue = deque(find_current_key_doors(builder)) while len(queue) > 0: d = queue.pop() if d.type is DoorType.SpiralStairs and d not in proposal: room = world.get_room(d.roomIndex, player) if room.doorList[d.doorListPos][1] == DoorKind.StairKeyLow: room.delete(d.doorListPos) else: if len(room.doorList) > 1: room.mirror(d.doorListPos) # I think this works for crossed now else: room.delete(d.doorListPos) d.smallKey = False elif d.type is DoorType.Interior and d not in flat_proposal and d.dest not in flat_proposal: if not d.entranceFlag: world.get_room(d.roomIndex, player).change(d.doorListPos, DoorKind.Normal) d.smallKey = False d.dest.smallKey = False queue.remove(d.dest) elif d.type is DoorType.Normal and d not in flat_proposal: if not d.entranceFlag: world.get_room(d.roomIndex, player).change(d.doorListPos, DoorKind.Normal) d.smallKey = False for dp in world.paired_doors[player]: if dp.door_a == d.name or dp.door_b == d.name: dp.pair = False for obj in proposal: if type(obj) is tuple: d1 = obj[0] d2 = obj[1] if d1.type is DoorType.Interior: change_door_to_small_key(d1, world, player) d2.smallKey = True # ensure flag is set else: names = [d1.name, d2.name] found = False for dp in world.paired_doors[player]: if dp.door_a in names and dp.door_b in names: dp.pair = True found = True elif dp.door_a in names: dp.pair = False elif dp.door_b in names: dp.pair = False if not found: world.paired_doors[player].append(PairedDoor(d1.name, d2.name)) change_door_to_small_key(d1, world, player) change_door_to_small_key(d2, world, player) world.spoiler.set_door_type(d1.name+' <-> '+d2.name, 'Key Door', player) logger.debug('Key Door: %s', d1.name+' <-> '+d2.name) else: d = obj if d.type is DoorType.Interior: change_door_to_small_key(d, world, player) d.dest.smallKey = True # ensure flag is set elif d.type is DoorType.SpiralStairs: pass # we don't have spiral stairs candidates yet that aren't already key doors elif d.type is DoorType.Normal: change_door_to_small_key(d, world, player) world.spoiler.set_door_type(d.name, 'Key Door', player) logger.debug('Key Door: %s', d.name) def change_door_to_small_key(d, world, player): d.smallKey = True room = world.get_room(d.roomIndex, player) if room.doorList[d.doorListPos][1] != DoorKind.SmallKey: room.change(d.doorListPos, DoorKind.SmallKey) def smooth_door_pairs(world, player): all_doors = [x for x in world.doors if x.player == player] skip = set() bd_candidates = defaultdict(list) for door in all_doors: if door.type in [DoorType.Normal, DoorType.Interior] and door not in skip and not door.entranceFlag: partner = door.dest skip.add(partner) room_a = world.get_room(door.roomIndex, player) type_a = room_a.kind(door) if partner.type in [DoorType.Normal, DoorType.Interior]: room_b = world.get_room(partner.roomIndex, player) type_b = room_b.kind(partner) valid_pair = stateful_door(door, type_a) and stateful_door(partner, type_b) else: valid_pair, room_b, type_b = False, None, None if door.type == DoorType.Normal: if type_a == DoorKind.SmallKey or type_b == DoorKind.SmallKey: if valid_pair: if type_a != DoorKind.SmallKey: room_a.change(door.doorListPos, DoorKind.SmallKey) if type_b != DoorKind.SmallKey: room_b.change(partner.doorListPos, DoorKind.SmallKey) add_pair(door, partner, world, player) else: if type_a == DoorKind.SmallKey: remove_pair(door, world, player) if type_b == DoorKind.SmallKey: remove_pair(door, world, player) else: if valid_pair: bd_candidates[door.entrance.parent_region.dungeon].append(door) elif type_a in [DoorKind.Bombable, DoorKind.Dashable] or type_b in [DoorKind.Bombable, DoorKind.Dashable]: if type_a in [DoorKind.Bombable, DoorKind.Dashable]: room_a.change(door.doorListPos, DoorKind.Normal) remove_pair(door, world, player) else: room_b.change(partner.doorListPos, DoorKind.Normal) remove_pair(partner, world, player) elif valid_pair and type_a != DoorKind.SmallKey and type_b != DoorKind.SmallKey: bd_candidates[door.entrance.parent_region.dungeon].append(door) shuffle_bombable_dashable(bd_candidates, world, player) world.paired_doors[player] = [x for x in world.paired_doors[player] if x.pair or x.original] def add_pair(door_a, door_b, world, player): pair_a, pair_b = None, None for paired_door in world.paired_doors[player]: if paired_door.door_a == door_a.name and paired_door.door_b == door_b.name: paired_door.pair = True return if paired_door.door_a == door_b.name and paired_door.door_b == door_a.name: paired_door.pair = True return if paired_door.door_a == door_a.name or paired_door.door_b == door_a.name: pair_a = paired_door if paired_door.door_a == door_b.name or paired_door.door_b == door_b.name: pair_b = paired_door if pair_a: pair_a.pair = False if pair_b: pair_b.pair = False world.paired_doors[player].append(PairedDoor(door_a, door_b)) def remove_pair(door, world, player): for paired_door in world.paired_doors[player]: if paired_door.door_a == door.name or paired_door.door_b == door.name: paired_door.pair = False break def stateful_door(door, kind): if 0 <= door.doorListPos < 4: return kind in [DoorKind.Normal, DoorKind.SmallKey, DoorKind.Bombable, DoorKind.Dashable] #, DoorKind.BigKey] return False def shuffle_bombable_dashable(bd_candidates, world, player): if world.doorShuffle[player] == 'basic': for dungeon, candidates in bd_candidates.items(): diff = bomb_dash_counts[dungeon.name][1] if diff > 0: for chosen in random.sample(candidates, min(diff, len(candidates))): change_pair_type(chosen, DoorKind.Dashable, world, player) candidates.remove(chosen) diff = bomb_dash_counts[dungeon.name][0] if diff > 0: for chosen in random.sample(candidates, min(diff, len(candidates))): change_pair_type(chosen, DoorKind.Bombable, world, player) candidates.remove(chosen) for excluded in candidates: remove_pair_type_if_present(excluded, world, player) elif world.doorShuffle[player] == 'crossed': all_candidates = sum(bd_candidates.values(), []) for chosen in random.sample(all_candidates, min(8, len(all_candidates))): change_pair_type(chosen, DoorKind.Dashable, world, player) all_candidates.remove(chosen) for chosen in random.sample(all_candidates, min(12, len(all_candidates))): change_pair_type(chosen, DoorKind.Bombable, world, player) all_candidates.remove(chosen) for excluded in all_candidates: remove_pair_type_if_present(excluded, world, player) def change_pair_type(door, new_type, world, player): room_a = world.get_room(door.roomIndex, player) room_a.change(door.doorListPos, new_type) if door.type != DoorType.Interior: room_b = world.get_room(door.dest.roomIndex, player) room_b.change(door.dest.doorListPos, new_type) add_pair(door, door.dest, world, player) spoiler_type = 'Bomb Door' if new_type == DoorKind.Bombable else 'Dash Door' world.spoiler.set_door_type(door.name + ' <-> ' + door.dest.name, spoiler_type, player) def remove_pair_type_if_present(door, world, player): room_a = world.get_room(door.roomIndex, player) if room_a.kind(door) in [DoorKind.Bombable, DoorKind.Dashable]: room_a.change(door.doorListPos, DoorKind.Normal) if door.type != DoorType.Interior: remove_pair(door, world, player) if door.type != DoorType.Interior: room_b = world.get_room(door.dest.roomIndex, player) if room_b.kind(door.dest) in [DoorKind.Bombable, DoorKind.Dashable]: room_b.change(door.dest.doorListPos, DoorKind.Normal) remove_pair(door.dest, world, player) def find_inaccessible_regions(world, player): world.inaccessible_regions[player] = [] if world.mode[player] != 'inverted': start_regions = ['Links House', 'Sanctuary'] else: start_regions = ['Links House', 'Dark Sanctuary Hint'] regs = convert_regions(start_regions, world, player) all_regions = [r for r in world.regions if r.player == player and r.type is not RegionType.Dungeon] visited_regions = set() queue = deque(regs) while len(queue) > 0: next_region = queue.popleft() visited_regions.add(next_region) if next_region.name == 'Dark Sanctuary Hint': # special spawn point in cave for ent in next_region.entrances: parent = ent.parent_region if parent and parent.type is not RegionType.Dungeon and parent not in queue and parent not in visited_regions: queue.append(parent) for ext in next_region.exits: connect = ext.connected_region if connect and connect not in queue and connect not in visited_regions: if connect.type is not RegionType.Dungeon or connect.name.endswith(' Portal'): queue.append(connect) world.inaccessible_regions[player].extend([r.name for r in all_regions if r not in visited_regions and valid_inaccessible_region(r)]) if (world.mode[player] == 'inverted') != (0x1b in world.owswaps[player][0] and world.owMixed[player]): ledge = world.get_region('Hyrule Castle Ledge', player) if any(x for x in ledge.exits if x.connected_region and x.connected_region.name == 'Agahnims Tower Portal'): world.inaccessible_regions[player].append('Hyrule Castle Ledge') logger = logging.getLogger('') logger.debug('Inaccessible Regions:') for r in world.inaccessible_regions[player]: logger.debug('%s', r) def find_accessible_entrances(world, player, builder): entrances = [region.name for region in (portal.door.entrance.parent_region for portal in world.dungeon_portals[player]) if region.dungeon.name == builder.name] entrances.extend(drop_entrances[builder.name]) if world.mode[player] == 'standard' and builder.name == 'Hyrule Castle': start_regions = ['Hyrule Castle Courtyard'] elif world.mode[player] != 'inverted': start_regions = ['Links House', 'Sanctuary'] else: start_regions = ['Links House', 'Dark Sanctuary Hint'] if (world.mode[player] == 'inverted') != (0x1b in world.owswaps[player][0] and world.owMixed[player]): start_regions.append('Hyrule Castle Ledge') regs = convert_regions(start_regions, world, player) visited_regions = set() visited_entrances = [] # Add Sanctuary as an additional entrance in open mode, since you can save and quit to there if world.mode[player] == 'open' and world.get_region('Sanctuary', player).dungeon.name == builder.name and 'Sanctuary' not in entrances: entrances.append('Sanctuary') visited_entrances.append('Sanctuary') regs.remove(world.get_region('Sanctuary', player)) queue = deque(regs) while len(queue) > 0: next_region = queue.popleft() visited_regions.add(next_region) if (world.mode[player] == 'inverted') != (0x1b in world.owswaps[player][0] and world.owMixed[player]) and next_region.name == 'Tower Agahnim 1': connect = world.get_region('Hyrule Castle Ledge', player) if connect not in queue and connect not in visited_regions: queue.append(connect) for ext in next_region.exits: connect = ext.connected_region if connect is None or ext.door and ext.door.blocked: continue if world.mode[player] == 'standard' and builder.name == 'Hyrule Castle' and (ext.name.startswith('Flute From') or ext.name in ['Hyrule Castle Main Gate (North)', 'Top of Pyramid (Inner)', 'Inverted Pyramid Entrance']): continue if connect.name in entrances and connect not in visited_entrances: visited_entrances.append(connect.name) elif connect and connect not in queue and connect not in visited_regions: queue.append(connect) return visited_entrances def valid_inaccessible_region(r): return r.type is not RegionType.Cave or (len(r.exits) > 0 and r.name not in ['Links House', 'Chris Houlihan Room']) def add_inaccessible_doors(world, player): if world.mode[player] == 'standard': create_doors_for_inaccessible_region('Hyrule Castle Ledge', world, player) # todo: ignore standard mode hyrule castle ledge? for inaccessible_region in world.inaccessible_regions[player]: create_doors_for_inaccessible_region(inaccessible_region, world, player) def create_doors_for_inaccessible_region(inaccessible_region, world, player): region = world.get_region(inaccessible_region, player) for ext in region.exits: create_door(world, player, ext.name, region.name) if ext.connected_region is None: logging.getLogger('').warning('Exit not connected to any region: %s', ext.name) elif ext.connected_region.name.endswith(' Portal'): for more_exts in ext.connected_region.exits: create_door(world, player, more_exts.name, ext.connected_region.name) def create_door(world, player, entName, region_name): entrance = world.get_entrance(entName, player) connect = entrance.connected_region if connect is not None: for ext in connect.exits: if ext.connected_region is not None and ext.connected_region.name == region_name: d = Door(player, ext.name, DoorType.Logical, ext), world.doors += d connect_door_only(world, ext.name, ext.connected_region, player) d = Door(player, entName, DoorType.Logical, entrance), world.doors += d connect_door_only(world, entName, connect, player) def check_required_paths(paths, world, player): for dungeon_name in paths.keys(): if dungeon_name in world.dungeon_layouts[player].keys(): builder = world.dungeon_layouts[player][dungeon_name] if len(paths[dungeon_name]) > 0: states_to_explore = {} for path in paths[dungeon_name]: if type(path) is tuple: states_to_explore[tuple([path[0]])] = (path[1], 'any') else: common_starts = tuple(builder.path_entrances) if common_starts not in states_to_explore: states_to_explore[common_starts] = ([], 'all') states_to_explore[common_starts][0].append(path) cached_initial_state = None for start_regs, info in states_to_explore.items(): dest_regs, path_type = info if type(dest_regs) is not list: dest_regs = [dest_regs] check_paths = convert_regions(dest_regs, world, player) start_regions = convert_regions(start_regs, world, player) initial = start_regs == tuple(builder.path_entrances) if not initial or cached_initial_state is None: init = determine_init_crystal(initial, cached_initial_state, start_regions) state = ExplorationState(init, dungeon_name) for region in start_regions: state.visit_region(region) state.add_all_doors_check_unattached(region, world, player) explore_state(state, world, player) if initial and cached_initial_state is None: cached_initial_state = state else: state = cached_initial_state if path_type == 'any': valid, bad_region = check_if_any_regions_visited(state, check_paths) else: valid, bad_region = check_if_all_regions_visited(state, check_paths) if not valid: if check_for_pinball_fix(state, bad_region, world, player): explore_state(state, world, player) if path_type == 'any': valid, bad_region = check_if_any_regions_visited(state, check_paths) else: valid, bad_region = check_if_all_regions_visited(state, check_paths) if not valid: raise Exception('%s cannot reach %s' % (dungeon_name, bad_region.name)) def determine_init_crystal(initial, state, start_regions): if initial or state is None: return CrystalBarrier.Orange if len(start_regions) > 1: raise NotImplementedError('Path checking for multiple start regions (not the entrances) not implemented, use more paths instead') start_region = start_regions[0] if start_region in state.visited_blue and start_region in state.visited_orange: return CrystalBarrier.Either elif start_region in state.visited_blue: return CrystalBarrier.Blue elif start_region in state.visited_orange: return CrystalBarrier.Orange else: raise Exception(f'Can\'t get to {start_region.name} from initial state') # raise Exception(f'Can\'t get to {start_region.name} from initial state\n{state.dungeon}\n{state.found_locations}') def explore_state(state, world, player): while len(state.avail_doors) > 0: door = state.next_avail_door().door connect_region = world.get_entrance(door.name, player).connected_region if state.can_traverse(door) and not state.visited(connect_region) and valid_region_to_explore(connect_region, world, player): state.visit_region(connect_region) state.add_all_doors_check_unattached(connect_region, world, player) def explore_state_not_inaccessible(state, world, player): while len(state.avail_doors) > 0: door = state.next_avail_door().door connect_region = world.get_entrance(door.name, player).connected_region if state.can_traverse(door) and not state.visited(connect_region) and connect_region.type == RegionType.Dungeon: state.visit_region(connect_region) state.add_all_doors_check_unattached(connect_region, world, player) def check_if_any_regions_visited(state, check_paths): valid = False breaking_region = None for region_target in check_paths: if state.visited_at_all(region_target): valid = True break elif not breaking_region: breaking_region = region_target return valid, breaking_region def check_if_all_regions_visited(state, check_paths): for region_target in check_paths: if not state.visited_at_all(region_target): return False, region_target return True, None def check_for_pinball_fix(state, bad_region, world, player): pinball_region = world.get_region('Skull Pinball', player) # todo: lobby shuffle if bad_region.name == 'Skull 2 West Lobby' and state.visited_at_all(pinball_region): # revisit this for entrance shuffle door = world.get_door('Skull Pinball WS', player) room = world.get_room(door.roomIndex, player) if room.doorList[door.doorListPos][1] == DoorKind.Trap: room.change(door.doorListPos, DoorKind.Normal) door.trapFlag = 0x0 door.blocked = False connect_two_way(world, door.name, door.dest.name, player) state.add_all_doors_check_unattached(pinball_region, world, player) return True return False @unique class DROptions(Flag): NoOptions = 0x00 Eternal_Mini_Bosses = 0x01 # If on, GT minibosses marked as defeated when they try to spawn a heart Town_Portal = 0x02 # If on, Players will start with mirror scroll Map_Info = 0x04 Debug = 0x08 Fix_EG = 0x10 # used to be Rails = 0x10 # Unused bit now OriginalPalettes = 0x20 # Open_PoD_Wall = 0x40 # No longer pre-opening pod wall - unused # Open_Desert_Wall = 0x80 # No longer pre-opening desert wall - unused Hide_Total = 0x100 DarkWorld_Spawns = 0x200 # DATA GOES DOWN HERE logical_connections = [ ('Hyrule Dungeon North Abyss Catwalk Dropdown', 'Hyrule Dungeon North Abyss'), ('Hyrule Dungeon Cellblock Door', 'Hyrule Dungeon Cell'), ('Hyrule Dungeon Cell Exit', 'Hyrule Dungeon Cellblock'), ('Hyrule Castle Throne Room Tapestry', 'Hyrule Castle Behind Tapestry'), ('Hyrule Castle Tapestry Backwards', 'Hyrule Castle Throne Room'), ('Sewers Secret Room Push Block', 'Sewers Secret Room Blocked Path'), ('Eastern Hint Tile Push Block', 'Eastern Hint Tile'), ('Eastern Map Balcony Hook Path', 'Eastern Map Room'), ('Eastern Map Room Drop Down', 'Eastern Map Balcony'), ('Desert Main Lobby Left Path', 'Desert Left Alcove'), ('Desert Main Lobby Right Path', 'Desert Right Alcove'), ('Desert Left Alcove Path', 'Desert Main Lobby'), ('Desert Right Alcove Path', 'Desert Main Lobby'), ('Hera Lobby to Front Barrier - Blue', 'Hera Front'), ('Hera Front to Lobby Barrier - Blue', 'Hera Lobby'), ('Hera Lobby to Crystal', 'Hera Lobby - Crystal'), ('Hera Lobby Crystal Exit', 'Hera Lobby'), ('Hera Front to Crystal', 'Hera Front - Crystal'), ('Hera Front to Back Bypass', 'Hera Back'), ('Hera Front Crystal Exit', 'Hera Front'), ('Hera Front to Down Stairs Barrier - Blue', 'Hera Down Stairs Landing'), ('Hera Front to Up Stairs Barrier - Orange', 'Hera Up Stairs Landing'), ('Hera Front to Back Barrier - Orange', 'Hera Back'), ('Hera Down Stairs to Front Barrier - Blue', 'Hera Front'), ('Hera Down Stairs Landing to Ranged Crystal', 'Hera Down Stairs Landing - Ranged Crystal'), ('Hera Down Stairs Landing Ranged Crystal Exit', 'Hera Down Stairs Landing'), ('Hera Up Stairs to Front Barrier - Orange', 'Hera Front'), ('Hera Up Stairs Landing to Ranged Crystal', 'Hera Up Stairs Landing - Ranged Crystal'), ('Hera Up Stairs Landing Ranged Crystal Exit', 'Hera Up Stairs Landing'), ('Hera Back to Front Barrier - Orange', 'Hera Front'), ('Hera Back to Ranged Crystal', 'Hera Back - Ranged Crystal'), ('Hera Back Ranged Crystal Exit', 'Hera Back'), ('Hera Basement Cage to Crystal', 'Hera Basement Cage - Crystal'), ('Hera Basement Cage Crystal Exit', 'Hera Basement Cage'), ('Hera Tridorm to Crystal', 'Hera Tridorm - Crystal'), ('Hera Tridorm Crystal Exit', 'Hera Tridorm'), ('Hera Startile Wide to Crystal', 'Hera Startile Wide - Crystal'), ('Hera Startile Wide Crystal Exit', 'Hera Startile Wide'), ('Hera Big Chest Hook Path', 'Hera Big Chest Landing'), ('Hera Big Chest Landing Exit', 'Hera 4F'), ('PoD Pit Room Block Path N', 'PoD Pit Room Blocked'), ('PoD Pit Room Block Path S', 'PoD Pit Room'), ('PoD Arena Landing Bonk Path', 'PoD Arena Bridge'), ('PoD Arena North Drop Down', 'PoD Arena Main'), ('PoD Arena Bridge Drop Down', 'PoD Arena Main'), ('PoD Arena North to Landing Barrier - Orange', 'PoD Arena Landing'), ('PoD Arena Main to Ranged Crystal', 'PoD Arena Main - Ranged Crystal'), ('PoD Arena Main to Landing Barrier - Blue', 'PoD Arena Landing'), ('PoD Arena Main to Landing Bypass', 'PoD Arena Landing'), ('PoD Arena Main to Right Bypass', 'PoD Arena Right'), ('PoD Arena Main Ranged Crystal Exit', 'PoD Arena Main'), ('PoD Arena Bridge to Ranged Crystal', 'PoD Arena Bridge - Ranged Crystal'), ('PoD Arena Bridge Ranged Crystal Exit', 'PoD Arena Bridge'), ('PoD Arena Landing to Main Barrier - Blue', 'PoD Arena Main'), ('PoD Arena Landing to Right Barrier - Blue', 'PoD Arena Right'), ('PoD Arena Landing to North Barrier - Orange', 'PoD Arena North'), ('PoD Arena Right to Landing Barrier - Blue', 'PoD Arena Landing'), ('PoD Arena Right to Ranged Crystal', 'PoD Arena Right - Ranged Crystal'), ('PoD Arena Right Ranged Crystal Exit', 'PoD Arena Right'), ('PoD Arena Ledge to Ranged Crystal', 'PoD Arena Ledge - Ranged Crystal'), ('PoD Arena Ledge Ranged Crystal Exit', 'PoD Arena Ledge'), ('PoD Map Balcony Drop Down', 'PoD Sexy Statue'), ('PoD Map Balcony to Ranged Crystal', 'PoD Map Balcony - Ranged Crystal'), ('PoD Map Balcony Ranged Crystal Exit', 'PoD Map Balcony'), ('PoD Basement Ledge Drop Down', 'PoD Stalfos Basement'), ('PoD Falling Bridge Path N', 'PoD Falling Bridge Ledge'), ('PoD Falling Bridge Path S', 'PoD Falling Bridge'), ('PoD Bow Statue Left to Right Barrier - Orange', 'PoD Bow Statue Right'), ('PoD Bow Statue Left to Right Bypass', 'PoD Bow Statue Right'), ('PoD Bow Statue Left to Crystal', 'PoD Bow Statue Left - Crystal'), ('PoD Bow Statue Left Crystal Exit', 'PoD Bow Statue Left'), ('PoD Bow Statue Right to Left Barrier - Orange', 'PoD Bow Statue Left'), ('PoD Bow Statue Right to Ranged Crystal', 'PoD Bow Statue Right - Ranged Crystal'), ('PoD Bow Statue Ranged Crystal Exit', 'PoD Bow Statue Right'), ('PoD Dark Pegs Landing to Right', 'PoD Dark Pegs Right'), ('PoD Dark Pegs Landing to Ranged Crystal', 'PoD Dark Pegs Landing - Ranged Crystal'), ('PoD Dark Pegs Right to Landing', 'PoD Dark Pegs Landing'), ('PoD Dark Pegs Right to Middle Barrier - Orange', 'PoD Dark Pegs Middle'), ('PoD Dark Pegs Right to Middle Bypass', 'PoD Dark Pegs Middle'), ('PoD Dark Pegs Middle to Right Barrier - Orange', 'PoD Dark Pegs Right'), ('PoD Dark Pegs Middle to Left Barrier - Blue', 'PoD Dark Pegs Left'), ('PoD Dark Pegs Middle to Ranged Crystal', 'PoD Dark Pegs Middle - Ranged Crystal'), ('PoD Dark Pegs Left to Middle Barrier - Blue', 'PoD Dark Pegs Middle'), ('PoD Dark Pegs Left to Ranged Crystal', 'PoD Dark Pegs Left - Ranged Crystal'), ('PoD Dark Pegs Landing Ranged Crystal Exit', 'PoD Dark Pegs Landing'), ('PoD Dark Pegs Middle Ranged Crystal Exit', 'PoD Dark Pegs Middle'), ('PoD Dark Pegs Middle to Left Bypass', 'PoD Dark Pegs Left'), ('PoD Dark Pegs Left Ranged Crystal Exit', 'PoD Dark Pegs Left'), ('Swamp Lobby Moat', 'Swamp Entrance'), ('Swamp Entrance Moat', 'Swamp Lobby'), ('Swamp Trench 1 Approach Dry', 'Swamp Trench 1 Nexus'), ('Swamp Trench 1 Approach Key', 'Swamp Trench 1 Key Ledge'), ('Swamp Trench 1 Approach Swim Depart', 'Swamp Trench 1 Departure'), ('Swamp Trench 1 Nexus Approach', 'Swamp Trench 1 Approach'), ('Swamp Trench 1 Nexus Key', 'Swamp Trench 1 Key Ledge'), ('Swamp Trench 1 Key Ledge Dry', 'Swamp Trench 1 Nexus'), ('Swamp Trench 1 Key Approach', 'Swamp Trench 1 Approach'), ('Swamp Trench 1 Key Ledge Depart', 'Swamp Trench 1 Departure'), ('Swamp Trench 1 Departure Dry', 'Swamp Trench 1 Nexus'), ('Swamp Trench 1 Departure Approach', 'Swamp Trench 1 Approach'), ('Swamp Trench 1 Departure Key', 'Swamp Trench 1 Key Ledge'), ('Swamp Hub Hook Path', 'Swamp Hub North Ledge'), ('Swamp Hub North Ledge Drop Down', 'Swamp Hub'), ('Swamp Crystal Switch Outer to Inner Barrier - Blue', 'Swamp Crystal Switch Inner'), ('Swamp Crystal Switch Outer to Ranged Crystal', 'Swamp Crystal Switch Outer - Ranged Crystal'), ('Swamp Crystal Switch Outer to Inner Bypass', 'Swamp Crystal Switch Inner'), ('Swamp Crystal Switch Outer Ranged Crystal Exit', 'Swamp Crystal Switch Outer'), ('Swamp Crystal Switch Inner to Outer Barrier - Blue', 'Swamp Crystal Switch Outer'), ('Swamp Crystal Switch Inner to Outer Bypass', 'Swamp Crystal Switch Outer'), ('Swamp Crystal Switch Inner to Crystal', 'Swamp Crystal Switch Inner - Crystal'), ('Swamp Crystal Switch Inner Crystal Exit', 'Swamp Crystal Switch Inner'), ('Swamp Compass Donut Push Block', 'Swamp Donut Top'), ('Swamp Shortcut Blue Barrier', 'Swamp Trench 2 Pots'), ('Swamp Trench 2 Pots Blue Barrier', 'Swamp Shortcut'), ('Swamp Trench 2 Pots Dry', 'Swamp Trench 2 Blocks'), ('Swamp Trench 2 Pots Wet', 'Swamp Trench 2 Departure'), ('Swamp Trench 2 Blocks Pots', 'Swamp Trench 2 Pots'), ('Swamp Trench 2 Departure Wet', 'Swamp Trench 2 Pots'), ('Swamp West Shallows Push Blocks', 'Swamp West Block Path'), ('Swamp West Block Path Drop Down', 'Swamp West Shallows'), ('Swamp West Ledge Drop Down', 'Swamp West Shallows'), ('Swamp West Ledge Hook Path', 'Swamp Barrier Ledge'), ('Swamp Barrier Ledge Drop Down', 'Swamp West Shallows'), ('Swamp Barrier Ledge - Orange', 'Swamp Barrier'), ('Swamp Barrier - Orange', 'Swamp Barrier Ledge'), ('Swamp Barrier Ledge Hook Path', 'Swamp West Ledge'), ('Swamp Drain Right Switch', 'Swamp Drain Left'), ('Swamp Flooded Spot Ladder', 'Swamp Flooded Room'), ('Swamp Flooded Room Ladder', 'Swamp Flooded Spot'), ('Skull Pot Circle Star Path', 'Skull Map Room'), ('Skull Big Chest Hookpath', 'Skull 1 Lobby'), ('Skull Back Drop Star Path', 'Skull Small Hall'), ('Thieves Rail Ledge Drop Down', 'Thieves BK Corner'), ('Thieves Hellway Orange Barrier', 'Thieves Hellway S Crystal'), ('Thieves Hellway Crystal Orange Barrier', 'Thieves Hellway'), ('Thieves Hellway Blue Barrier', 'Thieves Hellway N Crystal'), ('Thieves Hellway Crystal Blue Barrier', 'Thieves Hellway'), ('Thieves Attic Orange Barrier', 'Thieves Attic Hint'), ('Thieves Attic Hint Orange Barrier', 'Thieves Attic'), ('Thieves Basement Block Path', 'Thieves Blocked Entry'), ('Thieves Blocked Entry Path', 'Thieves Basement Block'), ('Thieves Conveyor Bridge Block Path', 'Thieves Conveyor Block'), ('Thieves Conveyor Block Path', 'Thieves Conveyor Bridge'), ("Thieves Blind's Cell Door", "Thieves Blind's Cell Interior"), ("Thieves Blind's Cell Exit", "Thieves Blind's Cell"), ('Ice Cross Bottom Push Block Left', 'Ice Floor Switch'), ('Ice Cross Right Push Block Top', 'Ice Bomb Drop'), ('Ice Conveyor to Crystal', 'Ice Conveyor - Crystal'), ('Ice Conveyor Crystal Exit', 'Ice Conveyor'), ('Ice Big Key Push Block', 'Ice Dead End'), ('Ice Bomb Jump Ledge Orange Barrier', 'Ice Bomb Jump Catwalk'), ('Ice Bomb Jump Catwalk Orange Barrier', 'Ice Bomb Jump Ledge'), ('Ice Hookshot Ledge Path', 'Ice Hookshot Balcony'), ('Ice Hookshot Balcony Path', 'Ice Hookshot Ledge'), ('Ice Crystal Right Orange Barrier', 'Ice Crystal Left'), ('Ice Crystal Left Orange Barrier', 'Ice Crystal Right'), ('Ice Crystal Left Blue Barrier', 'Ice Crystal Block'), ('Ice Crystal Block Exit', 'Ice Crystal Left'), ('Ice Big Chest Landing Push Blocks', 'Ice Big Chest View'), ('Ice Refill to Crystal', 'Ice Refill - Crystal'), ('Ice Refill Crystal Exit', 'Ice Refill'), ('Mire Lobby Gap', 'Mire Post-Gap'), ('Mire Post-Gap Gap', 'Mire Lobby'), ('Mire Hub Upper Blue Barrier', 'Mire Hub Switch'), ('Mire Hub Lower Blue Barrier', 'Mire Hub Right'), ('Mire Hub Right Blue Barrier', 'Mire Hub'), ('Mire Hub Top Blue Barrier', 'Mire Hub Switch'), ('Mire Hub Switch Blue Barrier N', 'Mire Hub Top'), ('Mire Hub Switch Blue Barrier S', 'Mire Hub'), ('Mire Map Spike Side Drop Down', 'Mire Lone Shooter'), ('Mire Map Spike Side Blue Barrier', 'Mire Crystal Dead End'), ('Mire Map Spot Blue Barrier', 'Mire Crystal Dead End'), ('Mire Crystal Dead End Left Barrier', 'Mire Map Spot'), ('Mire Crystal Dead End Right Barrier', 'Mire Map Spike Side'), ('Mire Hidden Shooters Block Path S', 'Mire Hidden Shooters'), ('Mire Hidden Shooters Block Path N', 'Mire Hidden Shooters Blocked'), ('Mire Conveyor to Crystal', 'Mire Conveyor - Crystal'), ('Mire Conveyor Crystal Exit', 'Mire Conveyor Crystal'), ('Mire Left Bridge Hook Path', 'Mire Right Bridge'), ('Mire Tall Dark and Roomy to Ranged Crystal', 'Mire Tall Dark and Roomy - Ranged Crystal'), ('Mire Tall Dark and Roomy Ranged Crystal Exit', 'Mire Tall Dark and Roomy'), ('Mire Crystal Right Orange Barrier', 'Mire Crystal Mid'), ('Mire Crystal Mid Orange Barrier', 'Mire Crystal Right'), ('Mire Crystal Mid Blue Barrier', 'Mire Crystal Left'), ('Mire Crystal Left Blue Barrier', 'Mire Crystal Mid'), ('Mire Firesnake Skip Orange Barrier', 'Mire Antechamber'), ('Mire Antechamber Orange Barrier', 'Mire Firesnake Skip'), ('Mire Compass Blue Barrier', 'Mire Compass Chest'), ('Mire Compass Chest Exit', 'Mire Compass Room'), ('Mire South Fish Blue Barrier', 'Mire Fishbone'), ('Mire Fishbone Blue Barrier', 'Mire South Fish'), ('Mire Fishbone Blue Barrier Bypass', 'Mire South Fish'), ('TR Main Lobby Gap', 'TR Lobby Ledge'), ('TR Lobby Ledge Gap', 'TR Main Lobby'), ('TR Pipe Ledge Drop Down', 'TR Pipe Pit'), ('TR Big Chest Gap', 'TR Big Chest Entrance'), ('TR Big Chest Entrance Gap', 'TR Big Chest'), ('TR Chain Chomps Top to Bottom Barrier - Orange', 'TR Chain Chomps Bottom'), ('TR Chain Chomps Top to Crystal', 'TR Chain Chomps Top - Crystal'), ('TR Chain Chomps Top Crystal Exit', 'TR Chain Chomps Top'), ('TR Chain Chomps Bottom to Top Barrier - Orange', 'TR Chain Chomps Top'), ('TR Chain Chomps Bottom to Ranged Crystal', 'TR Chain Chomps Bottom - Ranged Crystal'), ('TR Chain Chomps Bottom Ranged Crystal Exit', 'TR Chain Chomps Bottom'), ('TR Pokey 2 Top to Bottom Barrier - Blue', 'TR Pokey 2 Bottom'), ('TR Pokey 2 Top to Crystal', 'TR Pokey 2 Top - Crystal'), ('TR Pokey 2 Top Crystal Exit', 'TR Pokey 2 Top'), ('TR Pokey 2 Bottom to Top Barrier - Blue', 'TR Pokey 2 Top'), ('TR Pokey 2 Bottom to Ranged Crystal', 'TR Pokey 2 Bottom - Ranged Crystal'), ('TR Pokey 2 Bottom Ranged Crystal Exit', 'TR Pokey 2 Bottom'), ('TR Crystaroller Bottom to Middle Barrier - Orange', 'TR Crystaroller Middle'), ('TR Crystaroller Bottom to Ranged Crystal', 'TR Crystaroller Bottom - Ranged Crystal'), ('TR Crystaroller Middle to Bottom Barrier - Orange', 'TR Crystaroller Bottom'), ('TR Crystaroller Middle to Bottom Bypass', 'TR Crystaroller Bottom'), ('TR Crystaroller Middle to Chest Barrier - Blue', 'TR Crystaroller Chest'), ('TR Crystaroller Middle to Top Barrier - Orange', 'TR Crystaroller Top'), ('TR Crystaroller Middle to Ranged Crystal', 'TR Crystaroller Middle - Ranged Crystal'), ('TR Crystaroller Top to Middle Barrier - Orange', 'TR Crystaroller Middle'), ('TR Crystaroller Top to Crystal', 'TR Crystaroller Top - Crystal'), ('TR Crystaroller Top Crystal Exit', 'TR Crystaroller Top'), ('TR Crystaroller Chest to Middle Barrier - Blue', 'TR Crystaroller Middle'), ('TR Crystaroller Middle Ranged Crystal Exit', 'TR Crystaroller Middle'), ('TR Crystaroller Bottom Ranged Crystal Exit', 'TR Crystaroller Bottom'), ('TR Crystal Maze Start to Interior Barrier - Blue', 'TR Crystal Maze Interior'), ('TR Crystal Maze Start to Crystal', 'TR Crystal Maze Start - Crystal'), ('TR Crystal Maze Start Crystal Exit', 'TR Crystal Maze Start'), ('TR Crystal Maze Interior to End Barrier - Blue', 'TR Crystal Maze End'), ('TR Crystal Maze Interior to Start Barrier - Blue', 'TR Crystal Maze Start'), ('TR Crystal Maze Interior to End Bypass', 'TR Crystal Maze End'), ('TR Crystal Maze Interior to Start Bypass', 'TR Crystal Maze Start'), ('TR Crystal Maze End to Interior Barrier - Blue', 'TR Crystal Maze Interior'), ('TR Crystal Maze End to Ranged Crystal', 'TR Crystal Maze End - Ranged Crystal'), ('TR Crystal Maze End Ranged Crystal Exit', 'TR Crystal Maze End'), ('GT Blocked Stairs Block Path', 'GT Big Chest'), ('GT Speed Torch South Path', 'GT Speed Torch'), ('GT Speed Torch North Path', 'GT Speed Torch Upper'), ('GT Hookshot East-North Path', 'GT Hookshot North Platform'), ('GT Hookshot East-South Path', 'GT Hookshot South Platform'), ('GT Hookshot North-East Path', 'GT Hookshot East Platform'), ('GT Hookshot North-South Path', 'GT Hookshot South Platform'), ('GT Hookshot South-East Path', 'GT Hookshot East Platform'), ('GT Hookshot South-North Path', 'GT Hookshot North Platform'), ('GT Hookshot Platform Blue Barrier', 'GT Hookshot South Entry'), ('GT Hookshot Platform Barrier Bypass', 'GT Hookshot South Entry'), ('GT Hookshot Entry Blue Barrier', 'GT Hookshot South Platform'), ('GT Hookshot South Entry to Ranged Crystal', 'GT Hookshot South Entry - Ranged Crystal'), ('GT HookShot South Entry Ranged Crystal Exit', 'GT Hookshot South Entry'), ('GT Double Switch Entry to Pot Corners Barrier - Orange', 'GT Double Switch Pot Corners'), ('GT Double Switch Entry to Left Barrier - Orange', 'GT Double Switch Left'), ('GT Double Switch Entry to Ranged Switches', 'GT Double Switch Entry - Ranged Switches'), ('GT Double Switch Entry Ranged Switches Exit', 'GT Double Switch Entry'), ('GT Double Switch Left to Crystal', 'GT Double Switch Left - Crystal'), ('GT Double Switch Left Crystal Exit', 'GT Double Switch Left'), ('GT Double Switch Left to Entry Barrier - Orange', 'GT Double Switch Entry'), ('GT Double Switch Left to Entry Bypass', 'GT Double Switch Entry'), ('GT Double Switch Left to Pot Corners Bypass', 'GT Double Switch Pot Corners'), ('GT Double Switch Left to Exit Bypass', 'GT Double Switch Exit'), ('GT Double Switch Pot Corners to Entry Barrier - Orange', 'GT Double Switch Entry'), ('GT Double Switch Pot Corners to Exit Barrier - Blue', 'GT Double Switch Exit'), ('GT Double Switch Pot Corners to Ranged Switches', 'GT Double Switch Pot Corners - Ranged Switches'), ('GT Double Switch Pot Corners Ranged Switches Exit', 'GT Double Switch Pot Corners'), ('GT Double Switch Exit to Blue Barrier', 'GT Double Switch Pot Corners'), ('GT Spike Crystal Left to Right Barrier - Orange', 'GT Spike Crystal Right'), ('GT Spike Crystal Right to Left Barrier - Orange', 'GT Spike Crystal Left'), ('GT Spike Crystal Left to Right Bypass', 'GT Spike Crystal Right'), ('GT Warp Maze - Pit Section Warp Spot', 'GT Warp Maze - Pit Exit Warp Spot'), ('GT Warp Maze Exit Section Warp Spot', 'GT Warp Maze - Pit Exit Warp Spot'), ('GT Firesnake Room Hook Path', 'GT Firesnake Room Ledge'), ('GT Crystal Conveyor to Corner Barrier - Blue', 'GT Crystal Conveyor Corner'), ('GT Crystal Conveyor to Ranged Crystal', 'GT Crystal Conveyor - Ranged Crystal'), ('GT Crystal Conveyor Corner to Left Bypass', 'GT Crystal Conveyor Left'), ('GT Crystal Conveyor Corner to Barrier - Blue', 'GT Crystal Conveyor Left'), ('GT Crystal Conveyor Corner to Barrier - Orange', 'GT Crystal Conveyor'), ('GT Crystal Conveyor Corner to Ranged Crystal', 'GT Crystal Conveyor Corner - Ranged Crystal'), ('GT Crystal Conveyor Left to Corner Barrier - Orange', 'GT Crystal Conveyor Corner'), ('GT Crystal Conveyor Ranged Crystal Exit', 'GT Crystal Conveyor'), ('GT Crystal Conveyor Corner Ranged Crystal Exit', 'GT Crystal Conveyor Corner'), ('GT Left Moldorm Ledge Drop Down', 'GT Moldorm'), ('GT Right Moldorm Ledge Drop Down', 'GT Moldorm'), ('GT Crystal Circles Barrier - Orange', 'GT Crystal Inner Circle'), ('GT Crystal Circles to Ranged Crystal', 'GT Crystal Circles - Ranged Crystal'), ('GT Crystal Inner Circle Barrier - Orange', 'GT Crystal Circles'), ('GT Crystal Circles Ranged Crystal Exit', 'GT Crystal Circles'), ('GT Moldorm Gap', 'GT Validation'), ('GT Validation Block Path', 'GT Validation Door') ] vanilla_logical_connections = [ ('Ice Cross Left Push Block', 'Ice Compass Room'), ('Ice Cross Right Push Block Bottom', 'Ice Compass Room'), ('Ice Cross Bottom Push Block Right', 'Ice Pengator Switch'), ('Ice Cross Top Push Block Right', 'Ice Pengator Switch'), ] spiral_staircases = [ ('Hyrule Castle Back Hall Down Stairs', 'Hyrule Dungeon Map Room Up Stairs'), ('Hyrule Dungeon Armory Down Stairs', 'Hyrule Dungeon Staircase Up Stairs'), ('Hyrule Dungeon Staircase Down Stairs', 'Hyrule Dungeon Cellblock Up Stairs'), ('Sewers Behind Tapestry Down Stairs', 'Sewers Rope Room Up Stairs'), ('Sewers Secret Room Up Stairs', 'Sewers Pull Switch Down Stairs'), ('Eastern Darkness Up Stairs', 'Eastern Attic Start Down Stairs'), ('Desert Tiles 1 Up Stairs', 'Desert Bridge Down Stairs'), ('Hera Lobby Down Stairs', 'Hera Basement Cage Up Stairs'), ('Hera Lobby Key Stairs', 'Hera Tile Room Up Stairs'), ('Hera Lobby Up Stairs', 'Hera Beetles Down Stairs'), ('Hera Startile Wide Up Stairs', 'Hera 4F Down Stairs'), ('Hera 4F Up Stairs', 'Hera 5F Down Stairs'), ('Hera 5F Up Stairs', 'Hera Boss Down Stairs'), ('Tower Room 03 Up Stairs', 'Tower Lone Statue Down Stairs'), ('Tower Dark Chargers Up Stairs', 'Tower Dual Statues Down Stairs'), ('Tower Dark Archers Up Stairs', 'Tower Red Spears Down Stairs'), ('Tower Pacifist Run Up Stairs', 'Tower Push Statue Down Stairs'), ('PoD Left Cage Down Stairs', 'PoD Shooter Room Up Stairs'), ('PoD Middle Cage Down Stairs', 'PoD Warp Room Up Stairs'), ('PoD Basement Ledge Up Stairs', 'PoD Big Key Landing Down Stairs'), ('PoD Compass Room W Down Stairs', 'PoD Dark Basement W Up Stairs'), ('PoD Compass Room E Down Stairs', 'PoD Dark Basement E Up Stairs'), ('Swamp Entrance Down Stairs', 'Swamp Pot Row Up Stairs'), ('Swamp West Block Path Up Stairs', 'Swamp Attic Down Stairs'), ('Swamp Push Statue Down Stairs', 'Swamp Flooded Room Up Stairs'), ('Swamp Left Elbow Down Stairs', 'Swamp Drain Left Up Stairs'), ('Swamp Right Elbow Down Stairs', 'Swamp Drain Right Up Stairs'), ('Swamp Behind Waterfall Up Stairs', 'Swamp C Down Stairs'), ('Thieves Spike Switch Up Stairs', 'Thieves Attic Down Stairs'), ('Thieves Conveyor Maze Down Stairs', 'Thieves Basement Block Up Stairs'), ('Ice Jelly Key Down Stairs', 'Ice Floor Switch Up Stairs'), ('Ice Narrow Corridor Down Stairs', 'Ice Pengator Trap Up Stairs'), ('Ice Spike Room Up Stairs', 'Ice Hammer Block Down Stairs'), ('Ice Spike Room Down Stairs', 'Ice Spikeball Up Stairs'), ('Ice Lonely Freezor Down Stairs', 'Iced T Up Stairs'), ('Ice Backwards Room Down Stairs', 'Ice Anti-Fairy Up Stairs'), ('Mire Post-Gap Down Stairs', 'Mire 2 Up Stairs'), ('Mire Left Bridge Down Stairs', 'Mire Dark Shooters Up Stairs'), ('Mire Conveyor Barrier Up Stairs', 'Mire Torches Top Down Stairs'), ('Mire Falling Foes Up Stairs', 'Mire Firesnake Skip Down Stairs'), ('TR Chain Chomps Down Stairs', 'TR Pipe Pit Up Stairs'), ('TR Crystaroller Down Stairs', 'TR Dark Ride Up Stairs'), ('GT Lobby Left Down Stairs', 'GT Torch Up Stairs'), ('GT Lobby Up Stairs', 'GT Crystal Paths Down Stairs'), ('GT Lobby Right Down Stairs', 'GT Hope Room Up Stairs'), ('GT Blocked Stairs Down Stairs', 'GT Four Torches Up Stairs'), ('GT Cannonball Bridge Up Stairs', 'GT Gauntlet 1 Down Stairs'), ('GT Quad Pot Up Stairs', 'GT Wizzrobes 1 Down Stairs'), ('GT Moldorm Pit Up Stairs', 'GT Right Moldorm Ledge Down Stairs'), ('GT Frozen Over Up Stairs', 'GT Brightly Lit Hall Down Stairs') ] straight_staircases = [ ('Hyrule Castle Lobby North Stairs', 'Hyrule Castle Throne Room South Stairs'), ('Sewers Rope Room North Stairs', 'Sewers Dark Cross South Stairs'), ('Tower Catwalk North Stairs', 'Tower Antechamber South Stairs'), ('PoD Conveyor North Stairs', 'PoD Map Balcony South Stairs'), ('TR Crystal Maze North Stairs', 'TR Final Abyss South Stairs') ] open_edges = [ ('Hyrule Dungeon North Abyss South Edge', 'Hyrule Dungeon South Abyss North Edge'), ('Hyrule Dungeon North Abyss Catwalk Edge', 'Hyrule Dungeon South Abyss Catwalk North Edge'), ('Hyrule Dungeon South Abyss West Edge', 'Hyrule Dungeon Guardroom Abyss Edge'), ('Hyrule Dungeon South Abyss Catwalk West Edge', 'Hyrule Dungeon Guardroom Catwalk Edge'), ('Desert Main Lobby NW Edge', 'Desert North Hall SW Edge'), ('Desert Main Lobby N Edge', 'Desert Dead End Edge'), ('Desert Main Lobby NE Edge', 'Desert North Hall SE Edge'), ('Desert Main Lobby E Edge', 'Desert East Wing W Edge'), ('Desert East Wing N Edge', 'Desert Arrow Pot Corner S Edge'), ('Desert Arrow Pot Corner W Edge', 'Desert North Hall E Edge'), ('Desert West Wing N Edge', 'Desert Sandworm Corner S Edge'), ('Desert Sandworm Corner E Edge', 'Desert North Hall W Edge'), ('Thieves Lobby N Edge', 'Thieves Ambush S Edge'), ('Thieves Lobby NE Edge', 'Thieves Ambush SE Edge'), ('Thieves Ambush ES Edge', 'Thieves BK Corner WS Edge'), ('Thieves Ambush EN Edge', 'Thieves BK Corner WN Edge'), ('Thieves BK Corner S Edge', 'Thieves Compass Room N Edge'), ('Thieves BK Corner SW Edge', 'Thieves Compass Room NW Edge'), ('Thieves Compass Room WS Edge', 'Thieves Big Chest Nook ES Edge'), ('Thieves Cricket Hall Left Edge', 'Thieves Cricket Hall Right Edge') ] falldown_pits = [ ('Eastern Courtyard Potholes', 'Eastern Fairies'), ('Hera Beetles Holes Front', 'Hera Front'), ('Hera Beetles Holes Landing', 'Hera Up Stairs Landing'), ('Hera Startile Corner Holes Front', 'Hera Front'), ('Hera Startile Corner Holes Landing', 'Hera Down Stairs Landing'), ('Hera Startile Wide Holes', 'Hera Back'), ('Hera 4F Holes', 'Hera Back'), # failed bomb jump ('Hera Big Chest Landing Holes', 'Hera Startile Wide'), # the other holes near big chest ('Hera 5F Star Hole', 'Hera Big Chest Landing'), ('Hera 5F Pothole Chain', 'Hera Fairies'), ('Hera 5F Normal Holes', 'Hera 4F'), ('Hera Boss Outer Hole', 'Hera 5F'), ('Hera Boss Inner Hole', 'Hera 4F'), ('PoD Pit Room Freefall', 'PoD Stalfos Basement'), ('PoD Pit Room Bomb Hole', 'PoD Basement Ledge'), ('PoD Big Key Landing Hole', 'PoD Stalfos Basement'), ('Swamp Attic Right Pit', 'Swamp Barrier Ledge'), ('Swamp Attic Left Pit', 'Swamp West Ledge'), ('Skull Final Drop Hole', 'Skull Boss'), ('Ice Bomb Drop Hole', 'Ice Stalfos Hint'), ('Ice Falling Square Hole', 'Ice Tall Hint'), ('Ice Freezors Hole', 'Ice Big Chest View'), ('Ice Freezors Ledge Hole', 'Ice Big Chest View'), ('Ice Freezors Bomb Hole', 'Ice Big Chest Landing'), ('Ice Crystal Block Hole', 'Ice Switch Room'), ('Ice Crystal Right Blue Hole', 'Ice Switch Room'), ('Ice Backwards Room Hole', 'Ice Fairy'), ('Ice Antechamber Hole', 'Ice Boss'), ('Mire Attic Hint Hole', 'Mire BK Chest Ledge'), ('Mire Torches Top Holes', 'Mire Conveyor Barrier'), ('Mire Torches Bottom Holes', 'Mire Warping Pool'), ('GT Bob\'s Room Hole', 'GT Ice Armos'), ('GT Falling Torches Hole', 'GT Staredown'), ('GT Moldorm Hole', 'GT Moldorm Pit') ] dungeon_warps = [ ('Eastern Fairies\' Warp', 'Eastern Courtyard'), ('Hera Fairies\' Warp', 'Hera 5F'), ('PoD Warp Hint Warp', 'PoD Warp Room'), ('PoD Warp Room Warp', 'PoD Warp Hint'), ('PoD Stalfos Basement Warp', 'PoD Warp Room'), ('PoD Callback Warp', 'PoD Dark Alley'), ('Ice Fairy Warp', 'Ice Anti-Fairy'), ('Mire Lone Warp Warp', 'Mire BK Door Room'), ('Mire Warping Pool Warp', 'Mire Square Rail'), ('GT Compass Room Warp', 'GT Conveyor Star Pits'), ('GT Spike Crystals Warp', 'GT Firesnake Room'), ('GT Warp Maze - Left Section Warp', 'GT Warp Maze - Rando Rail'), ('GT Warp Maze - Mid Section Left Warp', 'GT Warp Maze - Main Rails'), ('GT Warp Maze - Mid Section Right Warp', 'GT Warp Maze - Main Rails'), ('GT Warp Maze - Right Section Warp', 'GT Warp Maze - Main Rails'), ('GT Warp Maze - Pit Exit Warp', 'GT Warp Maze - Pot Rail'), ('GT Warp Maze - Rail Choice Left Warp', 'GT Warp Maze - Left Section'), ('GT Warp Maze - Rail Choice Right Warp', 'GT Warp Maze - Mid Section'), ('GT Warp Maze - Rando Rail Warp', 'GT Warp Maze - Mid Section'), ('GT Warp Maze - Main Rails Best Warp', 'GT Warp Maze - Pit Section'), ('GT Warp Maze - Main Rails Mid Left Warp', 'GT Warp Maze - Mid Section'), ('GT Warp Maze - Main Rails Mid Right Warp', 'GT Warp Maze - Mid Section'), ('GT Warp Maze - Main Rails Right Top Warp', 'GT Warp Maze - Right Section'), ('GT Warp Maze - Main Rails Right Mid Warp', 'GT Warp Maze - Right Section'), ('GT Warp Maze - Pot Rail Warp', 'GT Warp Maze Exit Section'), ('GT Hidden Star Warp', 'GT Invisible Bridges') ] ladders = [ ('PoD Bow Statue Down Ladder', 'PoD Dark Pegs Up Ladder'), ('Ice Big Key Down Ladder', 'Ice Tongue Pull Up Ladder'), ('Ice Firebar Down Ladder', 'Ice Freezors Up Ladder'), ('GT Staredown Up Ladder', 'GT Falling Torches Down Ladder') ] interior_doors = [ ('Hyrule Dungeon Armory Interior Key Door S', 'Hyrule Dungeon Armory Interior Key Door N'), ('Hyrule Dungeon Armory ES', 'Hyrule Dungeon Armory Boomerang WS'), ('Hyrule Dungeon Map Room Key Door S', 'Hyrule Dungeon North Abyss Key Door N'), ('Sewers Rat Path WS', 'Sewers Secret Room ES'), ('Sewers Rat Path WN', 'Sewers Secret Room EN'), ('Sewers Yet More Rats S', 'Sewers Pull Switch N'), ('Eastern Lobby N', 'Eastern Lobby Bridge S'), ('Eastern Lobby NW', 'Eastern Lobby Left Ledge SW'), ('Eastern Lobby NE', 'Eastern Lobby Right Ledge SE'), ('Eastern East Wing EN', 'Eastern Pot Switch WN'), ('Eastern East Wing ES', 'Eastern Map Balcony WS'), ('Eastern Pot Switch SE', 'Eastern Map Room NE'), ('Eastern West Wing WS', 'Eastern Stalfos Spawn ES'), ('Eastern Stalfos Spawn NW', 'Eastern Compass Room SW'), ('Eastern Compass Room EN', 'Eastern Hint Tile WN'), ('Eastern Dark Square EN', 'Eastern Dark Pots WN'), ('Eastern Darkness NE', 'Eastern Rupees SE'), ('Eastern False Switches WS', 'Eastern Cannonball Hell ES'), ('Eastern Single Eyegore NE', 'Eastern Duo Eyegores SE'), ('Desert East Lobby WS', 'Desert East Wing ES'), ('Desert East Wing Key Door EN', 'Desert Compass Key Door WN'), ('Desert North Hall NW', 'Desert Map SW'), ('Desert North Hall NE', 'Desert Map SE'), ('Desert Arrow Pot Corner NW', 'Desert Trap Room SW'), ('Desert Sandworm Corner NE', 'Desert Bonk Torch SE'), ('Desert Sandworm Corner WS', 'Desert Circle of Pots ES'), ('Desert Circle of Pots NW', 'Desert Big Chest SW'), ('Desert West Wing WS', 'Desert West Lobby ES'), ('Desert Fairy Fountain SW', 'Desert West Lobby NW'), ('Desert Back Lobby NW', 'Desert Tiles 1 SW'), ('Desert Bridge SW', 'Desert Four Statues NW'), ('Desert Four Statues ES', 'Desert Beamos Hall WS'), ('Desert Tiles 2 NE', 'Desert Wall Slide SE'), ('Hera Tile Room EN', 'Hera Tridorm WN'), ('Hera Tridorm SE', 'Hera Torches NE'), ('Hera Beetles WS', 'Hera Startile Corner ES'), ('Hera Startile Corner NW', 'Hera Startile Wide SW'), ('Tower Lobby NW', 'Tower Gold Knights SW'), ('Tower Gold Knights EN', 'Tower Room 03 WN'), ('Tower Lone Statue WN', 'Tower Dark Maze EN'), ('Tower Dark Maze ES', 'Tower Dark Chargers WS'), ('Tower Dual Statues WS', 'Tower Dark Pits ES'), ('Tower Dark Pits EN', 'Tower Dark Archers WN'), ('Tower Red Spears WN', 'Tower Red Guards EN'), ('Tower Red Guards SW', 'Tower Circle of Pots NW'), ('Tower Circle of Pots ES', 'Tower Pacifist Run WS'), ('Tower Push Statue WS', 'Tower Catwalk ES'), ('Tower Antechamber NW', 'Tower Altar SW'), ('PoD Lobby N', 'PoD Middle Cage S'), ('PoD Lobby NW', 'PoD Left Cage SW'), ('PoD Lobby NE', 'PoD Middle Cage SE'), ('PoD Warp Hint SE', 'PoD Jelly Hall NE'), ('PoD Jelly Hall NW', 'PoD Mimics 1 SW'), ('PoD Falling Bridge EN', 'PoD Compass Room WN'), ('PoD Compass Room SE', 'PoD Harmless Hellway NE'), ('PoD Mimics 2 NW', 'PoD Bow Statue SW'), ('PoD Dark Pegs WN', 'PoD Lonely Turtle EN'), ('PoD Lonely Turtle SW', 'PoD Turtle Party NW'), ('PoD Turtle Party ES', 'PoD Callback WS'), ('Swamp Trench 1 Nexus N', 'Swamp Trench 1 Alcove S'), ('Swamp Trench 1 Key Ledge NW', 'Swamp Hammer Switch SW'), ('Swamp Donut Top SE', 'Swamp Donut Bottom NE'), ('Swamp Donut Bottom NW', 'Swamp Compass Donut SW'), ('Swamp Crystal Switch SE', 'Swamp Shortcut NE'), ('Swamp Trench 2 Blocks N', 'Swamp Trench 2 Alcove S'), ('Swamp Push Statue NW', 'Swamp Shooters SW'), ('Swamp Push Statue NE', 'Swamp Right Elbow SE'), ('Swamp Shooters EN', 'Swamp Left Elbow WN'), ('Swamp Drain WN', 'Swamp Basement Shallows EN'), ('Swamp Flooded Room WS', 'Swamp Basement Shallows ES'), ('Swamp Waterfall Room NW', 'Swamp Refill SW'), ('Swamp Waterfall Room NE', 'Swamp Behind Waterfall SE'), ('Swamp C SE', 'Swamp Waterway NE'), ('Swamp Waterway N', 'Swamp I S'), ('Swamp Waterway NW', 'Swamp T SW'), ('Skull 1 Lobby ES', 'Skull Map Room WS'), ('Skull Pot Circle WN', 'Skull Pull Switch EN'), ('Skull Pull Switch S', 'Skull Big Chest N'), ('Skull Left Drop ES', 'Skull Compass Room WS'), ('Skull 2 East Lobby NW', 'Skull Big Key SW'), ('Skull Big Key EN', 'Skull Lone Pot WN'), ('Skull Small Hall WS', 'Skull 2 West Lobby ES'), ('Skull 2 West Lobby NW', 'Skull X Room SW'), ('Skull 3 Lobby EN', 'Skull East Bridge WN'), ('Skull East Bridge WS', 'Skull West Bridge Nook ES'), ('Skull Star Pits ES', 'Skull Torch Room WS'), ('Skull Torch Room WN', 'Skull Vines EN'), ('Skull Spike Corner ES', 'Skull Final Drop WS'), ('Thieves Hallway WS', 'Thieves Pot Alcove Mid ES'), ('Thieves Conveyor Maze SW', 'Thieves Pot Alcove Top NW'), ('Thieves Conveyor Maze EN', 'Thieves Hallway WN'), ('Thieves Spike Track NE', 'Thieves Triple Bypass SE'), ('Thieves Spike Track WS', 'Thieves Hellway Crystal ES'), ('Thieves Hellway Crystal EN', 'Thieves Triple Bypass WN'), ('Thieves Attic ES', 'Thieves Cricket Hall Left WS'), ('Thieves Cricket Hall Right ES', 'Thieves Attic Window WS'), ('Thieves Blocked Entry SW', 'Thieves Lonely Zazak NW'), ('Thieves Lonely Zazak ES', 'Thieves Blind\'s Cell WS'), ('Thieves Conveyor Bridge WS', 'Thieves Big Chest Room ES'), ('Thieves Conveyor Block WN', 'Thieves Trap EN'), ('Ice Lobby WS', 'Ice Jelly Key ES'), ('Ice Floor Switch ES', 'Ice Cross Left WS'), ('Ice Cross Top NE', 'Ice Bomb Drop SE'), ('Ice Pengator Switch ES', 'Ice Dead End WS'), ('Ice Stalfos Hint SE', 'Ice Conveyor NE'), ('Ice Bomb Jump EN', 'Ice Narrow Corridor WN'), ('Ice Spike Cross WS', 'Ice Firebar ES'), ('Ice Spike Cross NE', 'Ice Falling Square SE'), ('Ice Hammer Block ES', 'Ice Tongue Pull WS'), ('Ice Freezors Ledge ES', 'Ice Tall Hint WS'), ('Ice Hookshot Balcony SW', 'Ice Spikeball NW'), ('Ice Crystal Right NE', 'Ice Backwards Room SE'), ('Ice Crystal Left WS', 'Ice Big Chest View ES'), ('Ice Anti-Fairy SE', 'Ice Switch Room NE'), ('Mire Lone Shooter ES', 'Mire Falling Bridge WS'), # technically one-way ('Mire Falling Bridge W', 'Mire Failure Bridge E'), # technically one-way ('Mire Falling Bridge WN', 'Mire Map Spike Side EN'), # technically one-way ('Mire Hidden Shooters WS', 'Mire Cross ES'), # technically one-way ('Mire Hidden Shooters NE', 'Mire Minibridge SE'), ('Mire Spikes NW', 'Mire Ledgehop SW'), ('Mire Spike Barrier ES', 'Mire Square Rail WS'), ('Mire Square Rail NW', 'Mire Lone Warp SW'), ('Mire Wizzrobe Bypass WN', 'Mire Compass Room EN'), # technically one-way ('Mire Conveyor Crystal WS', 'Mire Tile Room ES'), ('Mire Tile Room NW', 'Mire Compass Room SW'), ('Mire Neglected Room SE', 'Mire Chest View NE'), ('Mire BK Chest Ledge WS', 'Mire Warping Pool ES'), # technically one-way ('Mire Torches Top SW', 'Mire Torches Bottom NW'), ('Mire Torches Bottom WS', 'Mire Attic Hint ES'), ('Mire Dark Shooters SE', 'Mire Key Rupees NE'), ('Mire Dark Shooters SW', 'Mire Block X NW'), ('Mire Tall Dark and Roomy WS', 'Mire Crystal Right ES'), ('Mire Tall Dark and Roomy WN', 'Mire Shooter Rupees EN'), ('Mire Crystal Mid NW', 'Mire Crystal Top SW'), ('TR Tile Room NE', 'TR Refill SE'), ('TR Pokey 1 NW', 'TR Chain Chomps SW'), ('TR Twin Pokeys EN', 'TR Dodgers WN'), ('TR Twin Pokeys SW', 'TR Hallway NW'), ('TR Hallway ES', 'TR Big View WS'), ('TR Big Chest NE', 'TR Dodgers SE'), ('TR Dash Room ES', 'TR Tongue Pull WS'), ('TR Dash Room NW', 'TR Crystaroller SW'), ('TR Tongue Pull NE', 'TR Rupees SE'), ('GT Torch EN', 'GT Hope Room WN'), ('GT Torch SW', 'GT Big Chest NW'), ('GT Tile Room EN', 'GT Speed Torch WN'), ('GT Speed Torch WS', 'GT Pots n Blocks ES'), ('GT Crystal Conveyor WN', 'GT Compass Room EN'), ('GT Conveyor Cross WN', 'GT Hookshot EN'), ('GT Hookshot ES', 'GT Map Room WS'), ('GT Double Switch EN', 'GT Spike Crystals WN'), ('GT Firesnake Room SW', 'GT Warp Maze (Rails) NW'), ('GT Ice Armos NE', 'GT Big Key Room SE'), ('GT Ice Armos WS', 'GT Four Torches ES'), ('GT Four Torches NW', 'GT Fairy Abyss SW'), ('GT Crystal Paths SW', 'GT Mimics 1 NW'), ('GT Mimics 1 ES', 'GT Mimics 2 WS'), ('GT Mimics 2 NE', 'GT Dash Hall SE'), ('GT Cannonball Bridge SE', 'GT Refill NE'), ('GT Gauntlet 1 WN', 'GT Gauntlet 2 EN'), ('GT Gauntlet 2 SW', 'GT Gauntlet 3 NW'), ('GT Gauntlet 4 SW', 'GT Gauntlet 5 NW'), ('GT Beam Dash WS', 'GT Lanmolas 2 ES'), ('GT Lanmolas 2 NW', 'GT Quad Pot SW'), ('GT Wizzrobes 1 SW', 'GT Dashing Bridge NW'), ('GT Dashing Bridge NE', 'GT Wizzrobes 2 SE'), ('GT Torch Cross ES', 'GT Staredown WS'), ('GT Falling Torches NE', 'GT Mini Helmasaur Room SE'), ('GT Mini Helmasaur Room WN', 'GT Bomb Conveyor EN'), ('GT Bomb Conveyor SW', 'GT Crystal Circles NW') ] key_doors = [ ('Sewers Key Rat Key Door N', 'Sewers Secret Room Key Door S'), ('Sewers Dark Cross Key Door N', 'Sewers Water S'), ('Eastern Dark Square Key Door WN', 'Eastern Cannonball Ledge Key Door EN'), ('Eastern Darkness Up Stairs', 'Eastern Attic Start Down Stairs'), ('Eastern Big Key NE', 'Eastern Hint Tile Blocked Path SE'), ('Eastern Darkness S', 'Eastern Courtyard N'), ('Desert East Wing Key Door EN', 'Desert Compass Key Door WN'), ('Desert Tiles 1 Up Stairs', 'Desert Bridge Down Stairs'), ('Desert Beamos Hall NE', 'Desert Tiles 2 SE'), ('Desert Tiles 2 NE', 'Desert Wall Slide SE'), ('Desert Wall Slide NW', 'Desert Boss SW'), ('Hera Lobby Key Stairs', 'Hera Tile Room Up Stairs'), ('Hera Startile Corner NW', 'Hera Startile Wide SW'), ('PoD Middle Cage N', 'PoD Pit Room S'), ('PoD Arena Main NW', 'PoD Falling Bridge SW'), ('PoD Falling Bridge WN', 'PoD Dark Maze EN'), ] default_small_key_doors = { 'Hyrule Castle': [ ('Sewers Key Rat Key Door N', 'Sewers Secret Room Key Door S'), ('Sewers Dark Cross Key Door N', 'Sewers Water S'), ('Hyrule Dungeon Map Room Key Door S', 'Hyrule Dungeon North Abyss Key Door N'), ('Hyrule Dungeon Armory Interior Key Door N', 'Hyrule Dungeon Armory Interior Key Door S') ], 'Eastern Palace': [ ('Eastern Dark Square Key Door WN', 'Eastern Cannonball Ledge Key Door EN'), 'Eastern Darkness Up Stairs', ], 'Desert Palace': [ ('Desert East Wing Key Door EN', 'Desert Compass Key Door WN'), 'Desert Tiles 1 Up Stairs', ('Desert Beamos Hall NE', 'Desert Tiles 2 SE'), ('Desert Tiles 2 NE', 'Desert Wall Slide SE'), ], 'Tower of Hera': [ 'Hera Lobby Key Stairs' ], 'Agahnims Tower': [ 'Tower Room 03 Up Stairs', ('Tower Dark Maze ES', 'Tower Dark Chargers WS'), 'Tower Dark Archers Up Stairs', ('Tower Circle of Pots ES', 'Tower Pacifist Run WS'), ], 'Palace of Darkness': [ ('PoD Middle Cage N', 'PoD Pit Room S'), ('PoD Arena Main NW', 'PoD Falling Bridge SW'), ('PoD Falling Bridge WN', 'PoD Dark Maze EN'), 'PoD Basement Ledge Up Stairs', ('PoD Compass Room SE', 'PoD Harmless Hellway NE'), ('PoD Dark Pegs WN', 'PoD Lonely Turtle EN') ], 'Swamp Palace': [ 'Swamp Entrance Down Stairs', ('Swamp Pot Row WS', 'Swamp Trench 1 Approach ES'), ('Swamp Trench 1 Key Ledge NW', 'Swamp Hammer Switch SW'), ('Swamp Hub WN', 'Swamp Crystal Switch EN'), ('Swamp Hub North Ledge N', 'Swamp Push Statue S'), ('Swamp Waterway NW', 'Swamp T SW') ], 'Skull Woods': [ ('Skull 1 Lobby WS', 'Skull Pot Prison ES'), ('Skull Map Room SE', 'Skull Pinball NE'), ('Skull 2 West Lobby NW', 'Skull X Room SW'), ('Skull 3 Lobby NW', 'Skull Star Pits SW'), ('Skull Spike Corner ES', 'Skull Final Drop WS') ], 'Thieves Town': [ ('Thieves Hallway WS', 'Thieves Pot Alcove Mid ES'), 'Thieves Spike Switch Up Stairs', ('Thieves Conveyor Bridge WS', 'Thieves Big Chest Room ES') ], 'Ice Palace': [ 'Ice Jelly Key Down Stairs', ('Ice Conveyor SW', 'Ice Bomb Jump NW'), ('Ice Spike Cross ES', 'Ice Spike Room WS'), ('Ice Tall Hint SE', 'Ice Lonely Freezor NE'), 'Ice Backwards Room Down Stairs', ('Ice Switch Room ES', 'Ice Refill WS') ], 'Misery Mire': [ ('Mire Hub WS', 'Mire Conveyor Crystal ES'), ('Mire Hub Right EN', 'Mire Map Spot WN'), ('Mire Spikes NW', 'Mire Ledgehop SW'), ('Mire Fishbone SE', 'Mire Spike Barrier NE'), ('Mire Conveyor Crystal WS', 'Mire Tile Room ES'), ('Mire Dark Shooters SE', 'Mire Key Rupees NE') ], 'Turtle Rock': [ ('TR Hub NW', 'TR Pokey 1 SW'), ('TR Pokey 1 NW', 'TR Chain Chomps SW'), 'TR Chain Chomps Down Stairs', ('TR Pokey 2 ES', 'TR Lava Island WS'), 'TR Crystaroller Down Stairs', ('TR Dash Bridge WS', 'TR Crystal Maze ES') ], 'Ganons Tower': [ ('GT Torch EN', 'GT Hope Room WN'), ('GT Tile Room EN', 'GT Speed Torch WN'), ('GT Hookshot ES', 'GT Map Room WS'), ('GT Double Switch EN', 'GT Spike Crystals WN'), ('GT Firesnake Room SW', 'GT Warp Maze (Rails) NW'), ('GT Conveyor Star Pits EN', 'GT Falling Bridge WN'), ('GT Mini Helmasaur Room WN', 'GT Bomb Conveyor EN'), ('GT Crystal Circles SW', 'GT Left Moldorm Ledge NW') ] } default_door_connections = [ ('Hyrule Castle Lobby W', 'Hyrule Castle West Lobby E'), ('Hyrule Castle Lobby E', 'Hyrule Castle East Lobby W'), ('Hyrule Castle Lobby WN', 'Hyrule Castle West Lobby EN'), ('Hyrule Castle West Lobby N', 'Hyrule Castle West Hall S'), ('Hyrule Castle East Lobby N', 'Hyrule Castle East Hall S'), ('Hyrule Castle East Lobby NW', 'Hyrule Castle East Hall SW'), ('Hyrule Castle East Hall W', 'Hyrule Castle Back Hall E'), ('Hyrule Castle West Hall E', 'Hyrule Castle Back Hall W'), ('Hyrule Castle Throne Room N', 'Sewers Behind Tapestry S'), ('Hyrule Dungeon Guardroom N', 'Hyrule Dungeon Armory S'), ('Sewers Dark Cross Key Door N', 'Sewers Water S'), ('Sewers Water W', 'Sewers Key Rat E'), ('Sewers Key Rat Key Door N', 'Sewers Secret Room Key Door S'), ('Eastern Lobby Bridge N', 'Eastern Cannonball S'), ('Eastern Cannonball N', 'Eastern Courtyard Ledge S'), ('Eastern Cannonball Ledge WN', 'Eastern Big Key EN'), ('Eastern Cannonball Ledge Key Door EN', 'Eastern Dark Square Key Door WN'), ('Eastern Courtyard Ledge W', 'Eastern West Wing E'), ('Eastern Courtyard Ledge E', 'Eastern East Wing W'), ('Eastern Hint Tile EN', 'Eastern Courtyard WN'), ('Eastern Big Key NE', 'Eastern Hint Tile Blocked Path SE'), ('Eastern Courtyard EN', 'Eastern Map Valley WN'), ('Eastern Courtyard N', 'Eastern Darkness S'), ('Eastern Map Valley SW', 'Eastern Dark Square NW'), ('Eastern Attic Start WS', 'Eastern False Switches ES'), ('Eastern Cannonball Hell WS', 'Eastern Single Eyegore ES'), ('Desert Compass NW', 'Desert Cannonball S'), ('Desert Beamos Hall NE', 'Desert Tiles 2 SE'), ('PoD Middle Cage N', 'PoD Pit Room S'), ('PoD Pit Room NW', 'PoD Arena Main SW'), ('PoD Pit Room NE', 'PoD Arena Bridge SE'), ('PoD Arena Main NW', 'PoD Falling Bridge SW'), ('PoD Arena Crystals E', 'PoD Sexy Statue W'), ('PoD Mimics 1 NW', 'PoD Conveyor SW'), ('PoD Map Balcony WS', 'PoD Arena Ledge ES'), ('PoD Falling Bridge WN', 'PoD Dark Maze EN'), ('PoD Dark Maze E', 'PoD Big Chest Balcony W'), ('PoD Sexy Statue NW', 'PoD Mimics 2 SW'), ('Swamp Pot Row WN', 'Swamp Map Ledge EN'), ('Swamp Pot Row WS', 'Swamp Trench 1 Approach ES'), ('Swamp Trench 1 Departure WS', 'Swamp Hub ES'), ('Swamp Hammer Switch WN', 'Swamp Hub Dead Ledge EN'), ('Swamp Hub S', 'Swamp Donut Top N'), ('Swamp Hub WS', 'Swamp Trench 2 Pots ES'), ('Swamp Hub WN', 'Swamp Crystal Switch EN'), ('Swamp Hub North Ledge N', 'Swamp Push Statue S'), ('Swamp Trench 2 Departure WS', 'Swamp West Shallows ES'), ('Swamp Big Key Ledge WN', 'Swamp Barrier EN'), ('Swamp Basement Shallows NW', 'Swamp Waterfall Room SW'), ('Skull 1 Lobby WS', 'Skull Pot Prison ES'), ('Skull Map Room SE', 'Skull Pinball NE'), ('Skull Pinball WS', 'Skull Compass Room ES'), ('Skull Compass Room NE', 'Skull Pot Prison SE'), ('Skull 2 East Lobby WS', 'Skull Small Hall ES'), ('Skull 3 Lobby NW', 'Skull Star Pits SW'), ('Skull Vines NW', 'Skull Spike Corner SW'), ('Thieves Lobby E', 'Thieves Compass Room W'), ('Thieves Ambush E', 'Thieves Rail Ledge W'), ('Thieves Rail Ledge NW', 'Thieves Pot Alcove Bottom SW'), ('Thieves BK Corner NE', 'Thieves Hallway SE'), ('Thieves Pot Alcove Mid WS', 'Thieves Spike Track ES'), ('Thieves Hellway NW', 'Thieves Spike Switch SW'), ('Thieves Triple Bypass EN', 'Thieves Conveyor Maze WN'), ('Thieves Basement Block WN', 'Thieves Conveyor Bridge EN'), ('Thieves Lonely Zazak WS', 'Thieves Conveyor Bridge ES'), ('Ice Cross Bottom SE', 'Ice Compass Room NE'), ('Ice Cross Right ES', 'Ice Pengator Switch WS'), ('Ice Conveyor SW', 'Ice Bomb Jump NW'), ('Ice Pengator Trap NE', 'Ice Spike Cross SE'), ('Ice Spike Cross ES', 'Ice Spike Room WS'), ('Ice Tall Hint SE', 'Ice Lonely Freezor NE'), ('Ice Tall Hint EN', 'Ice Hookshot Ledge WN'), ('Iced T EN', 'Ice Catwalk WN'), ('Ice Catwalk NW', 'Ice Many Pots SW'), ('Ice Many Pots WS', 'Ice Crystal Right ES'), ('Ice Switch Room ES', 'Ice Refill WS'), ('Ice Switch Room SE', 'Ice Antechamber NE'), ('Mire 2 NE', 'Mire Hub SE'), ('Mire Hub ES', 'Mire Lone Shooter WS'), ('Mire Hub E', 'Mire Failure Bridge W'), ('Mire Hub NE', 'Mire Hidden Shooters SE'), ('Mire Hub WN', 'Mire Wizzrobe Bypass EN'), ('Mire Hub WS', 'Mire Conveyor Crystal ES'), ('Mire Hub Right EN', 'Mire Map Spot WN'), ('Mire Hub Top NW', 'Mire Cross SW'), ('Mire Hidden Shooters ES', 'Mire Spikes WS'), ('Mire Minibridge NE', 'Mire Right Bridge SE'), ('Mire BK Door Room EN', 'Mire Ledgehop WN'), ('Mire BK Door Room N', 'Mire Left Bridge S'), ('Mire Spikes SW', 'Mire Crystal Dead End NW'), ('Mire Ledgehop NW', 'Mire Bent Bridge SW'), ('Mire Bent Bridge W', 'Mire Over Bridge E'), ('Mire Over Bridge W', 'Mire Fishbone E'), ('Mire Fishbone SE', 'Mire Spike Barrier NE'), ('Mire Spike Barrier SE', 'Mire Wizzrobe Bypass NE'), ('Mire Conveyor Crystal SE', 'Mire Neglected Room NE'), ('Mire Tile Room SW', 'Mire Conveyor Barrier NW'), ('Mire Block X WS', 'Mire Tall Dark and Roomy ES'), ('Mire Crystal Left WS', 'Mire Falling Foes ES'), ('TR Lobby Ledge NE', 'TR Hub SE'), ('TR Compass Room NW', 'TR Hub SW'), ('TR Hub ES', 'TR Torches Ledge WS'), ('TR Hub EN', 'TR Torches WN'), ('TR Hub NW', 'TR Pokey 1 SW'), ('TR Hub NE', 'TR Tile Room SE'), ('TR Torches NW', 'TR Roller Room SW'), ('TR Pipe Pit WN', 'TR Lava Dual Pipes EN'), ('TR Lava Island ES', 'TR Pipe Ledge WS'), ('TR Lava Dual Pipes SW', 'TR Twin Pokeys NW'), ('TR Lava Dual Pipes WN', 'TR Pokey 2 EN'), ('TR Pokey 2 ES', 'TR Lava Island WS'), ('TR Dodgers NE', 'TR Lava Escape SE'), ('TR Lava Escape NW', 'TR Dash Room SW'), ('TR Hallway WS', 'TR Lazy Eyes ES'), ('TR Dark Ride SW', 'TR Dash Bridge NW'), ('TR Dash Bridge SW', 'TR Eye Bridge NW'), ('TR Dash Bridge WS', 'TR Crystal Maze ES'), ('GT Torch WN', 'GT Conveyor Cross EN'), ('GT Hope Room EN', 'GT Tile Room WN'), ('GT Big Chest SW', 'GT Invisible Catwalk NW'), ('GT Bob\'s Room SE', 'GT Invisible Catwalk NE'), ('GT Speed Torch NE', 'GT Petting Zoo SE'), ('GT Speed Torch SE', 'GT Crystal Conveyor NE'), ('GT Warp Maze (Pits) ES', 'GT Invisible Catwalk WS'), ('GT Hookshot NW', 'GT DMs Room SW'), ('GT Hookshot SW', 'GT Double Switch NW'), ('GT Warp Maze (Rails) WS', 'GT Randomizer Room ES'), ('GT Conveyor Star Pits EN', 'GT Falling Bridge WN'), ('GT Falling Bridge WS', 'GT Hidden Star ES'), ('GT Dash Hall NE', 'GT Hidden Spikes SE'), ('GT Hidden Spikes EN', 'GT Cannonball Bridge WN'), ('GT Gauntlet 3 SW', 'GT Gauntlet 4 NW'), ('GT Gauntlet 5 WS', 'GT Beam Dash ES'), ('GT Wizzrobes 2 NE', 'GT Conveyor Bridge SE'), ('GT Conveyor Bridge EN', 'GT Torch Cross WN'), ('GT Crystal Circles SW', 'GT Left Moldorm Ledge NW') ] default_one_way_connections = [ ('Sewers Pull Switch S', 'Sanctuary N'), ('Eastern Duo Eyegores NE', 'Eastern Boss SE'), ('Desert Wall Slide NW', 'Desert Boss SW'), ('Tower Altar NW', 'Tower Agahnim 1 SW'), ('PoD Harmless Hellway SE', 'PoD Arena Main NE'), ('PoD Dark Alley NE', 'PoD Boss SE'), ('Swamp T NW', 'Swamp Boss SW'), ('Thieves Hallway NE', 'Thieves Boss SE'), ('Mire Antechamber NW', 'Mire Boss SW'), ('TR Final Abyss NW', 'TR Boss SW'), ('GT Invisible Bridges WS', 'GT Invisible Catwalk ES'), ('GT Validation WS', 'GT Frozen Over ES'), ('GT Brightly Lit Hall NW', 'GT Agahnim 2 SW') ] # For crossed # offset from 0x122e17, sram storage, write offset from compass_w_addr, 0 = jmp or # of nops, dungeon_id compass_data = { 'Hyrule Castle': (0x1, 0xc0, 0x16, 0, 0x02), 'Eastern Palace': (0x1C, 0xc1, 0x28, 0, 0x04), 'Desert Palace': (0x35, 0xc2, 0x4a, 0, 0x06), 'Agahnims Tower': (0x51, 0xc3, 0x5c, 0, 0x08), 'Swamp Palace': (0x6A, 0xc4, 0x7e, 0, 0x0a), 'Palace of Darkness': (0x83, 0xc5, 0xa4, 0, 0x0c), 'Misery Mire': (0x9C, 0xc6, 0xca, 0, 0x0e), 'Skull Woods': (0xB5, 0xc7, 0xf0, 0, 0x10), 'Ice Palace': (0xD0, 0xc8, 0x102, 0, 0x12), 'Tower of Hera': (0xEB, 0xc9, 0x114, 0, 0x14), 'Thieves Town': (0x106, 0xca, 0x138, 0, 0x16), 'Turtle Rock': (0x11F, 0xcb, 0x15e, 0, 0x18), 'Ganons Tower': (0x13A, 0xcc, 0x170, 2, 0x1a) } # For compass boss indicator boss_indicator = { 'Eastern Palace': (0x04, 'Eastern Boss SE'), 'Desert Palace': (0x06, 'Desert Boss SW'), 'Agahnims Tower': (0x08, 'Tower Agahnim 1 SW'), 'Swamp Palace': (0x0a, 'Swamp Boss SW'), 'Palace of Darkness': (0x0c, 'PoD Boss SE'), 'Misery Mire': (0x0e, 'Mire Boss SW'), 'Skull Woods': (0x10, 'Skull Spike Corner SW'), 'Ice Palace': (0x12, 'Ice Antechamber NE'), 'Tower of Hera': (0x14, 'Hera Boss Down Stairs'), 'Thieves Town': (0x16, 'Thieves Boss SE'), 'Turtle Rock': (0x18, 'TR Boss SW'), 'Ganons Tower': (0x1a, 'GT Agahnim 2 SW') } # tuples: (non-boss, boss) # see Utils for other notes palette_map = { 'Hyrule Castle': (0x0, None), 'Eastern Palace': (0xb, None), 'Desert Palace': (0x9, 0x4, 'Desert Boss SW'), 'Agahnims Tower': (0x0, 0xc, 'Tower Agahnim 1 SW'), # ancillary 0x26 for F1, F4 'Swamp Palace': (0xa, 0x8, 'Swamp Boss SW'), 'Palace of Darkness': (0xf, 0x10, 'PoD Boss SE'), 'Misery Mire': (0x11, 0x12, 'Mire Boss SW'), 'Skull Woods': (0xd, 0xe, 'Skull Spike Corner SW'), 'Ice Palace': (0x13, 0x14, 'Ice Antechamber NE'), 'Tower of Hera': (0x6, None), 'Thieves Town': (0x17, None), # the attic uses 0x23 'Turtle Rock': (0x18, 0x19, 'TR Boss SW'), 'Ganons Tower': (0x28, 0x1b, 'GT Agahnim 2 SW'), # other palettes: 0x1a (other) 0x24 (Gauntlet - Lanmo) 0x25 (conveyor-torch-wizzrode moldorm pit f5?) } # implications: # pipe room -> where lava chest is # dark alley -> where pod basement is # conveyor star or hidden star -> where DMs room is # falling bridge -> where Rando room is # petting zoo -> where firesnake is # basement cage -> where tile room is # bob's room -> where big chest/hope/torch are # invis bridges -> compass room palette_non_influencers = { 'PoD Shooter Room Up Stairs', 'TR Lava Dual Pipes EN', 'TR Lava Dual Pipes WN', 'TR Lava Dual Pipes SW', 'TR Lava Escape SE', 'TR Lava Escape NW', 'PoD Arena Ledge ES', 'Swamp Big Key Ledge WN', 'Swamp Hub Dead Ledge EN', 'Swamp Map Ledge EN', 'Skull Pot Prison ES', 'Skull Pot Prison SE', 'PoD Dark Alley NE', 'GT Conveyor Star Pits EN', 'GT Hidden Star ES', 'GT Falling Bridge WN', 'GT Falling Bridge WS', 'GT Petting Zoo SE', 'Hera Basement Cage Up Stairs', "GT Bob's Room SE", 'GT Warp Maze (Pits) ES', 'GT Invisible Bridges WS', 'Mire Over Bridge E', 'Mire Over Bridge W', 'Eastern Courtyard Ledge S', 'Eastern Courtyard Ledge W', 'Eastern Courtyard Ledge E', 'Eastern Map Valley WN', 'Eastern Map Valley SW', 'Mire BK Door Room EN', 'Mire BK Door Room N', 'TR Tile Room SE', 'TR Tile Room NE', 'TR Refill SE', 'Eastern Cannonball Ledge WN', 'Eastern Cannonball Ledge Key Door EN', 'Mire Neglected Room SE', 'Mire Neglected Room NE', 'Mire Chest View NE', 'TR Compass Room NW', 'Desert Dead End Edge', 'Hyrule Dungeon South Abyss Catwalk North Edge', 'Hyrule Dungeon South Abyss Catwalk West Edge' } portal_map = { 'Sanctuary': ('Sanctuary', 'Sanctuary Exit', 'Enter HC (Sanc)'), 'Hyrule Castle West': ('Hyrule Castle Entrance (West)', 'Hyrule Castle Exit (West)', 'Enter HC (West)'), 'Hyrule Castle South': ('Hyrule Castle Entrance (South)', 'Hyrule Castle Exit (South)', 'Enter HC (South)'), 'Hyrule Castle East': ('Hyrule Castle Entrance (East)', 'Hyrule Castle Exit (East)', 'Enter HC (East)'), 'Eastern': ('Eastern Palace', 'Eastern Palace Exit', 'Enter Eastern Palace'), 'Desert West': ('Desert Palace Entrance (West)', 'Desert Palace Exit (West)', 'Enter Desert (West)'), 'Desert South': ('Desert Palace Entrance (South)', 'Desert Palace Exit (South)', 'Enter Desert (South)'), 'Desert East': ('Desert Palace Entrance (East)', 'Desert Palace Exit (East)', 'Enter Desert (East)'), 'Desert Back': ('Desert Palace Entrance (North)', 'Desert Palace Exit (North)', 'Enter Desert (North)'), 'Turtle Rock Lazy Eyes': ('Dark Death Mountain Ledge (West)', 'Turtle Rock Ledge Exit (West)', 'Enter Turtle Rock (Lazy Eyes)'), 'Turtle Rock Eye Bridge': ('Turtle Rock Isolated Ledge Entrance', 'Turtle Rock Isolated Ledge Exit', 'Enter Turtle Rock (Laser Bridge)'), 'Turtle Rock Chest': ('Dark Death Mountain Ledge (East)', 'Turtle Rock Ledge Exit (East)', 'Enter Turtle Rock (Chest)'), 'Agahnims Tower': ('Agahnims Tower', 'Agahnims Tower Exit', 'Enter Agahnims Tower'), 'Swamp': ('Swamp Palace', 'Swamp Palace Exit', 'Enter Swamp'), 'Palace of Darkness': ('Palace of Darkness', 'Palace of Darkness Exit', 'Enter Palace of Darkness'), 'Mire': ('Misery Mire', 'Misery Mire Exit', 'Enter Misery Mire'), 'Skull 2 West': ('Skull Woods Second Section Door (West)', 'Skull Woods Second Section Exit (West)', 'Enter Skull Woods 2 (West)'), 'Skull 2 East': ('Skull Woods Second Section Door (East)', 'Skull Woods Second Section Exit (East)', 'Enter Skull Woods 2 (East)'), 'Skull 1': ('Skull Woods First Section Door', 'Skull Woods First Section Exit', 'Enter Skull Woods 1'), 'Skull 3': ('Skull Woods Final Section', 'Skull Woods Final Section Exit', 'Enter Skull Woods 3'), 'Ice': ('Ice Palace', 'Ice Palace Exit', 'Enter Ice Palace'), 'Hera': ('Tower of Hera', 'Tower of Hera Exit', 'Enter Hera'), 'Thieves Town': ('Thieves Town', 'Thieves Town Exit', 'Enter Thieves Town'), 'Turtle Rock Main': ('Turtle Rock', 'Turtle Rock Exit (Front)', 'Enter Turtle Rock (Main)'), 'Ganons Tower': ('Ganons Tower', 'Ganons Tower Exit', 'Enter Ganons Tower'), } multiple_portal_map = { 'Hyrule Castle': ['Sanctuary', 'Hyrule Castle West', 'Hyrule Castle South', 'Hyrule Castle East'], 'Desert Palace': ['Desert West', 'Desert South', 'Desert East', 'Desert Back'], 'Skull Woods': ['Skull 1', 'Skull 2 West', 'Skull 2 East', 'Skull 3'], 'Turtle Rock': ['Turtle Rock Lazy Eyes', 'Turtle Rock Eye Bridge', 'Turtle Rock Chest', 'Turtle Rock Main'], } split_portals = { 'Desert Palace': ['Back', 'Main'], 'Skull Woods': ['1', '2', '3'] } split_portal_defaults = { 'Desert Palace': { 'Desert Back Lobby': 'Back', 'Desert Main Lobby': 'Main', 'Desert West Lobby': 'Main', 'Desert East Lobby': 'Main' }, 'Skull Woods': { 'Skull 1 Lobby': '1', 'Skull 2 East Lobby': '2', 'Skull 2 West Lobby': '2', 'Skull 3 Lobby': '3' } } bomb_dash_counts = { 'Hyrule Castle': (0, 2), 'Eastern Palace': (0, 0), 'Desert Palace': (0, 0), 'Agahnims Tower': (0, 0), 'Swamp Palace': (2, 0), 'Palace of Darkness': (3, 2), 'Misery Mire': (2, 0), 'Skull Woods': (2, 0), 'Ice Palace': (0, 0), 'Tower of Hera': (0, 0), 'Thieves Town': (1, 1), 'Turtle Rock': (0, 2), # 2 bombs kind of for entrances 'Ganons Tower': (2, 1) }
""" Export forces to sto """ from pathlib import Path import matplotlib.pyplot as plt import numpy as np import yaml from pyosim import Conf from pyosim import Analogs3dOsim aws_conf = yaml.safe_load(open("../conf.yml")) local_or_distant = "distant" if aws_conf["distant_id"]["enable"] else "local" conf = Conf(project_path=aws_conf["path"]["project"][local_or_distant]) participants = conf.get_participants_to_process() calibration_matrix = np.genfromtxt( conf.project_path / "forces_calibration_matrix.csv", delimiter="," ) params = { "low_pass_cutoff": 30, "order": 4, "forces_labels": conf.get_conf_field( participant=participants[0], field=["analogs", "targets"] ), } for i, iparticipant in enumerate(participants[:]): print(f"\nparticipant #{i}: {iparticipant}") directories = conf.get_conf_field( participant=iparticipant, field=["analogs", "data"] ) assigned = conf.get_conf_field( participant=iparticipant, field=["analogs", "assigned"] ) for itrial in Path(directories[0]).glob("*.c3d"): # try participant's channel assignment for iassign in assigned: # get index where assignment are empty nan_idx = [i for i, v in enumerate(iassign) if not v] if nan_idx: iassign_without_nans = [i for i in iassign if i] else: iassign_without_nans = iassign try: forces = Analogs3dOsim.from_c3d( itrial, names=iassign_without_nans, prefix=":" ) # Analogs3dOsim.from_c3d(itrial).get_labels if nan_idx: forces.get_nan_idx = np.array(nan_idx) # if there is any empty assignment, fill the dimension with nan for i in nan_idx: forces = np.insert(forces, i, np.nan, axis=1) print(f"\t{itrial.stem} (NaNs: {nan_idx})") else: print(f"\t{itrial.stem}") # check if dimensions are ok if not forces.shape[1] == len(iassign): raise ValueError("Wrong dimensions") break except ValueError: forces = [] # check if there is empty frames nan_rows = np.isnan(forces).any(axis=1).ravel() print( f"\t\tremoving {nan_rows.sum()} nan frames (indices: {np.argwhere(nan_rows)})" ) forces = forces[..., ~nan_rows] # processing (offset during the first second, calibration, low pass) forces = ( forces.center( mu=np.nanmedian(forces[..., 10 : int(forces.get_rate)], axis=-1), axis=-1, ) .squeeze() .T.matmul(calibration_matrix.T) .low_pass( freq=forces.get_rate, order=params["order"], cutoff=params["low_pass_cutoff"], ) .dot(-1) ) norm = Analogs3dOsim(forces[0, :3, :].norm(axis=0).reshape(1, 1, -1)) idx = norm[0, 0, :].detect_onset( threshold=5, above=int(forces.get_rate) / 2, below=1000 # 5 Newtons ) # Special cases if itrial.stem == "MarSF12H4_1": idx[0][1] = 11983 if itrial.stem == "MarSF6H4_1": idx[0][1] = 10672 if itrial.stem == "GatBH18H4_2": idx[0][1] = 17122 if itrial.stem == "GatBH18H4_2": idx[0][1] = 17122 if itrial.stem == "GatBH18H4_3": idx = np.array([[5271, 15965]]) if itrial.stem == "CamBF12H5_3": continue if itrial.stem == "EveDF12H1_2": idx = np.array([[1229, 5549]]) if itrial.stem == "SamNF12H5_2": idx = np.array([[3483, 14498]]) if itrial.stem == "SamNF6H3_1": idx = np.array([[3698, 12314]]) if itrial.stem == "AimQF12H3_1": idx = np.array([[4041, 10328]]) if itrial.stem == "AleBH18H6_3": idx = np.array([[2279, 11058]]) if itrial.stem == "AmiAF12H6_3": idx = np.array([[6146, 16873]]) if itrial.stem == "CarBF12H6_3": idx = np.array([[1649, 10415]]) if itrial.stem == "AnnSF6H2_3": continue if itrial.stem == "SteBF6H2_2": continue if itrial.stem == "SteBF6H3_1": idx = np.array([[2591, 8100]]) if itrial.stem == "RoxDF6H6_1": idx = np.array([[2883, 9514]]) if itrial.stem == "RoxDF6H6_2": idx = np.array([[2883, 9514]]) if itrial.stem == "GeoAH12H1_2": idx = np.array([[1110, 7764]]) if itrial.stem == "GeoAH12H2_1": idx = np.array([[1136, 9211]]) if itrial.stem == "GeoAH18H1_2": continue if itrial.stem == "GeoAH18H2_3": continue if itrial.stem == "GeoAH6H1_2": continue if itrial.stem == "YoaBH12H2_3": idx = np.array([[1500, 7137]]) if itrial.stem == "YoaBH12H3_1": idx = np.array([[1395, 7000]]) if itrial.stem == "NemKH12H1_2": continue if itrial.stem == "NemKH12H1_3": continue if itrial.stem == "NemKH12H2_2": continue if itrial.stem == "NemKH18H2_3": continue if itrial.stem == "NemKH6H1_1": continue if itrial.stem == "NemKH6H1_2": continue if itrial.stem == "NemKH6H1_3": continue if itrial.stem == "NemKH6H2_3": continue if itrial.stem == "MatRH18H1_2": idx = np.array([[1259, 7000]]) if itrial.stem == "MatRH6H1_2": idx = np.array([[1000, 6000]]) if itrial.stem == "JawRH12H1_3": continue if itrial.stem == "JawRH12H2_1": continue if itrial.stem == "JawRH12H3_2": continue if itrial.stem == "JawRH12H3_3": continue if itrial.stem == "JawRH12H4_1": continue if itrial.stem == "JawRH18H4_3": idx = np.array([[1259, 6965]]) if itrial.stem == "JawRH18H4_3": idx = np.array([[1000, 7150]]) if itrial.stem == "JawRH18H4_3": idx = np.array([[1000, 7150]]) if itrial.stem == "JawRH6H2_3": idx = np.array([[1000, 7150]]) if itrial.stem == "PhiIH18H4_3": idx = np.array([[1825, 7550]]) if idx.shape[0] > 1: raise ValueError("more than one onset") ten_percents = int(forces.shape[-1] * 0.08) if idx[0][0] < ten_percents and itrial.stem not in [ "AmiAF12H2_1", "GeoAH18H4_2", "NemKH18H1_3", "NemKH18H2_1", ]: raise ValueError( f"onset is less than 8% of the trial ({idx[0][0] / forces.shape[-1] * 100:2f}%)" ) ninety_percents = int(forces.shape[-1] * 0.97) if idx[0][1] > ninety_percents and itrial.stem not in [ "FabDH12H5_2", "DamGH18H6_2", "PhiIH18H1_1", "PhiIH18H4_2", "PhiIH18H4_3", ]: raise ValueError( f"onset is less than 97% of the trial ({idx[0][1] / forces.shape[-1] * 100:.2f}%)" ) _, ax = plt.subplots(nrows=1, ncols=1) norm.plot(ax=ax) for (inf, sup) in idx: ax.axvline(x=inf, color="g", lw=2, ls="--") ax.axvline(x=sup, color="r", lw=2, ls="--") plt.title(itrial.stem) plt.show() forces.get_labels = params["forces_labels"] sto_filename = ( f"{conf.project_path / iparticipant / "0_forces" / itrial.stem}.sto" ) forces.to_sto(filename=sto_filename) # add onset & offset in configuration onset = idx[0][0] / forces.get_rate offset = idx[0][1] / forces.get_rate conf.add_conf_field({iparticipant: {"onset": {itrial.stem: [onset, offset]}}})
""" Export forces to sto """ from pathlib import Path import matplotlib.pyplot as plt import numpy as np import yaml from pyosim import Conf from pyosim import Analogs3dOsim aws_conf = yaml.safe_load(open("../conf.yml")) local_or_distant = "distant" if aws_conf["distant_id"]["enable"] else "local" conf = Conf(project_path=aws_conf["path"]["project"][local_or_distant]) participants = conf.get_participants_to_process() calibration_matrix = np.genfromtxt( conf.project_path / "forces_calibration_matrix.csv", delimiter="," ) params = { "low_pass_cutoff": 30, "order": 4, "forces_labels": conf.get_conf_field( participant=participants[0], field=["analogs", "targets"] ), } for i, iparticipant in enumerate(participants[:]): print(f"\nparticipant #{i}: {iparticipant}") directories = conf.get_conf_field( participant=iparticipant, field=["analogs", "data"] ) assigned = conf.get_conf_field( participant=iparticipant, field=["analogs", "assigned"] ) for itrial in Path(directories[0]).glob("*.c3d"): # try participant's channel assignment for iassign in assigned: # get index where assignment are empty nan_idx = [i for i, v in enumerate(iassign) if not v] if nan_idx: iassign_without_nans = [i for i in iassign if i] else: iassign_without_nans = iassign try: forces = Analogs3dOsim.from_c3d( itrial, names=iassign_without_nans, prefix=":" ) # Analogs3dOsim.from_c3d(itrial).get_labels if nan_idx: forces.get_nan_idx = np.array(nan_idx) # if there is any empty assignment, fill the dimension with nan for i in nan_idx: forces = np.insert(forces, i, np.nan, axis=1) print(f"\t{itrial.stem} (NaNs: {nan_idx})") else: print(f"\t{itrial.stem}") # check if dimensions are ok if not forces.shape[1] == len(iassign): raise ValueError("Wrong dimensions") break except ValueError: forces = [] # check if there is empty frames nan_rows = np.isnan(forces).any(axis=1).ravel() print( f"\t\tremoving {nan_rows.sum()} nan frames (indices: {np.argwhere(nan_rows)})" ) forces = forces[..., ~nan_rows] # processing (offset during the first second, calibration, low pass) forces = ( forces.center( mu=np.nanmedian(forces[..., 10 : int(forces.get_rate)], axis=-1), axis=-1, ) .squeeze() .T.matmul(calibration_matrix.T) .low_pass( freq=forces.get_rate, order=params["order"], cutoff=params["low_pass_cutoff"], ) .dot(-1) ) norm = Analogs3dOsim(forces[0, :3, :].norm(axis=0).reshape(1, 1, -1)) idx = norm[0, 0, :].detect_onset( threshold=5, above=int(forces.get_rate) / 2, below=1000 # 5 Newtons ) # Special cases if itrial.stem == "MarSF12H4_1": idx[0][1] = 11983 if itrial.stem == "MarSF6H4_1": idx[0][1] = 10672 if itrial.stem == "GatBH18H4_2": idx[0][1] = 17122 if itrial.stem == "GatBH18H4_2": idx[0][1] = 17122 if itrial.stem == "GatBH18H4_3": idx = np.array([[5271, 15965]]) if itrial.stem == "CamBF12H5_3": continue if itrial.stem == "EveDF12H1_2": idx = np.array([[1229, 5549]]) if itrial.stem == "SamNF12H5_2": idx = np.array([[3483, 14498]]) if itrial.stem == "SamNF6H3_1": idx = np.array([[3698, 12314]]) if itrial.stem == "AimQF12H3_1": idx = np.array([[4041, 10328]]) if itrial.stem == "AleBH18H6_3": idx = np.array([[2279, 11058]]) if itrial.stem == "AmiAF12H6_3": idx = np.array([[6146, 16873]]) if itrial.stem == "CarBF12H6_3": idx = np.array([[1649, 10415]]) if itrial.stem == "AnnSF6H2_3": continue if itrial.stem == "SteBF6H2_2": continue if itrial.stem == "SteBF6H3_1": idx = np.array([[2591, 8100]]) if itrial.stem == "RoxDF6H6_1": idx = np.array([[2883, 9514]]) if itrial.stem == "RoxDF6H6_2": idx = np.array([[2883, 9514]]) if itrial.stem == "GeoAH12H1_2": idx = np.array([[1110, 7764]]) if itrial.stem == "GeoAH12H2_1": idx = np.array([[1136, 9211]]) if itrial.stem == "GeoAH18H1_2": continue if itrial.stem == "GeoAH18H2_3": continue if itrial.stem == "GeoAH6H1_2": continue if itrial.stem == "YoaBH12H2_3": idx = np.array([[1500, 7137]]) if itrial.stem == "YoaBH12H3_1": idx = np.array([[1395, 7000]]) if itrial.stem == "NemKH12H1_2": continue if itrial.stem == "NemKH12H1_3": continue if itrial.stem == "NemKH12H2_2": continue if itrial.stem == "NemKH18H2_3": continue if itrial.stem == "NemKH6H1_1": continue if itrial.stem == "NemKH6H1_2": continue if itrial.stem == "NemKH6H1_3": continue if itrial.stem == "NemKH6H2_3": continue if itrial.stem == "MatRH18H1_2": idx = np.array([[1259, 7000]]) if itrial.stem == "MatRH6H1_2": idx = np.array([[1000, 6000]]) if itrial.stem == "JawRH12H1_3": continue if itrial.stem == "JawRH12H2_1": continue if itrial.stem == "JawRH12H3_2": continue if itrial.stem == "JawRH12H3_3": continue if itrial.stem == "JawRH12H4_1": continue if itrial.stem == "JawRH18H4_3": idx = np.array([[1259, 6965]]) if itrial.stem == "JawRH18H4_3": idx = np.array([[1000, 7150]]) if itrial.stem == "JawRH18H4_3": idx = np.array([[1000, 7150]]) if itrial.stem == "JawRH6H2_3": idx = np.array([[1000, 7150]]) if itrial.stem == "PhiIH18H4_3": idx = np.array([[1825, 7550]]) if idx.shape[0] > 1: raise ValueError("more than one onset") ten_percents = int(forces.shape[-1] * 0.08) if idx[0][0] < ten_percents and itrial.stem not in [ "AmiAF12H2_1", "GeoAH18H4_2", "NemKH18H1_3", "NemKH18H2_1", ]: raise ValueError( f"onset is less than 8% of the trial ({idx[0][0] / forces.shape[-1] * 100:2f}%)" ) ninety_percents = int(forces.shape[-1] * 0.97) if idx[0][1] > ninety_percents and itrial.stem not in [ "FabDH12H5_2", "DamGH18H6_2", "PhiIH18H1_1", "PhiIH18H4_2", "PhiIH18H4_3", ]: raise ValueError( f"onset is less than 97% of the trial ({idx[0][1] / forces.shape[-1] * 100:.2f}%)" ) _, ax = plt.subplots(nrows=1, ncols=1) norm.plot(ax=ax) for (inf, sup) in idx: ax.axvline(x=inf, color="g", lw=2, ls="--") ax.axvline(x=sup, color="r", lw=2, ls="--") plt.title(itrial.stem) plt.show() forces.get_labels = params["forces_labels"] sto_filename = ( f"{conf.project_path / iparticipant / '0_forces' / itrial.stem}.sto" ) forces.to_sto(filename=sto_filename) # add onset & offset in configuration onset = idx[0][0] / forces.get_rate offset = idx[0][1] / forces.get_rate conf.add_conf_field({iparticipant: {"onset": {itrial.stem: [onset, offset]}}})
# Copyright 2020-2021 Huawei Technologies Co., Ltd # # 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. # ============================================================================ """pooling""" from mindspore.ops import operations as P from mindspore.ops import functional as F from mindspore._checkparam import Rel, Validator as validator from mindspore.ops.primitive import constexpr import mindspore.context as context from ..cell import Cell __all__ = ['AvgPool2d', 'MaxPool2d', 'AvgPool1d', 'MaxPool1d'] class _PoolNd(Cell): """N-D AvgPool""" def __init__(self, kernel_size, stride, pad_mode, data_format="NCHW"): """Initialize _PoolNd.""" super(_PoolNd, self).__init__() self.pad_mode = validator.check_string(pad_mode.upper(), ['VALID', 'SAME'], 'pad_mode', self.cls_name) self.format = validator.check_string(data_format, ['NCHW', 'NHWC'], 'format', self.cls_name) if context.get_context("device_target") != "GPU" and self.format == "NHWC": raise ValueError(f"For '{self.cls_name}, the 'NHWC' format only support in GPU target, but got device " f"target {context.get_context("device_target")}.") def _check_int_or_tuple(arg_name, arg_value): validator.check_value_type(arg_name, arg_value, [int, tuple], self.cls_name) error_msg = f"For '{self.cls_name}', the '{arg_name}' should be an positive int number or " \ f"a tuple of two positive int numbers, but got {arg_value}" if isinstance(arg_value, int): if arg_value <= 0: raise ValueError(error_msg) elif len(arg_value) == 2: for item in arg_value: if isinstance(item, int) and item > 0: continue raise ValueError(error_msg) else: raise ValueError(error_msg) return arg_value self.kernel_size = _check_int_or_tuple('kernel_size', kernel_size) self.stride = _check_int_or_tuple('stride', stride) def construct(self, *inputs): pass def extend_repr(self): return 'kernel_size={kernel_size}, stride={stride}, pad_mode={pad_mode}'.format(**self.__dict__) @constexpr def _shape_check(in_shape, prim_name=None): msg_prefix = f"For '{prim_name}', the" if prim_name else "The" if len(in_shape) != 3: raise ValueError(f"{msg_prefix} input must has 3 dim, but got {len(in_shape)}") class MaxPool2d(_PoolNd): r""" 2D max pooling operation for temporal data. Applies a 2D max pooling over an input Tensor which can be regarded as a composition of 2D planes. Typically the input is of shape :math:`(N_{in}, C_{in}, H_{in}, W_{in})`, MaxPool2d outputs regional maximum in the :math:`(H_{in}, W_{in})`-dimension. Given kernel size :math:`ks = (h_{ker}, w_{ker})` and stride :math:`s = (s_0, s_1)`, the operation is as follows. .. math:: \text{output}(N_i, C_j, h, w) = \max_{m=0, \ldots, h_{ker}-1} \max_{n=0, \ldots, w_{ker}-1} \text{input}(N_i, C_j, s_0 \times h + m, s_1 \times w + n) Note: pad_mode for training only supports "same" and "valid". Args: kernel_size (Union[int, tuple[int]]): The size of kernel used to take the max value, is an int number that represents height and width are both kernel_size, or a tuple of two int numbers that represent height and width respectively. Default: 1. stride (Union[int, tuple[int]]): The distance of kernel moving, an int number that represents the height and width of movement are both strides, or a tuple of two int numbers that represent height and width of movement respectively. Default: 1. pad_mode (str): The optional value for pad mode, is "same" or "valid", not case sensitive. Default: "valid". - same: Adopts the way of completion. The height and width of the output will be the same as the input. The total number of padding will be calculated in horizontal and vertical directions and evenly distributed to top and bottom, left and right if possible. Otherwise, the last extra padding will be done from the bottom and the right side. - valid: Adopts the way of discarding. The possible largest height and width of output will be returned without padding. Extra pixels will be discarded. data_format (str): The optional value for data format, is 'NHWC' or 'NCHW'. Default: 'NCHW'. Inputs: - **x** (Tensor) - Tensor of shape :math:`(N, C_{in}, H_{in}, W_{in})`. Outputs: Tensor of shape :math:`(N, C_{out}, H_{out}, W_{out})`. Raises: TypeError: If `kernel_size` or `strides` is neither int nor tuple. ValueError: If `pad_mode` is neither 'valid' nor 'same' with not case sensitive. ValueError: If `data_format` is neither 'NCHW' nor 'NHWC'. ValueError: If `kernel_size` or `strides` is less than 1. ValueError: If length of shape of `x` is not equal to 4. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> pool = nn.MaxPool2d(kernel_size=3, stride=1) >>> x = Tensor(np.random.randint(0, 10, [1, 2, 4, 4]), mindspore.float32) >>> output = pool(x) >>> print(output.shape) (1, 2, 2, 2) """ def __init__(self, kernel_size=1, stride=1, pad_mode="valid", data_format="NCHW"): """Initialize MaxPool2d.""" super(MaxPool2d, self).__init__(kernel_size, stride, pad_mode, data_format) self.max_pool = P.MaxPool(kernel_size=self.kernel_size, strides=self.stride, pad_mode=self.pad_mode, data_format=self.format) def construct(self, x): out = self.max_pool(x) return out class MaxPool1d(_PoolNd): r""" 1D max pooling operation for temporal data. Applies a 1D max pooling over an input Tensor which can be regarded as a composition of 1D planes. Typically the input is of shape :math:`(N_{in}, C_{in}, L_{in})`, MaxPool1d outputs regional maximum in the :math:`(L_{in})`-dimension. Given kernel size :math:`ks = (l_{ker})` and stride :math:`s = (s_0)`, the operation is as follows. .. math:: \text{output}(N_i, C_j, l) = \max_{n=0, \ldots, l_{ker}-1} \text{input}(N_i, C_j, s_0 \times l + n) Note: pad_mode for training only supports "same" and "valid". Args: kernel_size (int): The size of kernel used to take the max value, Default: 1. stride (int): The distance of kernel moving, an int number that represents the width of movement is stride, Default: 1. pad_mode (str): The optional value for pad mode, is "same" or "valid", not case sensitive. Default: "valid". - same: Adopts the way of completion. The total number of padding will be calculated in horizontal and vertical directions and evenly distributed to top and bottom, left and right if possible. Otherwise, the last extra padding will be done from the bottom and the right side. - valid: Adopts the way of discarding. The possible largest height and width of output will be returned without padding. Extra pixels will be discarded. Inputs: - **x** (Tensor) - Tensor of shape :math:`(N, C, L_{in})`. Outputs: Tensor of shape :math:`(N, C, L_{out})`. Raises: TypeError: If `kernel_size` or `strides` is not an int. ValueError: If `pad_mode` is neither 'valid' nor 'same' with not case sensitive. ValueError: If `data_format` is neither 'NCHW' nor 'NHWC'. ValueError: If `kernel_size` or `strides` is less than 1. ValueError: If length of shape of `x` is not equal to 4. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> max_pool = nn.MaxPool1d(kernel_size=3, stride=1) >>> x = Tensor(np.random.randint(0, 10, [1, 2, 4]), mindspore.float32) >>> output = max_pool(x) >>> result = output.shape >>> print(result) (1, 2, 2) """ def __init__(self, kernel_size=1, stride=1, pad_mode="valid"): """Initialize MaxPool1d.""" super(MaxPool1d, self).__init__(kernel_size, stride, pad_mode) validator.check_value_type('kernel_size', kernel_size, [int], self.cls_name) validator.check_value_type('stride', stride, [int], self.cls_name) self.pad_mode = validator.check_string(pad_mode.upper(), ['VALID', 'SAME'], 'pad_mode', self.cls_name) validator.check_int(kernel_size, 1, Rel.GE, "kernel_size", self.cls_name) validator.check_int(stride, 1, Rel.GE, "stride", self.cls_name) self.kernel_size = (1, kernel_size) self.stride = (1, stride) self.max_pool = P.MaxPool(kernel_size=self.kernel_size, strides=self.stride, pad_mode=self.pad_mode) self.shape = F.shape self.reduce_mean = P.ReduceMean(keep_dims=True) self.expand = P.ExpandDims() self.squeeze = P.Squeeze(2) def construct(self, x): _shape_check(self.shape(x), self.cls_name) x = self.expand(x, 2) output = self.max_pool(x) output = self.squeeze(output) return output class AvgPool2d(_PoolNd): r""" 2D average pooling for temporal data. Applies a 2D average pooling over an input Tensor which can be regarded as a composition of 2D input planes. Typically the input is of shape :math:`(N_{in}, C_{in}, H_{in}, W_{in})`, AvgPool2d outputs regional average in the :math:`(H_{in}, W_{in})`-dimension. Given kernel size :math:`ks = (h_{ker}, w_{ker})` and stride :math:`s = (s_0, s_1)`, the operation is as follows. .. math:: \text{output}(N_i, C_j, h, w) = \frac{1}{h_{ker} * w_{ker}} \sum_{m=0}^{h_{ker}-1} \sum_{n=0}^{w_{ker}-1} \text{input}(N_i, C_j, s_0 \times h + m, s_1 \times w + n) Note: pad_mode for training only supports "same" and "valid". Args: kernel_size (Union[int, tuple[int]]): The size of kernel used to take the average value. The data type of kernel_size must be int and the value represents the height and width, or a tuple of two int numbers that represent height and width respectively. Default: 1. stride (Union[int, tuple[int]]): The distance of kernel moving, an int number that represents the height and width of movement are both strides, or a tuple of two int numbers that represent height and width of movement respectively. Default: 1. pad_mode (str): The optional value for pad mode, is "same" or "valid", not case sensitive. Default: "valid". - same: Adopts the way of completion. The height and width of the output will be the same as the input. The total number of padding will be calculated in horizontal and vertical directions and evenly distributed to top and bottom, left and right if possible. Otherwise, the last extra padding will be done from the bottom and the right side. - valid: Adopts the way of discarding. The possible largest height and width of output will be returned without padding. Extra pixels will be discarded. data_format (str): The optional value for data format, is 'NHWC' or 'NCHW'. Default: 'NCHW'. Inputs: - **x** (Tensor) - Tensor of shape :math:`(N, C_{in}, H_{in}, W_{in})`. Outputs: Tensor of shape :math:`(N, C_{out}, H_{out}, W_{out})`. Raises: TypeError: If `kernel_size` or `strides` is neither int nor tuple. ValueError: If `pad_mode` is neither 'valid' nor 'same' with not case sensitive. ValueError: If `data_format` is neither 'NCHW' nor 'NHWC'. ValueError: If `kernel_size` or `strides` is less than 1. ValueError: If length of shape of `x` is not equal to 4. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> pool = nn.AvgPool2d(kernel_size=3, stride=1) >>> x = Tensor(np.random.randint(0, 10, [1, 2, 4, 4]), mindspore.float32) >>> output = pool(x) >>> print(output.shape) (1, 2, 2, 2) """ def __init__(self, kernel_size=1, stride=1, pad_mode="valid", data_format="NCHW"): """Initialize AvgPool2d.""" super(AvgPool2d, self).__init__(kernel_size, stride, pad_mode, data_format) self.avg_pool = P.AvgPool(kernel_size=self.kernel_size, strides=self.stride, pad_mode=self.pad_mode, data_format=self.format) def construct(self, x): return self.avg_pool(x) class AvgPool1d(_PoolNd): r""" 1D average pooling for temporal data. Applies a 1D average pooling over an input Tensor which can be regarded as a composition of 1D input planes. Typically the input is of shape :math:`(N_{in}, C_{in}, L_{in})`, AvgPool1d outputs regional average in the :math:`(L_{in})`-dimension. Given kernel size :math:`ks = l_{ker}` and stride :math:`s = s_0`, the operation is as follows. .. math:: \text{output}(N_i, C_j, l) = \frac{1}{l_{ker}} \sum_{n=0}^{l_{ker}-1} \text{input}(N_i, C_j, s_0 \times l + n) Note: pad_mode for training only supports "same" and "valid". Args: kernel_size (int): The size of kernel window used to take the average value, Default: 1. stride (int): The distance of kernel moving, an int number that represents the width of movement is strides, Default: 1. pad_mode (str): The optional value for pad mode, is "same" or "valid", not case sensitive. Default: "valid". - same: Adopts the way of completion. The height and width of the output will be the same as the input. The total number of padding will be calculated in horizontal and vertical directions and evenly distributed to top and bottom, left and right if possible. Otherwise, the last extra padding will be done from the bottom and the right side. - valid: Adopts the way of discarding. The possible largest height and width of output will be returned without padding. Extra pixels will be discarded. Inputs: - **x** (Tensor) - Tensor of shape :math:`(N, C_{in}, L_{in})`. Outputs: Tensor of shape :math:`(N, C_{out}, L_{out})`. Raises: TypeError: If `kernel_size` or `stride` is not an int. ValueError: If `pad_mode` is neither 'same' nor 'valid' with not case sensitive. ValueError: If `kernel_size` or `strides` is less than 1. ValueError: If length of shape of `x` is not equal to 3. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> pool = nn.AvgPool1d(kernel_size=6, stride=1) >>> x = Tensor(np.random.randint(0, 10, [1, 3, 6]), mindspore.float32) >>> output = pool(x) >>> result = output.shape >>> print(result) (1, 3, 1) """ def __init__(self, kernel_size=1, stride=1, pad_mode="valid"): """Initialize AvgPool1d.""" validator.check_value_type('kernel_size', kernel_size, [int], self.cls_name) validator.check_value_type('stride', stride, [int], self.cls_name) self.pad_mode = validator.check_string(pad_mode.upper(), ['VALID', 'SAME'], 'pad_mode', self.cls_name) validator.check_int(kernel_size, 1, Rel.GE, "kernel_size", self.cls_name) validator.check_int(stride, 1, Rel.GE, "stride", self.cls_name) super(AvgPool1d, self).__init__(kernel_size, stride, pad_mode) self.kernel_size = (1, kernel_size) self.stride = (1, stride) self.avg_pool = P.AvgPool(kernel_size=self.kernel_size, strides=self.stride, pad_mode=self.pad_mode) self.shape = F.shape self.reduce_mean = P.ReduceMean(keep_dims=True) self.slice = P.Slice() self.expand = P.ExpandDims() self.squeeze = P.Squeeze(2) def construct(self, x): x = F.depend(x, _shape_check(self.shape(x), self.cls_name)) batch, channel, width = self.shape(x) if width == self.kernel_size[1]: x = self.reduce_mean(x, 2) elif width - self.kernel_size[1] < self.stride[1]: x = self.slice(x, (0, 0, 0), (batch, channel, self.kernel_size[1])) x = self.reduce_mean(x, 2) else: x = self.expand(x, 2) x = self.avg_pool(x) x = self.squeeze(x) return x
# Copyright 2020-2021 Huawei Technologies Co., Ltd # # 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. # ============================================================================ """pooling""" from mindspore.ops import operations as P from mindspore.ops import functional as F from mindspore._checkparam import Rel, Validator as validator from mindspore.ops.primitive import constexpr import mindspore.context as context from ..cell import Cell __all__ = ['AvgPool2d', 'MaxPool2d', 'AvgPool1d', 'MaxPool1d'] class _PoolNd(Cell): """N-D AvgPool""" def __init__(self, kernel_size, stride, pad_mode, data_format="NCHW"): """Initialize _PoolNd.""" super(_PoolNd, self).__init__() self.pad_mode = validator.check_string(pad_mode.upper(), ['VALID', 'SAME'], 'pad_mode', self.cls_name) self.format = validator.check_string(data_format, ['NCHW', 'NHWC'], 'format', self.cls_name) if context.get_context("device_target") != "GPU" and self.format == "NHWC": raise ValueError(f"For '{self.cls_name}, the 'NHWC' format only support in GPU target, but got device " f"target {context.get_context('device_target')}.") def _check_int_or_tuple(arg_name, arg_value): validator.check_value_type(arg_name, arg_value, [int, tuple], self.cls_name) error_msg = f"For '{self.cls_name}', the '{arg_name}' should be an positive int number or " \ f"a tuple of two positive int numbers, but got {arg_value}" if isinstance(arg_value, int): if arg_value <= 0: raise ValueError(error_msg) elif len(arg_value) == 2: for item in arg_value: if isinstance(item, int) and item > 0: continue raise ValueError(error_msg) else: raise ValueError(error_msg) return arg_value self.kernel_size = _check_int_or_tuple('kernel_size', kernel_size) self.stride = _check_int_or_tuple('stride', stride) def construct(self, *inputs): pass def extend_repr(self): return 'kernel_size={kernel_size}, stride={stride}, pad_mode={pad_mode}'.format(**self.__dict__) @constexpr def _shape_check(in_shape, prim_name=None): msg_prefix = f"For '{prim_name}', the" if prim_name else "The" if len(in_shape) != 3: raise ValueError(f"{msg_prefix} input must has 3 dim, but got {len(in_shape)}") class MaxPool2d(_PoolNd): r""" 2D max pooling operation for temporal data. Applies a 2D max pooling over an input Tensor which can be regarded as a composition of 2D planes. Typically the input is of shape :math:`(N_{in}, C_{in}, H_{in}, W_{in})`, MaxPool2d outputs regional maximum in the :math:`(H_{in}, W_{in})`-dimension. Given kernel size :math:`ks = (h_{ker}, w_{ker})` and stride :math:`s = (s_0, s_1)`, the operation is as follows. .. math:: \text{output}(N_i, C_j, h, w) = \max_{m=0, \ldots, h_{ker}-1} \max_{n=0, \ldots, w_{ker}-1} \text{input}(N_i, C_j, s_0 \times h + m, s_1 \times w + n) Note: pad_mode for training only supports "same" and "valid". Args: kernel_size (Union[int, tuple[int]]): The size of kernel used to take the max value, is an int number that represents height and width are both kernel_size, or a tuple of two int numbers that represent height and width respectively. Default: 1. stride (Union[int, tuple[int]]): The distance of kernel moving, an int number that represents the height and width of movement are both strides, or a tuple of two int numbers that represent height and width of movement respectively. Default: 1. pad_mode (str): The optional value for pad mode, is "same" or "valid", not case sensitive. Default: "valid". - same: Adopts the way of completion. The height and width of the output will be the same as the input. The total number of padding will be calculated in horizontal and vertical directions and evenly distributed to top and bottom, left and right if possible. Otherwise, the last extra padding will be done from the bottom and the right side. - valid: Adopts the way of discarding. The possible largest height and width of output will be returned without padding. Extra pixels will be discarded. data_format (str): The optional value for data format, is 'NHWC' or 'NCHW'. Default: 'NCHW'. Inputs: - **x** (Tensor) - Tensor of shape :math:`(N, C_{in}, H_{in}, W_{in})`. Outputs: Tensor of shape :math:`(N, C_{out}, H_{out}, W_{out})`. Raises: TypeError: If `kernel_size` or `strides` is neither int nor tuple. ValueError: If `pad_mode` is neither 'valid' nor 'same' with not case sensitive. ValueError: If `data_format` is neither 'NCHW' nor 'NHWC'. ValueError: If `kernel_size` or `strides` is less than 1. ValueError: If length of shape of `x` is not equal to 4. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> pool = nn.MaxPool2d(kernel_size=3, stride=1) >>> x = Tensor(np.random.randint(0, 10, [1, 2, 4, 4]), mindspore.float32) >>> output = pool(x) >>> print(output.shape) (1, 2, 2, 2) """ def __init__(self, kernel_size=1, stride=1, pad_mode="valid", data_format="NCHW"): """Initialize MaxPool2d.""" super(MaxPool2d, self).__init__(kernel_size, stride, pad_mode, data_format) self.max_pool = P.MaxPool(kernel_size=self.kernel_size, strides=self.stride, pad_mode=self.pad_mode, data_format=self.format) def construct(self, x): out = self.max_pool(x) return out class MaxPool1d(_PoolNd): r""" 1D max pooling operation for temporal data. Applies a 1D max pooling over an input Tensor which can be regarded as a composition of 1D planes. Typically the input is of shape :math:`(N_{in}, C_{in}, L_{in})`, MaxPool1d outputs regional maximum in the :math:`(L_{in})`-dimension. Given kernel size :math:`ks = (l_{ker})` and stride :math:`s = (s_0)`, the operation is as follows. .. math:: \text{output}(N_i, C_j, l) = \max_{n=0, \ldots, l_{ker}-1} \text{input}(N_i, C_j, s_0 \times l + n) Note: pad_mode for training only supports "same" and "valid". Args: kernel_size (int): The size of kernel used to take the max value, Default: 1. stride (int): The distance of kernel moving, an int number that represents the width of movement is stride, Default: 1. pad_mode (str): The optional value for pad mode, is "same" or "valid", not case sensitive. Default: "valid". - same: Adopts the way of completion. The total number of padding will be calculated in horizontal and vertical directions and evenly distributed to top and bottom, left and right if possible. Otherwise, the last extra padding will be done from the bottom and the right side. - valid: Adopts the way of discarding. The possible largest height and width of output will be returned without padding. Extra pixels will be discarded. Inputs: - **x** (Tensor) - Tensor of shape :math:`(N, C, L_{in})`. Outputs: Tensor of shape :math:`(N, C, L_{out})`. Raises: TypeError: If `kernel_size` or `strides` is not an int. ValueError: If `pad_mode` is neither 'valid' nor 'same' with not case sensitive. ValueError: If `data_format` is neither 'NCHW' nor 'NHWC'. ValueError: If `kernel_size` or `strides` is less than 1. ValueError: If length of shape of `x` is not equal to 4. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> max_pool = nn.MaxPool1d(kernel_size=3, stride=1) >>> x = Tensor(np.random.randint(0, 10, [1, 2, 4]), mindspore.float32) >>> output = max_pool(x) >>> result = output.shape >>> print(result) (1, 2, 2) """ def __init__(self, kernel_size=1, stride=1, pad_mode="valid"): """Initialize MaxPool1d.""" super(MaxPool1d, self).__init__(kernel_size, stride, pad_mode) validator.check_value_type('kernel_size', kernel_size, [int], self.cls_name) validator.check_value_type('stride', stride, [int], self.cls_name) self.pad_mode = validator.check_string(pad_mode.upper(), ['VALID', 'SAME'], 'pad_mode', self.cls_name) validator.check_int(kernel_size, 1, Rel.GE, "kernel_size", self.cls_name) validator.check_int(stride, 1, Rel.GE, "stride", self.cls_name) self.kernel_size = (1, kernel_size) self.stride = (1, stride) self.max_pool = P.MaxPool(kernel_size=self.kernel_size, strides=self.stride, pad_mode=self.pad_mode) self.shape = F.shape self.reduce_mean = P.ReduceMean(keep_dims=True) self.expand = P.ExpandDims() self.squeeze = P.Squeeze(2) def construct(self, x): _shape_check(self.shape(x), self.cls_name) x = self.expand(x, 2) output = self.max_pool(x) output = self.squeeze(output) return output class AvgPool2d(_PoolNd): r""" 2D average pooling for temporal data. Applies a 2D average pooling over an input Tensor which can be regarded as a composition of 2D input planes. Typically the input is of shape :math:`(N_{in}, C_{in}, H_{in}, W_{in})`, AvgPool2d outputs regional average in the :math:`(H_{in}, W_{in})`-dimension. Given kernel size :math:`ks = (h_{ker}, w_{ker})` and stride :math:`s = (s_0, s_1)`, the operation is as follows. .. math:: \text{output}(N_i, C_j, h, w) = \frac{1}{h_{ker} * w_{ker}} \sum_{m=0}^{h_{ker}-1} \sum_{n=0}^{w_{ker}-1} \text{input}(N_i, C_j, s_0 \times h + m, s_1 \times w + n) Note: pad_mode for training only supports "same" and "valid". Args: kernel_size (Union[int, tuple[int]]): The size of kernel used to take the average value. The data type of kernel_size must be int and the value represents the height and width, or a tuple of two int numbers that represent height and width respectively. Default: 1. stride (Union[int, tuple[int]]): The distance of kernel moving, an int number that represents the height and width of movement are both strides, or a tuple of two int numbers that represent height and width of movement respectively. Default: 1. pad_mode (str): The optional value for pad mode, is "same" or "valid", not case sensitive. Default: "valid". - same: Adopts the way of completion. The height and width of the output will be the same as the input. The total number of padding will be calculated in horizontal and vertical directions and evenly distributed to top and bottom, left and right if possible. Otherwise, the last extra padding will be done from the bottom and the right side. - valid: Adopts the way of discarding. The possible largest height and width of output will be returned without padding. Extra pixels will be discarded. data_format (str): The optional value for data format, is 'NHWC' or 'NCHW'. Default: 'NCHW'. Inputs: - **x** (Tensor) - Tensor of shape :math:`(N, C_{in}, H_{in}, W_{in})`. Outputs: Tensor of shape :math:`(N, C_{out}, H_{out}, W_{out})`. Raises: TypeError: If `kernel_size` or `strides` is neither int nor tuple. ValueError: If `pad_mode` is neither 'valid' nor 'same' with not case sensitive. ValueError: If `data_format` is neither 'NCHW' nor 'NHWC'. ValueError: If `kernel_size` or `strides` is less than 1. ValueError: If length of shape of `x` is not equal to 4. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> pool = nn.AvgPool2d(kernel_size=3, stride=1) >>> x = Tensor(np.random.randint(0, 10, [1, 2, 4, 4]), mindspore.float32) >>> output = pool(x) >>> print(output.shape) (1, 2, 2, 2) """ def __init__(self, kernel_size=1, stride=1, pad_mode="valid", data_format="NCHW"): """Initialize AvgPool2d.""" super(AvgPool2d, self).__init__(kernel_size, stride, pad_mode, data_format) self.avg_pool = P.AvgPool(kernel_size=self.kernel_size, strides=self.stride, pad_mode=self.pad_mode, data_format=self.format) def construct(self, x): return self.avg_pool(x) class AvgPool1d(_PoolNd): r""" 1D average pooling for temporal data. Applies a 1D average pooling over an input Tensor which can be regarded as a composition of 1D input planes. Typically the input is of shape :math:`(N_{in}, C_{in}, L_{in})`, AvgPool1d outputs regional average in the :math:`(L_{in})`-dimension. Given kernel size :math:`ks = l_{ker}` and stride :math:`s = s_0`, the operation is as follows. .. math:: \text{output}(N_i, C_j, l) = \frac{1}{l_{ker}} \sum_{n=0}^{l_{ker}-1} \text{input}(N_i, C_j, s_0 \times l + n) Note: pad_mode for training only supports "same" and "valid". Args: kernel_size (int): The size of kernel window used to take the average value, Default: 1. stride (int): The distance of kernel moving, an int number that represents the width of movement is strides, Default: 1. pad_mode (str): The optional value for pad mode, is "same" or "valid", not case sensitive. Default: "valid". - same: Adopts the way of completion. The height and width of the output will be the same as the input. The total number of padding will be calculated in horizontal and vertical directions and evenly distributed to top and bottom, left and right if possible. Otherwise, the last extra padding will be done from the bottom and the right side. - valid: Adopts the way of discarding. The possible largest height and width of output will be returned without padding. Extra pixels will be discarded. Inputs: - **x** (Tensor) - Tensor of shape :math:`(N, C_{in}, L_{in})`. Outputs: Tensor of shape :math:`(N, C_{out}, L_{out})`. Raises: TypeError: If `kernel_size` or `stride` is not an int. ValueError: If `pad_mode` is neither 'same' nor 'valid' with not case sensitive. ValueError: If `kernel_size` or `strides` is less than 1. ValueError: If length of shape of `x` is not equal to 3. Supported Platforms: ``Ascend`` ``GPU`` ``CPU`` Examples: >>> pool = nn.AvgPool1d(kernel_size=6, stride=1) >>> x = Tensor(np.random.randint(0, 10, [1, 3, 6]), mindspore.float32) >>> output = pool(x) >>> result = output.shape >>> print(result) (1, 3, 1) """ def __init__(self, kernel_size=1, stride=1, pad_mode="valid"): """Initialize AvgPool1d.""" validator.check_value_type('kernel_size', kernel_size, [int], self.cls_name) validator.check_value_type('stride', stride, [int], self.cls_name) self.pad_mode = validator.check_string(pad_mode.upper(), ['VALID', 'SAME'], 'pad_mode', self.cls_name) validator.check_int(kernel_size, 1, Rel.GE, "kernel_size", self.cls_name) validator.check_int(stride, 1, Rel.GE, "stride", self.cls_name) super(AvgPool1d, self).__init__(kernel_size, stride, pad_mode) self.kernel_size = (1, kernel_size) self.stride = (1, stride) self.avg_pool = P.AvgPool(kernel_size=self.kernel_size, strides=self.stride, pad_mode=self.pad_mode) self.shape = F.shape self.reduce_mean = P.ReduceMean(keep_dims=True) self.slice = P.Slice() self.expand = P.ExpandDims() self.squeeze = P.Squeeze(2) def construct(self, x): x = F.depend(x, _shape_check(self.shape(x), self.cls_name)) batch, channel, width = self.shape(x) if width == self.kernel_size[1]: x = self.reduce_mean(x, 2) elif width - self.kernel_size[1] < self.stride[1]: x = self.slice(x, (0, 0, 0), (batch, channel, self.kernel_size[1])) x = self.reduce_mean(x, 2) else: x = self.expand(x, 2) x = self.avg_pool(x) x = self.squeeze(x) return x
from typing import Optional import time from datetime import datetime, timedelta from wpwatcher import log from wpwatcher.core import WPWatcher from wpwatcher.config import Config from wpwatcher.report import ScanReport from wpwatcher.site import Site from filelock import FileLock, Timeout # Date format used everywhere DATE_FORMAT = "%Y-%m-%dT%H-%M-%S" class Daemon: """ Daemonizer for `WPWatcher.run_scans`. """ def __init__(self, conf: Config) -> None: self._daemon_loop_sleep = conf['daemon_loop_sleep'] # Make sure the daemon mode is enabled conf['daemon'] = True self.wpwatcher = WPWatcherDaemonMode(conf) self.pidfile = '/tmp/wpwatcher.daemon.pid.lock' self.pidfilelock = FileLock(self.pidfile, timeout=1) self._running: bool = False self._stopping: bool = False self._start_time: Optional[datetime] = None def loop(self, ttl:Optional[timedelta]=None) -> None: """Enter the infinite loop that is calling `WPWatcher.run_scans`. """ self._running = True self._start_time = datetime.now() log.info("Daemon mode selected, looping for ever...") try: with self.pidfilelock: while self._running: # Run scans for ever self.wpwatcher.run_scans() if ttl and datetime.now() - self._start_time > ttl: self._running = False self._stopping = True if not self._stopping: log.info( f"Sleeping {self._daemon_loop_sleep} and scanning again..." ) time.sleep(self._daemon_loop_sleep.total_seconds()) except Timeout as err: log.error("The WPWatcher daemon is already running") raise RuntimeError("The WPWatcher daemon is already running") from err finally: self._running = False self._stopping = False def stop(self) -> None: """Interrupt the scans and stop the loop, do NOT raise SystemExit. """ self._stopping = True self._running = False self.wpwatcher.interrupt_scans() class WPWatcherDaemonMode(WPWatcher): def __init__(self, conf: Config): super().__init__(conf) self._daemon_loop_sleep: timedelta = conf["daemon_loop_sleep"] def _scan_site(self, wp_site: Site) -> Optional[ScanReport]: """Skips the site if it has already been scanned lately. """ last_wp_report = self.wp_reports.find(ScanReport(site=wp_site["url"])) # Skip if the daemon mode is enabled and scan already happend in the last configured `daemon_loop_wait` if last_wp_report and self._skip_this_site(last_wp_report): return None return super()._scan_site(wp_site) def _skip_this_site(self, last_wp_report: ScanReport) -> bool: """Return true if the daemon mode is enabled and scan already happend in the last configured `daemon_loop_wait`""" if ( datetime.now() - datetime.strptime(last_wp_report["datetime"], DATE_FORMAT) < self._daemon_loop_sleep ): log.info( f"Daemon skipping site {last_wp_report["site"]} because already scanned in the last {self._daemon_loop_sleep}" ) return True return False
from typing import Optional import time from datetime import datetime, timedelta from wpwatcher import log from wpwatcher.core import WPWatcher from wpwatcher.config import Config from wpwatcher.report import ScanReport from wpwatcher.site import Site from filelock import FileLock, Timeout # Date format used everywhere DATE_FORMAT = "%Y-%m-%dT%H-%M-%S" class Daemon: """ Daemonizer for `WPWatcher.run_scans`. """ def __init__(self, conf: Config) -> None: self._daemon_loop_sleep = conf['daemon_loop_sleep'] # Make sure the daemon mode is enabled conf['daemon'] = True self.wpwatcher = WPWatcherDaemonMode(conf) self.pidfile = '/tmp/wpwatcher.daemon.pid.lock' self.pidfilelock = FileLock(self.pidfile, timeout=1) self._running: bool = False self._stopping: bool = False self._start_time: Optional[datetime] = None def loop(self, ttl:Optional[timedelta]=None) -> None: """Enter the infinite loop that is calling `WPWatcher.run_scans`. """ self._running = True self._start_time = datetime.now() log.info("Daemon mode selected, looping for ever...") try: with self.pidfilelock: while self._running: # Run scans for ever self.wpwatcher.run_scans() if ttl and datetime.now() - self._start_time > ttl: self._running = False self._stopping = True if not self._stopping: log.info( f"Sleeping {self._daemon_loop_sleep} and scanning again..." ) time.sleep(self._daemon_loop_sleep.total_seconds()) except Timeout as err: log.error("The WPWatcher daemon is already running") raise RuntimeError("The WPWatcher daemon is already running") from err finally: self._running = False self._stopping = False def stop(self) -> None: """Interrupt the scans and stop the loop, do NOT raise SystemExit. """ self._stopping = True self._running = False self.wpwatcher.interrupt_scans() class WPWatcherDaemonMode(WPWatcher): def __init__(self, conf: Config): super().__init__(conf) self._daemon_loop_sleep: timedelta = conf["daemon_loop_sleep"] def _scan_site(self, wp_site: Site) -> Optional[ScanReport]: """Skips the site if it has already been scanned lately. """ last_wp_report = self.wp_reports.find(ScanReport(site=wp_site["url"])) # Skip if the daemon mode is enabled and scan already happend in the last configured `daemon_loop_wait` if last_wp_report and self._skip_this_site(last_wp_report): return None return super()._scan_site(wp_site) def _skip_this_site(self, last_wp_report: ScanReport) -> bool: """Return true if the daemon mode is enabled and scan already happend in the last configured `daemon_loop_wait`""" if ( datetime.now() - datetime.strptime(last_wp_report["datetime"], DATE_FORMAT) < self._daemon_loop_sleep ): log.info( f"Daemon skipping site {last_wp_report['site']} because already scanned in the last {self._daemon_loop_sleep}" ) return True return False
artilharia = list() while True: jogador = dict() print("-"*30) jogador['nome'] = str(input('Nome do Jogador: ')) gols = list() total = 0 partidas = int(input(f"Quantas partidas {jogador["nome"]} jogou? ")) for i in range(partidas): valor = int(input(f'Quantos gols na partida {i+1}? ')) gols.append(valor) total = total + valor jogador['gols'] = gols[:] jogador['total'] = total artilharia.append(jogador.copy()) cont = str(input('Quer continuar? [S/N] ')) if cont in "Nn": break print("-"*30) print("COD NOME GOALS TOTAL") print('-'*30) for i in range(len(artilharia)): print("{:< 4d}".format(i+1) + "{:< 15d}".format(artilharia[i]['nome']) + "{:<16d}".format(artilharia[i]['gols']) + "{:<5d}".format(artilharia[i]['total'])) while True: print("-"*30) num = int(input("Mostrar dados de qual jogador? ")) if num == 999: print("<< VOLTE SEMPRE >>") break elif num > len(artilharia): print(f"ERRO! Não existe jogador com o código {num}! Tente novamente.") else: print(f"-- LEVANTAMENTO DO JOGADOR {artilharia[num-1]["nome"]}:") jogo = 1 for j in artilharia[num-1]['gols']: print(f"No jogo {jogo} fez {j} gols.")
artilharia = list() while True: jogador = dict() print("-"*30) jogador['nome'] = str(input('Nome do Jogador: ')) gols = list() total = 0 partidas = int(input(f"Quantas partidas {jogador['nome']} jogou? ")) for i in range(partidas): valor = int(input(f'Quantos gols na partida {i+1}? ')) gols.append(valor) total = total + valor jogador['gols'] = gols[:] jogador['total'] = total artilharia.append(jogador.copy()) cont = str(input('Quer continuar? [S/N] ')) if cont in "Nn": break print("-"*30) print("COD NOME GOALS TOTAL") print('-'*30) for i in range(len(artilharia)): print("{:< 4d}".format(i+1) + "{:< 15d}".format(artilharia[i]['nome']) + "{:<16d}".format(artilharia[i]['gols']) + "{:<5d}".format(artilharia[i]['total'])) while True: print("-"*30) num = int(input("Mostrar dados de qual jogador? ")) if num == 999: print("<< VOLTE SEMPRE >>") break elif num > len(artilharia): print(f"ERRO! Não existe jogador com o código {num}! Tente novamente.") else: print(f"-- LEVANTAMENTO DO JOGADOR {artilharia[num-1]['nome']}:") jogo = 1 for j in artilharia[num-1]['gols']: print(f"No jogo {jogo} fez {j} gols.")
# -*- coding: utf-8 -*- # Owner(s): ["module: tests"] import torch import torch.utils.data import numpy as np import contextlib import gc import io import inspect import itertools import math import random import re import copy import os import tempfile import unittest import warnings import types import pickle import textwrap import subprocess import weakref import sys from torch.utils.dlpack import from_dlpack, to_dlpack from torch._six import inf, nan, string_classes from itertools import product, combinations, permutations from functools import partial from torch import multiprocessing as mp from torch.testing import make_tensor from torch.testing._internal.common_utils import ( TestCase, TEST_WITH_ROCM, run_tests, IS_WINDOWS, IS_FILESYSTEM_UTF8_ENCODING, NO_MULTIPROCESSING_SPAWN, IS_SANDCASTLE, IS_FBCODE, IS_REMOTE_GPU, load_tests, slowTest, TEST_WITH_CROSSREF, skipCUDAMemoryLeakCheckIf, BytesIOContext, skipIfRocm, skipIfNoSciPy, TemporaryFileName, TemporaryDirectoryName, wrapDeterministicFlagAPITest, DeterministicGuard, CudaSyncGuard, skipIfNotRegistered, bytes_to_scalar, parametrize, skipIfMps) from multiprocessing.reduction import ForkingPickler from torch.testing._internal.common_device_type import ( expectedFailureMeta, expectedFailureXLA, instantiate_device_type_tests, onlyCUDA, onlyCPU, dtypes, dtypesIfCUDA, dtypesIfCPU, deviceCountAtLeast, skipMeta, PYTORCH_CUDA_MEMCHECK, largeTensorTest, onlyNativeDeviceTypes, expectedAlertNondeterministic, get_all_device_types, skipXLA) from typing import Tuple import torch.backends.quantized import torch.testing._internal.data from torch.testing._internal.common_cuda import ( tf32_on_and_off, tf32_is_not_fp32, TEST_CUDNN) from torch.testing._internal.common_dtype import ( floating_types_and, get_all_math_dtypes, all_types_and_complex_and, complex_types, all_types_and, floating_types, floating_and_complex_types, integral_types, ) # Protects against includes accidentally setting the default dtype assert torch.get_default_dtype() is torch.float32 # load_tests from torch.testing._internal.common_utils is used to automatically filter tests for # sharding on sandcastle. This line silences flake warnings load_tests = load_tests AMPERE_OR_ROCM = TEST_WITH_ROCM or tf32_is_not_fp32() @contextlib.contextmanager def torch_vital_set(value): stash = None if 'TORCH_VITAL' in os.environ: stash = os.environ['TORCH_VITAL'] os.environ['TORCH_VITAL'] = value try: yield finally: if stash: os.environ['TORCH_VITAL'] = stash else: del os.environ['TORCH_VITAL'] # Tests Vital Signs for Torch # FIXME: document or deprecate whatever this is class TestBasicVitalSigns(TestCase): def test_basic_vitals(self): with torch_vital_set(''): self.assertFalse(torch.vitals_enabled()) with torch_vital_set('ON'): self.assertTrue(torch.vitals_enabled()) def test_basic_vitals_read_write(self): with torch_vital_set('ON'): self.assertTrue(torch.vitals_enabled()) # This tests the code path of setting a vital self.assertTrue(torch.set_vital('Dataloader', 'basic_unit_test', 'TEST_VALUE_STRING')) self.assertIn('TEST_VALUE_STRING', torch.read_vitals()) self.assertIn('CUDA.used', torch.read_vitals()) def test_dataloader_vitals(self): with torch_vital_set('ON'): inps = torch.arange(10 * 5, dtype=torch.float32).view(10, 5) tgts = torch.arange(10 * 5, dtype=torch.float32).view(10, 5) dataset = torch.utils.data.TensorDataset(inps, tgts) loader = torch.utils.data.DataLoader(dataset, batch_size=2) self.assertIn('Dataloader.enabled\t\t True', torch.read_vitals()) # FIXME: document or deprecate whatever this is class TestVitalSignsCuda(TestCase): @onlyCUDA def test_cuda_vitals_gpu_only(self, device): with torch_vital_set('ON'): self.assertIn('CUDA.used\t\t true', torch.read_vitals()) class TestTorchDeviceType(TestCase): exact_dtype = True # TODO: move all tensor creation to common ops def _rand_shape(self, dim, min_size, max_size): shape = [] for i in range(dim): shape.append(random.randint(min_size, max_size)) return tuple(shape) # Validates that mathematical constants are defined properly, as required by # the Python Array API (https://data-apis.org/array-api/latest/API_specification/constants.html) @onlyCPU def test_constants(self, device): self.assertIsInstance(torch.e, float) self.assertEqual(torch.e, math.e, atol=0, rtol=0) self.assertIsInstance(torch.pi, float) self.assertEqual(torch.pi, math.pi, atol=0, rtol=0) self.assertIsInstance(torch.nan, float) self.assertEqual(torch.nan, math.nan, equal_nan=True) self.assertIsInstance(torch.inf, float) self.assertEqual(torch.inf, math.inf) @onlyNativeDeviceTypes @dtypes(torch.int8, torch.uint8, torch.int16, torch.int32, torch.int64, torch.bool, torch.float32, torch.complex64, torch.float64, torch.complex128) def test_bytes_to_scalar(self, device, dtype): def rand_byte(): if dtype == torch.bool: return torch.randint(0, 2, ()).item() else: return torch.randint(0, 256, ()).item() element_size = torch._utils._element_size(dtype) for i in range(10): bytes_list = [rand_byte() for _ in range(element_size)] scalar = bytes_to_scalar(bytes_list, dtype, device) self.assertEqual(scalar.storage()._untyped().tolist(), bytes_list) @dtypes(torch.int8, torch.uint8, torch.int16, torch.int32, torch.int64, torch.bool, torch.float32, torch.complex64, torch.float64, torch.complex128) def test_storage(self, device, dtype): v = make_tensor((3, 5), dtype=dtype, device=device, low=-9, high=9) self.assertEqual(v.storage()[0], v[0][0]) self.assertEqual(v.storage()[14], v[2][4]) v_s = v.storage() for el_num in range(v.numel()): dim0 = el_num // v.size(1) dim1 = el_num % v.size(1) self.assertEqual( v_s[el_num], v[dim0][dim1]) v_s_byte = v.storage()._untyped() el_size = v.element_size() for el_num in range(v.numel()): start = el_num * el_size end = start + el_size dim0 = el_num // v.size(1) dim1 = el_num % v.size(1) self.assertEqual( bytes_to_scalar(v_s_byte[start:end], dtype, device), v[dim0][dim1]) @onlyNativeDeviceTypes @dtypes(torch.int8, torch.uint8, torch.int16, torch.int32, torch.int64, torch.bool, torch.float32, torch.complex64, torch.float64, torch.complex128, torch.quint8, torch.qint8, torch.qint32, torch.quint4x2) def test_storage_setitem(self, device, dtype): # Skip quantized dtypes for CUDA, since they're not supported if torch.device(device).type == 'cuda': if dtype in [torch.quint8, torch.qint8, torch.qint32, torch.quint4x2]: return storage_type_name = torch.storage._dtype_to_storage_type_map()[dtype] if torch.device(device).type == 'cuda': storage_type = eval('torch.cuda.' + storage_type_name) else: storage_type = eval('torch.' + storage_type_name) N = 10 s = storage_type(N) s[:] = 0 l = [0] * N self.assertEqual(s, storage_type(l)) for i in range(N): s[i] = i l[i] = i self.assertEqual(s, storage_type(l)) l[2:7] = [1] * 5 s[2:7] = 1 self.assertEqual(s, storage_type(l)) @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) def test_tensor_storage_type(self, device, dtype): a = make_tensor((10,), dtype=dtype, device=device, low=-9, high=9) module = torch.cuda if (torch.device(device).type == 'cuda') else torch expected_storage_type = getattr(module, torch.storage._dtype_to_storage_type_map()[dtype]) self.assertEqual(a.storage_type(), expected_storage_type) @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) def test_tensor_from_storage(self, device, dtype): a = make_tensor((4, 5, 3), dtype=dtype, device=device, low=-9, high=9) a_s = a.storage() b = torch.tensor(a_s, device=device, dtype=dtype).reshape(a.size()) self.assertEqual(a, b) c = torch.tensor(a_s._untyped(), device=device, dtype=dtype).reshape(a.size()) self.assertEqual(a, c) for error_dtype in all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16): if error_dtype == dtype: continue with self.assertRaisesRegex(RuntimeError, r'Expected a Storage of type'): error_storage = a.to(error_dtype).storage() torch.tensor(error_storage, device=device, dtype=dtype) @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) def test_set_storage(self, device, dtype): a = make_tensor((4, 5, 3), dtype=dtype, device=device, low=-9, high=9) a_s = a.storage() b = torch.tensor([], device=device, dtype=dtype).set_(a_s).reshape(a.size()) self.assertEqual(a, b) c = torch.tensor([], device=device, dtype=dtype).set_(a_s._untyped()).reshape(a.size()) self.assertEqual(a, c) for error_dtype in all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16): if error_dtype == dtype: continue with self.assertRaisesRegex(RuntimeError, r'Expected a Storage of type'): error_storage = a.to(error_dtype).storage() b = torch.tensor([], device=device, dtype=dtype).set_(error_storage) def _check_storage_meta(self, s, s_check): self.assertTrue( isinstance(s, (torch._UntypedStorage, torch._TypedStorage)) and isinstance(s_check, type(s)), ( 's and s_check must both be one of _UntypedStorage or ' '_TypedStorage, but got' f' {type(s).__name__} and {type(s_check).__name__}')) self.assertEqual(s.device.type, 'meta') self.assertEqual(s.nbytes(), s_check.nbytes()) self.assertEqual(s.size(), s_check.size()) self.assertEqual(s.data_ptr(), 0) with self.assertRaisesRegex(NotImplementedError, r'Not available'): s[0] if isinstance(s, torch._TypedStorage): self.assertEqual(s.dtype, s_check.dtype) self._check_storage_meta(s._untyped(), s_check._untyped()) @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) def test_typed_storage_meta(self, device, dtype): args_list = [ [], [0], [100], [[1, 2, 3, 4, 5, 6]], ] for args in args_list: s_check = torch._TypedStorage(*args, dtype=dtype, device=device) s = torch._TypedStorage(*args, dtype=dtype, device='meta') self._check_storage_meta(s, s_check) @onlyNativeDeviceTypes def test_untyped_storage_meta(self, device): args_list = [ [], [0], [100], [[1, 2, 3, 4, 5, 6]], ] for args in args_list: s_check = torch._UntypedStorage(*args, device=device) s = torch._UntypedStorage(*args, device='meta') self._check_storage_meta(s, s_check) @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) def test_storage_meta_from_tensor(self, device, dtype): t_check = make_tensor((4, 5, 3), dtype=dtype, device=device, low=-9, high=9) t = t_check.to('meta') s_check = t_check.storage() s = t.storage() self._check_storage_meta(s, s_check) @onlyCPU @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) def test_storage_meta_errors(self, device, dtype): s0 = torch._TypedStorage([1, 2, 3, 4], device='meta', dtype=dtype) with self.assertRaisesRegex(NotImplementedError, r'Cannot copy out'): s0.cpu() with self.assertRaisesRegex(RuntimeError, r'only available on CPU'): s0._share_fd_cpu_() with self.assertRaisesRegex(RuntimeError, r'only available on CPU'): s0._share_filename_cpu_() if torch.cuda.is_available(): with self.assertRaisesRegex(NotImplementedError, r'Cannot copy out'): s0.cuda() with self.assertRaisesRegex(RuntimeError, r'only available on CUDA'): s0._share_cuda_() with self.assertRaisesRegex(NotImplementedError, r'Cannot copy out'): s0.pin_memory() with self.assertRaisesRegex(RuntimeError, r'got unexpected device type'): s0.resize_(10) with self.assertRaisesRegex(RuntimeError, r'only available on CPU'): s0.share_memory_() with self.assertRaisesRegex(NotImplementedError, r'Not available'): s0.tolist() with tempfile.NamedTemporaryFile() as f: with self.assertRaisesRegex(RuntimeError, r'Device not recognized'): s0._write_file(f, True, True, s0.element_size()) for device in ['cpu', 'cuda'] if torch.cuda.is_available() else ['cpu']: s1 = torch._TypedStorage([1, 2, 3, 4], device=device, dtype=dtype) with self.assertRaisesRegex(NotImplementedError, r'Cannot copy out'): s1.copy_(s0) @dtypes(torch.float32, torch.complex64) def test_deepcopy(self, device, dtype): from copy import deepcopy a = torch.randn(5, 5, dtype=dtype, device=device) b = torch.randn(5, 5, dtype=dtype, device=device) c = a.view(25) q = [a, [a.storage(), b.storage()], b, c] w = deepcopy(q) self.assertEqual(w[0], q[0], atol=0, rtol=0) self.assertEqual(w[1][0], q[1][0], atol=0, rtol=0) self.assertEqual(w[1][1], q[1][1], atol=0, rtol=0) self.assertEqual(w[1], q[1], atol=0, rtol=0) self.assertEqual(w[2], q[2], atol=0, rtol=0) # Check that deepcopy preserves sharing w[0].add_(1) for i in range(a.numel()): self.assertEqual(w[1][0][i], q[1][0][i] + 1) self.assertEqual(w[3], c + 1) w[2].sub_(1) for i in range(a.numel()): self.assertEqual(w[1][1][i], q[1][1][i] - 1) # Check that deepcopy preserves attributes a.foo = 3 self.assertEqual(deepcopy(a).foo, 3) @dtypes(torch.float32, torch.complex64) def test_deepcopy_scalar(self, device, dtype): from copy import deepcopy a = torch.tensor(5, dtype=dtype, device=device) self.assertEqual(a.size(), deepcopy(a).size()) self.assertEqual(a, deepcopy(a)) def check_internal_mem_overlap(self, inplace_op, num_inputs, dtype, device, expected_failure=False): if isinstance(inplace_op, str): inplace_op = getattr(torch.Tensor, inplace_op) input = torch.randn(1, dtype=dtype, device=device).expand(3, 3) inputs = [input] + [torch.randn_like(input) for i in range(num_inputs - 1)] if not expected_failure: with self.assertRaisesRegex(RuntimeError, 'single memory location'): inplace_op(*inputs) else: with self.assertRaises(AssertionError): with self.assertRaisesRegex(RuntimeError, 'single memory location'): inplace_op(*inputs) def unary_check_input_output_mem_overlap(self, data, sz, op, expected_failure=False): def _test(op, output, input): output_exp = torch.empty_like(output) op(input, out=output_exp) self.assertEqual(op(input, out=output), output_exp, msg=op.__name__) # output is identical to input: _test(op, output=data[0:sz], input=data[0:sz]) # output and input are independent: _test(op, output=data[0:sz], input=data[sz:2 * sz]) # output partially overlaps with input: if not expected_failure: with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): _test(op, data[0:sz], data[1:sz + 1]) else: with self.assertRaises(AssertionError): with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): _test(op, data[0:sz], data[1:sz + 1]) # output is transpose of input: length = int(math.sqrt(sz)) input = data[:length**2].view([length, length]) out = input.t() if not expected_failure: with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): _test(op, out, input) else: with self.assertRaises(AssertionError): with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): _test(op, out, input) def ternary_check_input_output_mem_overlap(self, op, device, expected_failure=False): sz = 9 data = torch.randn(2 * sz, device=device) other1 = torch.randn(sz, device=device) other2 = torch.randn(sz, device=device) self.unary_check_input_output_mem_overlap( data, sz, lambda input, out: op(input, other1.view(input.shape), other2.view(input.shape), out=out), expected_failure=expected_failure) self.unary_check_input_output_mem_overlap( data, sz, lambda input, out: op(other1.view(input.shape), input, other2.view(input.shape), out=out), expected_failure=expected_failure) self.unary_check_input_output_mem_overlap( data, sz, lambda input, out: op(other1.view(input.shape), other2.view(input.shape), input, out=out), expected_failure=expected_failure) def _select_broadcastable_dims(self, dims_full=None): # select full dimensionality if dims_full is None: dims_full = [] ndims = random.randint(1, 4) dims_full = [random.randint(1, 8) for _ in range(ndims)] else: ndims = len(dims_full) # select actual dimensions for ops: # larger: full ndims, individual sizes may be reduced # smaller: possibly reduced ndims, sizes may be reduced smaller_ndims = random.randint(1, ndims) dims_small = [] dims_large = [] for i in range(ndims - 1, -1, -1): j = random.randint(1, 3) if j == 1: # no reduced singleton dimension ds = dims_full[i] dl = dims_full[i] elif j == 2: # larger may have reduced singleton dimension ds = dims_full[i] dl = 1 if len(dims_small) < smaller_ndims else dims_full[i] elif j == 3: # smaller may have reduced singleton dimension ds = 1 dl = dims_full[i] dims_large = [dl] + dims_large if len(dims_small) < smaller_ndims: dims_small = [ds] + dims_small return (dims_small, dims_large, dims_full) # collected tests of ops that used scalar_check in Declarations.cwrap for # correctness def test_scalar_check(self, device): zero_d = torch.randn((), device=device) one_d = torch.randn((1,), device=device) # remainder self.assertEqual((), torch.remainder(zero_d, zero_d).shape) self.assertEqual((), torch.remainder(zero_d, 2).shape) self.assertEqual((1,), torch.remainder(zero_d, one_d).shape) self.assertEqual((1,), torch.remainder(one_d, zero_d).shape) # fmod self.assertEqual((), torch.fmod(zero_d, zero_d).shape) self.assertEqual((), torch.fmod(zero_d, 2).shape) self.assertEqual((1,), torch.fmod(zero_d, one_d).shape) self.assertEqual((1,), torch.fmod(one_d, zero_d).shape) # exp, cos, cosh, tan, atan, tanh, erf, erfc, reciprocal self.assertEqual((), torch.exp(zero_d).shape) self.assertEqual((), torch.cos(zero_d).shape) self.assertEqual((), torch.cosh(zero_d).shape) self.assertEqual((), torch.tan(zero_d).shape) self.assertEqual((), torch.atan(zero_d).shape) self.assertEqual((), torch.acosh(zero_d).shape) self.assertEqual((), torch.asinh(zero_d).shape) self.assertEqual((), torch.atanh(zero_d).shape) self.assertEqual((), torch.tanh(zero_d).shape) self.assertEqual((), torch.erf(zero_d).shape) self.assertEqual((), torch.erfc(zero_d).shape) self.assertEqual((), torch.reciprocal(zero_d).shape) self.assertEqual((1,), torch.exp(one_d).shape) self.assertEqual((1,), torch.cos(one_d).shape) self.assertEqual((1,), torch.cosh(one_d).shape) self.assertEqual((1,), torch.tan(one_d).shape) self.assertEqual((1,), torch.atan(one_d).shape) self.assertEqual((1,), torch.acosh(one_d).shape) self.assertEqual((1,), torch.asinh(one_d).shape) self.assertEqual((1,), torch.atanh(one_d).shape) self.assertEqual((1,), torch.tanh(one_d).shape) self.assertEqual((1,), torch.erf(one_d).shape) self.assertEqual((1,), torch.erfc(one_d).shape) self.assertEqual((1,), torch.reciprocal(one_d).shape) # clamp self.assertEqual((), torch.clamp(zero_d, min=0, max=1).shape) self.assertEqual((), torch.clamp(zero_d, min=0).shape) self.assertEqual((), torch.clamp(zero_d, max=1).shape) self.assertEqual((1,), torch.clamp(one_d, min=0, max=1).shape) self.assertEqual((1,), torch.clamp(one_d, min=0).shape) self.assertEqual((1,), torch.clamp(one_d, max=1).shape) # cumsum, cumprod, cummax, cummin self.assertEqual((), torch.logcumsumexp(zero_d, 0).shape) self.assertEqual((), torch.cumsum(zero_d, 0).shape) self.assertEqual((), torch.cumprod(zero_d, 0).shape) self.assertEqual((), torch.cummax(zero_d, 0)[0].shape) self.assertEqual((), torch.cummin(zero_d, 0)[0].shape) # sort, topk self.assertEqual([(), ()], [x.shape for x in torch.sort(zero_d, 0, False)]) self.assertEqual([(), ()], [x.shape for x in torch.sort(zero_d, 0, True)]) self.assertEqual([(), ()], [x.shape for x in torch.topk(zero_d, 1, 0, False)]) self.assertEqual([(), ()], [x.shape for x in torch.topk(zero_d, 1, 0, True)]) # max, min self.assertEqual((), torch.max(zero_d, zero_d).shape) self.assertEqual((1,), torch.max(one_d, zero_d).shape) self.assertEqual((1,), torch.max(zero_d, one_d).shape) self.assertEqual((), torch.min(zero_d, zero_d).shape) self.assertEqual((1,), torch.min(one_d, zero_d).shape) self.assertEqual((1,), torch.min(zero_d, one_d).shape) zero_d_int = torch.tensor(1, device=device) one_d_int = torch.tensor([1], device=device) # lshift, rshift self.assertEqual((), (zero_d_int >> zero_d_int).shape) self.assertEqual((), (zero_d_int >> 1).shape) self.assertEqual((1,), (one_d_int >> zero_d_int).shape) self.assertEqual((1,), (zero_d_int >> one_d_int).shape) self.assertEqual((1,), (one_d_int >> 1).shape) self.assertEqual((), (zero_d_int << zero_d_int).shape) self.assertEqual((), (zero_d_int << 1).shape) self.assertEqual((1,), (one_d_int << zero_d_int).shape) self.assertEqual((1,), (zero_d_int << one_d_int).shape) self.assertEqual((1,), (one_d_int << 1).shape) # or self.assertEqual((), (zero_d_int | zero_d_int).shape) self.assertEqual((), (zero_d_int | 1).shape) self.assertEqual((1,), (one_d_int | zero_d_int).shape) self.assertEqual((1,), (zero_d_int | one_d_int).shape) self.assertEqual((1,), (one_d_int | 1).shape) # and self.assertEqual((), (zero_d_int & zero_d_int).shape) self.assertEqual((), (zero_d_int & 1).shape) self.assertEqual((1,), (one_d_int & zero_d_int).shape) self.assertEqual((1,), (zero_d_int & one_d_int).shape) self.assertEqual((1,), (one_d_int & 1).shape) # clone self.assertEqual((), zero_d.clone().shape) zero_d_bool = torch.tensor(True, device=device) one_d_bool = torch.tensor([True], device=device) # masked_select self.assertEqual((1,), torch.masked_select(zero_d_bool, zero_d_bool).shape) self.assertEqual((1,), torch.masked_select(zero_d_bool, one_d_bool).shape) self.assertEqual((1,), torch.masked_select(one_d_bool, zero_d_bool).shape) zero_d_uint8 = torch.tensor(1, dtype=torch.uint8, device=device) one_d_uint8 = torch.tensor([1], dtype=torch.uint8, device=device) with warnings.catch_warnings(): warnings.simplefilter("ignore") self.assertEqual((1,), torch.masked_select(zero_d_uint8, zero_d_uint8).shape) self.assertEqual((1,), torch.masked_select(zero_d_uint8, one_d_uint8).shape) self.assertEqual((1,), torch.masked_select(one_d_uint8, zero_d_uint8).shape) # mode self.assertEqual([(), ()], [x.shape for x in torch.mode(zero_d, dim=0, keepdim=True)]) self.assertEqual([(), ()], [x.shape for x in torch.mode(zero_d, dim=0, keepdim=False)]) self.assertEqual([(1,), (1,)], [x.shape for x in torch.mode(one_d, dim=0, keepdim=True)]) self.assertEqual([(), ()], [x.shape for x in torch.mode(one_d, dim=0, keepdim=False)]) # max self.assertEqual([(), ()], [x.shape for x in torch.max(zero_d, dim=0, keepdim=True)]) self.assertEqual([(), ()], [x.shape for x in torch.max(zero_d, dim=0, keepdim=False)]) self.assertEqual([(1,), (1,)], [x.shape for x in torch.max(one_d, dim=0, keepdim=True)]) self.assertEqual([(), ()], [x.shape for x in torch.max(one_d, dim=0, keepdim=False)]) # amax self.assertEqual((), torch.amax(zero_d, dim=0, keepdim=True).shape) self.assertEqual((), torch.amax(zero_d, dim=0, keepdim=False).shape) self.assertEqual((1,), torch.amax(one_d, dim=0, keepdim=True).shape) self.assertEqual((), torch.amax(one_d, dim=0, keepdim=False).shape) # min self.assertEqual([(), ()], [x.shape for x in torch.min(zero_d, dim=0, keepdim=True)]) self.assertEqual([(), ()], [x.shape for x in torch.min(zero_d, dim=0, keepdim=False)]) self.assertEqual([(1,), (1,)], [x.shape for x in torch.min(one_d, dim=0, keepdim=True)]) self.assertEqual([(), ()], [x.shape for x in torch.min(one_d, dim=0, keepdim=False)]) # amin self.assertEqual((), torch.amin(zero_d, dim=0, keepdim=True).shape) self.assertEqual((), torch.amin(zero_d, dim=0, keepdim=False).shape) self.assertEqual((1,), torch.amin(one_d, dim=0, keepdim=True).shape) self.assertEqual((), torch.amin(one_d, dim=0, keepdim=False).shape) # set_ zero_d_clone = zero_d.clone() one_d_clone = one_d.clone() self.assertEqual((), zero_d_clone.set_(one_d.storage(), 0, (), ()).shape) self.assertEqual((1,), zero_d_clone.set_(one_d.storage(), 0, (1,), (1,)).shape) self.assertEqual((), one_d_clone.set_(one_d.storage(), 0, (), ()).shape) self.assertEqual((1,), one_d_clone.set_(one_d.storage(), 0, (1,), (1,)).shape) self.assertEqual((), zero_d.clone().set_(zero_d).shape) self.assertEqual((), one_d.clone().set_(zero_d).shape) self.assertEqual((1,), zero_d.clone().set_(one_d).shape) self.assertEqual((1,), one_d.clone().set_(one_d).shape) # take self.assertEqual((), torch.randn((2, 3), device=device).take(zero_d_int).shape) self.assertEqual((1,), torch.randn((2, 3), device=device).take(one_d_int).shape) # gather self.assertEqual((), torch.gather(zero_d, 0, torch.zeros((), dtype=torch.int64, device=device)).shape) self.assertEqual((1,), torch.gather(zero_d, 0, torch.zeros((1,), dtype=torch.int64, device=device)).shape) self.assertEqual((), torch.gather(one_d, 0, torch.zeros((), dtype=torch.int64, device=device)).shape) self.assertEqual((1,), torch.gather(one_d, 0, torch.zeros((1,), dtype=torch.int64, device=device)).shape) # normal # std must be >= 0 zero_d_ge_0 = torch.rand((), device=device) # documentation says out shape matches shape of mean self.assertEqual((), torch.normal(zero_d, zero_d_ge_0).shape) self.assertEqual((1,), torch.normal(one_d, zero_d_ge_0).shape) self.assertEqual((), torch.normal(1, zero_d_ge_0).shape) self.assertEqual((), torch.normal(zero_d, 1).shape) self.assertEqual((1,), torch.normal(one_d, 1).shape) # TODO: this behavior differs on CPU and GPU, see https://github.com/pytorch/pytorch/issues/30480. # self.assertEqual((), torch.normal(zero_d, one_d).shape) # self.assertEqual((), torch.normal(1, one_d).shape) # convolutions. Yes, we are testing nn.functional here; seems justified # given its similar to the other tests w = torch.randn(2, 1, 3, 3, device=device).div_(2).requires_grad_() self.assertRaises(RuntimeError, lambda: torch.nn.functional.conv2d(zero_d, w, groups=1)) self.assertRaises(RuntimeError, lambda: torch.nn.functional.conv2d(zero_d, w, groups=2)) # nll_loss -- verify input can't be 0-dimensional. self.assertRaises(ValueError, lambda: torch.nn.functional.nll_loss(zero_d, zero_d, reduction='none')) self.assertRaises(ValueError, lambda: torch.nn.functional.nll_loss(zero_d, one_d, reduction='none')) # verify output is 0-dimensional when reduction != 'none' for (input, target) in ((torch.randn(1, 1, device=device), torch.tensor([0], device=device)), (torch.randn(1, 1, 1, 1, device=device), torch.tensor([[[0]]], device=device))): self.assertEqual((), torch.nn.functional.nll_loss(input, target, reduction='mean').shape) self.assertEqual((), torch.nn.functional.nll_loss(input, target, reduction='sum').shape) # multilabel_margin_loss for input in (zero_d, one_d, torch.randn(1, 1, device=device)): for target in (torch.tensor(0, device=device), torch.tensor([0], device=device), torch.tensor([[0]], device=device)): if (input.dim() <= 1 and target.dim() <= 1) or (input.dim() == 2 and target.dim() == 2): output_shape = (target.shape[0],) if target.dim() == 2 else () self.assertEqual(output_shape, torch.nn.functional.multilabel_margin_loss(input, target, reduction='none').shape) self.assertEqual((), torch.nn.functional.multilabel_margin_loss(input, target, reduction='mean').shape) self.assertEqual((), torch.nn.functional.multilabel_margin_loss(input, target, reduction='sum').shape) else: self.assertRaises(RuntimeError, lambda: torch.nn.functional.multilabel_margin_loss(input, target, reduction='none')) self.assertRaises(RuntimeError, lambda: torch.nn.functional.multilabel_margin_loss(input, target, reduction='mean')) self.assertRaises(RuntimeError, lambda: torch.nn.functional.multilabel_margin_loss(input, target, reduction='sum')) # multi_margin_loss for input in (zero_d, one_d, torch.randn(1, 1, device=device)): for target in (torch.tensor(0, device=device), torch.tensor([0], device=device)): self.assertEqual(target.shape, torch.nn.functional.multi_margin_loss(input, target, reduction='none').shape) self.assertEqual((), torch.nn.functional.multi_margin_loss(input, target, reduction='mean').shape) self.assertEqual((), torch.nn.functional.multi_margin_loss(input, target, reduction='sum').shape) # Uses mismatched arange out size to trigger a warning @unittest.skipIf(TEST_WITH_CROSSREF, "crossref perturbs line numbering") def test_cpp_warnings_have_python_context(self, device): # Creates long string in advance to avoid a too-long Python line s = ".+Triggered internally at.+RangeFactories.+" def cpp_warn_fn(): out = torch.empty((5,)) torch.arange(0, 3, out=out) return out # Checks eager-mode cpp warning with warnings.catch_warnings(record=True) as w: cpp_warn_fn() frameinfo = inspect.getframeinfo(inspect.currentframe()) warning = w[0] # Checks for cpp context in the warning message escaped_warning_message = str(warning.message).encode('unicode_escape') self.assertTrue(re.search(s, str(escaped_warning_message), re.IGNORECASE) is not None) # Checks the Python features of the warning # Note: the eager mode warning refers to the line in the function # that throws the warning. self.assertEqual(frameinfo.lineno - 6, warning.lineno) self.assertEqual(len(w), 1) # Checks jitted cpp warning with warnings.catch_warnings(record=True) as w: scripted_cpp_warn_fn = torch.jit.script(cpp_warn_fn) scripted_cpp_warn_fn() warning = w[0] # Checks for cpp context in the warning message escaped_warning_message = str(warning.message).encode('unicode_escape') self.assertTrue(re.search(s, str(escaped_warning_message), re.IGNORECASE) is not None) # Checks the Python features of the warning # Note: the jitted warning's lineno refers to the call to the jitted # function, which in our test suite has a layer of indirection # that makes checking the Python lineno fragile self.assertEqual(len(w), 1) # Checks jitted Python warning def warn_fn(): warnings.warn("Warning!") # The jit mimics an eager-mode Python warning in this case with warnings.catch_warnings(record=True) as w: scripted_warn_fn = torch.jit.script(warn_fn) scripted_warn_fn() frameinfo = inspect.getframeinfo(inspect.currentframe()) warning = w[0] self.assertTrue(re.search('Warning!', str(warning.message)) is not None) # Checks the Python features of the warning self.assertEqual(frameinfo.lineno - 6, warning.lineno) self.assertEqual(len(w), 1) # FIXME: move to test_testing @onlyCPU def test_warn_always_caught(self, device): # Check that we can catch a TORCH_WARN_ONCE warning twice # since assertWarnsOnceRegex uses set_warn_always(True) which changes # TORCH_WARN_ONCE to TORCH_WARN a = np.arange(10) a.flags.writeable = False with self.assertWarnsOnceRegex(UserWarning, '.*non-writable.*'): torch.from_numpy(a) # OK, got it once, now try again with self.assertWarnsOnceRegex(UserWarning, '.*non-writable.*'): torch.from_numpy(a) # Make sure emitting two warnings will pass the assertWarnsOnceRegex # context manager with self.assertWarnsOnceRegex(UserWarning, '.*non-writable.*'): torch.from_numpy(a) torch.from_numpy(a) # TODO: this test should be in test_nn.py def test_conv_transposed_backward_agnostic_to_memory_format(self, device): in_channels = 64 out_channels = 128 scale_factor = 8 batch_size = 8 length = 16 conv = torch.nn.ConvTranspose1d( in_channels, out_channels, kernel_size=scale_factor * 2, stride=scale_factor).to(device) layer_norm = torch.nn.LayerNorm(out_channels).to(device) input_ = torch.randn(batch_size, in_channels, length).to(device).contiguous() input_ = conv(input_).contiguous() input_ = layer_norm(input_.transpose(1, 2).contiguous()).contiguous() input_.sum().backward() # 3d conv = torch.nn.ConvTranspose3d(3, 3, kernel_size=3).to(device) input = torch.randn(batch_size, 3, length, length, length, device=device) out = conv(input) out.backward(torch.ones_like(out).transpose(-2, -1)) # TODO: this test should be in test_nn.py @onlyCUDA @largeTensorTest('12GB') def test_conv_transposed_large(self, device): # ConvTranspose3d works for large input tensors (gh-32866) in_channels = 64 out_channels = 128 kernel_size = 5 conv = torch.nn.ConvTranspose3d( in_channels, out_channels, kernel_size=kernel_size, stride=2, padding=2, output_padding=1).to(device) x = torch.rand([1, 64, 8, 128, 172]).to(device) y = conv(x) def test_is_set_to(self, device): t1 = torch.empty(3, 4, 9, 10, device=device) t2 = torch.empty(3, 4, 9, 10, device=device) t3 = torch.tensor([], device=device).set_(t1) t4 = t3.clone().resize_(12, 90) self.assertFalse(t1.is_set_to(t2)) self.assertTrue(t1.is_set_to(t3)) self.assertTrue(t3.is_set_to(t1), "is_set_to should be symmetric") self.assertFalse(t1.is_set_to(t4)) self.assertFalse(torch.tensor([]).is_set_to(torch.tensor([])), "Tensors with no storages should not appear to be set " "to each other") t1 = torch.tensor([True, True], dtype=torch.bool, device=device) t2 = torch.tensor([0], dtype=torch.bool, device=device).set_(t1) self.assertTrue(t1.is_set_to(t2)) # test that sizes must match t1 = torch.empty([2, 3, 4], device=device) t2 = t1.view(4, 3, 2) self.assertFalse(t1.is_set_to(t2)) self.assertFalse(t2.is_set_to(t1)) # test that legacy empty size behavior used to be respected (i.e. all # empty tensors were logically collapsed to size [0]). t1 = torch.empty([2, 5, 0], device=device) t2 = t1.view([0]) self.assertFalse(t1.is_set_to(t2)) self.assertFalse(t2.is_set_to(t1)) # See https://github.com/pytorch/pytorch/issues/72650 @skipIfMps @skipMeta @parametrize( "fn", [ "dist", "atan2", "pow", "lerp", "add", "sub", "mul", "div", "fmod", "remainder", "eq", "ge", "gt", "le", "lt", "max", "min", "ne", "addcdiv", "addcmul", "masked_scatter", "masked_select", "masked_fill", "map", "map2", "copy", ], ) def test_broadcast(self, fn, device): # functions with three tensor arguments fns_3_args = {"map2"} fns_value_kwarg = {"addcdiv", "addcmul"} (dims_small, dims_large, dims_full) = self._select_broadcastable_dims() full1d = torch.randn(*dims_full, device=device).flatten().float() small = torch.randn(*dims_small, device=device).float() large = torch.randn(*dims_large, device=device).float() small_expanded = small.expand(*dims_full) large_expanded = large.expand(*dims_full) small2 = None small2_expanded = None if fn in fns_3_args or fn in fns_value_kwarg: # create another smaller tensor (dims_small2, _, _) = self._select_broadcastable_dims(dims_full) small2 = torch.randn(*dims_small2, device=device).float() small2_expanded = small2.expand(*dims_full) if small.is_cuda and fn in ['map', 'map2']: # map and map2 are not implementd on CUDA tensors return if hasattr(large_expanded, fn): # run through tensor versions of functions # and verify fully expanded inputs give same results expanded = {large: large_expanded, small: small_expanded, small2: small2_expanded} def tensorfn(myfn, t1, t2): if fn == "lerp": return myfn(t1, 0.5) elif fn == "masked_select": return myfn(t1 < 0) elif fn == "masked_scatter": return myfn(t1 < 0.5, full1d) elif fn == "masked_fill": return myfn(t1 < 0.5, 1.0) elif fn in fns_3_args: return myfn(1, t1, t2) elif fn in fns_value_kwarg: return myfn(t1, t2, value=1) else: return myfn(t1) # test various orders for first, second, third in [(large, small, small2), (small, large, small2), (small2, small, large), (small2, large, small)]: if first is None: break # ignore last iter when small2 is None method_expanded = getattr(expanded[first], fn) method = getattr(first, fn) r1 = tensorfn(method_expanded, expanded[second], expanded[third]) r2 = tensorfn(method, second, third) self.assertEqual(r1, r2) # now for torch. versions of functions if hasattr(torch, fn): fntorch = getattr(torch, fn) expanded = {large: large_expanded, small: small_expanded, small2: small2_expanded} def torchfn(t1, t2, t3): if fn == "lerp": return fntorch(t1, t2, 0.5) elif fn == "masked_select": return fntorch(t1, t2 < 0) elif fn == "masked_scatter": return fntorch(t1, t2 < 0.5, full1d) elif fn == "masked_fill": return fntorch(t1, t2 < 0.5, 1.0) elif fn in fns_3_args: return fntorch(t1, 1.0, t2, t3) elif fn in fns_value_kwarg: return fntorch(t1, t2, t3, value=1.0) else: return fntorch(t1, t2) # test various orders for first, second, third in [(large, small, small2), (small, large, small2), (small2, small, large), (small2, large, small)]: if first is None: break # ignore last iter when small2 is None r1 = torchfn(expanded[first], expanded[second], expanded[third]) r2 = torchfn(first, second, third) self.assertEqual(r1, r2) # now for in place functions # in-place tensor is not broadcastable; test only guaranteed # to work by broadcasting other argument(s) if not hasattr(large_expanded, fn + "_"): return # need to clone largeExpanded so we can reuse, since functions are in-place large_expanded_clone = large_expanded.clone() def tensorfn_inplace(t0, t1, t2=None): t0_fn = getattr(t0, fn + "_") if fn == "lerp": return t0_fn(t1, 0.5) elif fn == "masked_scatter": return t0_fn(t1 < 0.5, full1d) elif fn == "masked_fill": return t0_fn(t1 < 0.5, 1.0) elif fn == "map": return t0_fn(t1, lambda x, y: x + y) elif fn == "map2": return t0_fn(t1, t2, lambda x, y, z: x + y + z) elif fn in fns_3_args: return t0_fn(1.0, t1, t2) elif fn in fns_value_kwarg: return t0_fn(t1, t2, value=1.0) else: return t0_fn(t1) # in-place pointwise operations don't actually work if the in-place # tensor is 0-strided (numpy has the same issue) if (0 not in large_expanded.stride() and 0 not in large_expanded_clone.stride()): r1 = tensorfn_inplace(large_expanded, small_expanded, small2_expanded) r2 = tensorfn_inplace(large_expanded_clone, small, small2) self.assertEqual(r1, r2) def broadcastable(t0, t1, t2=None): try: t1.expand_as(t0) if t2 is not None: t2.expand_as(t0) except RuntimeError: return False return True def _test_in_place_broadcastable(t0, t1, t2=None): if not broadcastable(t0, t1, t2): same_size = t0.numel() == t1.numel() and (t0.numel() == t2.numel() if t2 is not None else True) if not same_size: self.assertRaises(RuntimeError, lambda: tensorfn_inplace(t0, t1, t2)) else: tensorfn_inplace(t0, t1, t2) if fn not in fns_3_args and fn not in fns_value_kwarg: _test_in_place_broadcastable(small, large_expanded) _test_in_place_broadcastable(small, large) else: _test_in_place_broadcastable(small2, small_expanded, large_expanded) _test_in_place_broadcastable(small2, small, large) @unittest.skipIf(IS_FBCODE and IS_REMOTE_GPU, "cublas runtime error") @onlyCUDA @wrapDeterministicFlagAPITest def test_cublas_config_nondeterministic_alert(self, device): test_cases = [ # (function, (tensor sizes)) ('mm', ((2, 2), (2, 2),)), ('mv', ((2, 2), (2,),)), ('bmm', ((1, 2, 2), (1, 2, 2),))] test_configs = [ # (CuBLAS workspace config, is deterministic) ('garbage', False), (None, False), (':4096:8', True), (':16:8', True)] cublas_var_name = 'CUBLAS_WORKSPACE_CONFIG' is_cuda10_2_or_higher = ( (torch.version.cuda is not None) and ([int(x) for x in torch.version.cuda.split(".")] >= [10, 2])) def test_case_info(fn_name, config): return f'function "{fn_name}' with config '{'' if config is None else config}"' # Create processes to test each combination of test cases and config settings processes = [] for fn_name, arg_sizes in test_cases: for config, is_config_deterministic in test_configs: env = os.environ.copy() if config is None: if env.get(cublas_var_name) is not None: del env[cublas_var_name] else: env[cublas_var_name] = config should_throw_error = is_cuda10_2_or_higher and not is_config_deterministic script = f""" import torch torch.use_deterministic_algorithms(True) fn = torch.{fn_name} arg_sizes = {arg_sizes} device = '{device}' should_throw_error = {should_throw_error} args = [] for arg_size in arg_sizes: args.append(torch.randn(*arg_size, device=device)) try: fn(*args) except RuntimeError as e: if not should_throw_error: raise RuntimeError('Did not expect any error to be raised') elif 'Deterministic behavior was enabled with either' not in str(e): raise RuntimeError('Expected a CuBLAS nondeterministic error, but got a different error') else: if should_throw_error: raise RuntimeError('Expected a CuBLAS nondeterministic error, but it was not raised') """ try: subprocess.check_output( [sys.executable, '-c', script], stderr=subprocess.STDOUT, # On Windows, opening the subprocess with the default CWD makes `import torch` # fail, so just set CWD to this script's directory cwd=os.path.dirname(os.path.realpath(__file__)), env=env) except subprocess.CalledProcessError as e: self.fail(msg=( f'Subprocess exception while attempting to run {test_case_info(fn_name, config)}:\n' + e.output.decode("utf-8"))) # FIXME: update OpInfos to support "nondeterministic samples" and port these tests # to that architecture @skipIfMps def test_nondeterministic_alert_AvgPool3d(self, device): module = torch.nn.AvgPool3d(3) input = torch.randn(2, 3, 3, 3, requires_grad=True, device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('avg_pool3d_backward_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) @skipIfMps def test_nondeterministic_alert_AdaptiveAvgPool2d(self, device): module = torch.nn.AdaptiveAvgPool2d(3) input = torch.randn(2, 3, 3, requires_grad=True, device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('adaptive_avg_pool2d_backward_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) @skipIfMps def test_nondeterministic_alert_AdaptiveAvgPool3d(self, device): module = torch.nn.AdaptiveAvgPool3d(3) input = torch.randn(2, 3, 3, 3, requires_grad=True, device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('adaptive_avg_pool3d_backward_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) @skipIfMps def test_nondeterministic_alert_MaxPool3d(self, device): module = torch.nn.MaxPool3d(3) input = torch.randn(2, 3, 3, 3, requires_grad=True, device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('max_pool3d_with_indices_backward_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) @skipIfMps def test_nondeterministic_alert_AdaptiveMaxPool2d(self, device): module = torch.nn.AdaptiveMaxPool2d(3) input = torch.randn(2, 3, 3, requires_grad=True, device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('adaptive_max_pool2d_backward_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) @skipIfMps def test_nondeterministic_alert_FractionalMaxPool2d(self, device): module = torch.nn.FractionalMaxPool2d(2, output_ratio=0.5) input = torch.randn(2, 3, 3, 3, requires_grad=True, device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('fractional_max_pool2d_backward_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) @skipIfMps def test_nondeterministic_alert_FractionalMaxPool3d(self, device): module = torch.nn.FractionalMaxPool3d(2, output_ratio=0.5) input = torch.randn(2, 3, 3, 3, 3, requires_grad=True, device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('fractional_max_pool3d_backward_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) @skipIfMps def test_nondeterministic_alert_interpolate_linear(self, device): input = torch.randn(1, 2, 4, device=device, requires_grad=True) res = torch.nn.functional.interpolate( input, size=12, mode='linear', align_corners=False) grad = torch.ones_like(res) @expectedAlertNondeterministic('upsample_linear1d_backward_out_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_interpolate_bilinear(self, device): input = torch.randn(1, 2, 4, 4, device=device, requires_grad=True) res = torch.nn.functional.interpolate( input, size=12, mode='bilinear', align_corners=False) grad = torch.ones_like(res) @expectedAlertNondeterministic('upsample_bilinear2d_backward_out_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) @skipIfMps def test_nondeterministic_alert_interpolate_bicubic(self, device): input = torch.randn(1, 2, 4, 4, device=device, requires_grad=True) res = torch.nn.functional.interpolate( input, size=12, mode='bicubic', align_corners=False) grad = torch.ones_like(res) @expectedAlertNondeterministic('upsample_bicubic2d_backward_out_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) @skipIfMps def test_nondeterministic_alert_interpolate_trilinear(self, device): input = torch.randn(1, 2, 4, 4, 4, device=device, requires_grad=True) res = torch.nn.functional.interpolate( input, size=12, mode='trilinear', align_corners=False) grad = torch.ones_like(res) @expectedAlertNondeterministic('upsample_trilinear3d_backward_out_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) @skipIfMps def test_nondeterministic_alert_ReflectionPad1d(self, device): module = torch.nn.ReflectionPad1d((1, 2)) input = torch.randn(2, 3, 8, device=device, requires_grad=True) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('reflection_pad1d_backward_out_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_ReflectionPad2d(self, device): module = torch.nn.ReflectionPad2d((1, 2, 3, 4)) input = torch.randn(2, 3, 8, 8, device=device, requires_grad=True) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('reflection_pad2d_backward_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) @skipIfMps def test_nondeterministic_alert_ReflectionPad3d(self, device): module = torch.nn.ReflectionPad3d((1, 2, 3, 4, 5, 6)) input = torch.randn(2, 3, 8, 8, 8, device=device, requires_grad=True) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('reflection_pad3d_backward_out_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) @skipIfMps def test_nondeterministic_alert_ReplicationPad1d(self, device): module = torch.nn.ReplicationPad1d((1, 2)) input = torch.randn(2, 3, 4, device=device, requires_grad=True) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('replication_pad1d_backward_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_ReplicationPad2d(self, device): module = torch.nn.ReplicationPad2d((1, 2, 3, 4)) input = torch.randn(2, 3, 4, 4, device=device, requires_grad=True) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('replication_pad2d_backward_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) @skipIfMps def test_nondeterministic_alert_ReplicationPad3d(self, device): module = torch.nn.ReplicationPad3d((1, 2, 3, 4, 5, 6)) input = torch.randn(2, 3, 4, 4, 4, device=device, requires_grad=True) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('replication_pad3d_backward_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_NLLLoss(self, device): module = torch.nn.NLLLoss() input = torch.randn(2, 3, 5, 5, device=device) target = torch.rand(2, 5, 5, device=device).mul(3).floor().long() @expectedAlertNondeterministic('nll_loss2d_forward_out_cuda_template', ['cuda']) def forward_func(slf, device): module(input, target) forward_func(self, device) def test_nondeterministic_alert_CTCLoss(self, device): module = torch.nn.CTCLoss() input = torch.randn(50, 3, 15, device=device, requires_grad=True) target = torch.randint(0, 14, (3, 30), device=device) input_lengths = [50, 50, 50] target_lengths = [30, 25, 20] res = module(input, target, input_lengths, target_lengths) grad = torch.ones_like(res) @expectedAlertNondeterministic('ctc_loss_backward_gpu', ['cuda']) def backward_func(slf, device): res.backward(grad, retain_graph=True) backward_func(self, device) def test_nondeterministic_alert_EmbeddingBag_max(self, device): module = torch.nn.EmbeddingBag( 4, 3, None, 2., False, 'max', _weight=torch.randn(4, 3, device=device, requires_grad=True)) input = torch.randint(0, 3, (4, 3), device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('embedding_bag_backward_cuda_max', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_scatter_add(self, device): def test_func(op_call): input = torch.randn(5, 4, device=device) dim = 0 index = torch.tensor([[3]], device=device) src = torch.tensor([[1.0]], device=device) @expectedAlertNondeterministic('scatter_add_cuda_kernel', ['cuda']) def forward_func(slf, device): op_call(input, dim, index, src) forward_func(self, device) test_func(torch.Tensor.scatter_add_) test_func(torch.Tensor.scatter_add) test_func(torch.scatter_add) @expectedFailureMeta # expected a non-determinitic error, but it was not raised @onlyNativeDeviceTypes def test_nondeterministic_alert_put(self, device): def test_func(op_call): a = torch.randn(10, device=device) indices = torch.tensor([0, 0], device=device) values = torch.tensor([0., 1.], device=device) @expectedAlertNondeterministic('put_') def forward_func(slf, device): op_call(a, indices, values, accumulate=False) forward_func(self, device) test_func(torch.Tensor.put) test_func(torch.Tensor.put_) def test_nondeterministic_alert_put_accumulate(self, device): def test_func(op_call): a = torch.randn(10, device=device) indices = torch.tensor([0, 0], device=device) values = torch.tensor([0., 1.], device=device) @expectedAlertNondeterministic('put_', ['cuda']) def forward_func(slf, device): op_call(a, indices, values, accumulate=True) forward_func(self, device) test_func(torch.Tensor.put) test_func(torch.Tensor.put_) @skipIfMps def test_nondeterministic_alert_histc(self, device): def test_func(op_call): a = torch.tensor([], device=device) @expectedAlertNondeterministic('_histc_cuda', ['cuda']) def forward_func(slf, device): res = op_call(a, min=0, max=3) forward_func(self, device) test_func(torch.histc) test_func(torch.Tensor.histc) @skipIfMps def test_nondeterministic_alert_bincount(self, device): def test_func(op_call): a = torch.tensor([], device=device, dtype=torch.long) @expectedAlertNondeterministic('_bincount_cuda', ['cuda']) def forward_func(slf, device): res = op_call(a) forward_func(self, device) test_func(torch.bincount) test_func(torch.Tensor.bincount) # Ensures that kthvalue throws nondeterministic alerts in the correct cases @dtypes(torch.double) def test_nondeterministic_alert_kthvalue(self, device, dtype): @expectedAlertNondeterministic('kthvalue CUDA', ['cuda']) def test_func(slf, device, call_type): S = 10 k = 5 a = torch.randn(S, device=device) if call_type == 'function': torch.kthvalue(a, k) elif call_type == 'method': a.kthvalue(k) elif call_type == 'out': values = torch.empty_like(a) indices = torch.empty((), device=device, dtype=torch.long) torch.kthvalue(a, k, out=(values, indices)) else: self.fail(f"'{call_type}' is not a valid call type") test_func(self, device, 'function') test_func(self, device, 'method') test_func(self, device, 'out') @onlyNativeDeviceTypes def test_nondeterministic_alert_gather(self, device): def test_func(op_call): a = torch.randn(3, 3, device=device, requires_grad=True) dim = 0 index = torch.tensor([[0]], device=device) res = op_call(a, dim, index) grad = torch.ones_like(res) @expectedAlertNondeterministic('scatter_add_cuda_kernel', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) test_func(torch.gather) test_func(torch.Tensor.gather) @skipIfMps def test_nondeterministic_alert_grid_sample_2d(self, device): input = torch.empty(1, 1, 2, 2, device=device, requires_grad=True) grid = torch.empty(1, 1, 1, 2, device=device) res = torch.nn.functional.grid_sample(input, grid, align_corners=False) grad = torch.ones_like(res) @expectedAlertNondeterministic('grid_sampler_2d_backward_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) @skipIfMps def test_nondeterministic_alert_grid_sample_3d(self, device): input = torch.empty(1, 1, 2, 2, 2, device=device, requires_grad=True) grid = torch.empty(1, 1, 1, 2, 3, device=device) res = torch.nn.functional.grid_sample(input, grid, align_corners=False) grad = torch.ones_like(res) @expectedAlertNondeterministic('grid_sampler_3d_backward_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_invalid_shapes_grid_sampler(self, device): make_arg = partial( make_tensor, device=device, dtype=torch.float64, requires_grad=True) inputs = ( # input, grid ((5, 5, 5, 5, 5,), (1, 1, 1, 4, 4,)), # 3d ((5, 5, 5, 5,), (1, 1, 4, 4,)), # 2d ) interpolation_mode = 0 padding_mode = 0 align_corners = True err = "expected grid and input to have same batch size" for input, grid in inputs: input = make_arg(input) grid = make_arg(grid, low=-1, high=1) # Wrapper for the 2d, 3d, and cuDNN functions listed below. with self.assertRaisesRegex(RuntimeError, err): torch.grid_sampler( input, grid, interpolation_mode, padding_mode, align_corners) # Expects 2d input. with self.assertRaisesRegex(RuntimeError, err): torch.grid_sampler_2d( input, grid, interpolation_mode, padding_mode, align_corners) # Expects 3d input. with self.assertRaisesRegex(RuntimeError, err): torch.grid_sampler_3d( input, grid, interpolation_mode, padding_mode, align_corners) # Expects 2d input. with self.assertRaisesRegex(RuntimeError, err): torch._grid_sampler_2d_cpu_fallback( input, grid, interpolation_mode, padding_mode, align_corners) # Expects 2d input, on CUDA. # Doesn't work on CPU and ROCm. if device != 'cpu' and TEST_CUDNN and not TEST_WITH_ROCM: with self.assertRaisesRegex(RuntimeError, err): torch.cudnn_grid_sampler(input, grid) def test_dist(self, device): def run_test(x, y): for p in [0, 1, 2, 3, 4, inf, -inf]: dist_xy = torch.dist(x, y, p) dist_xy_norm = torch.norm(x - y, p) self.assertEqual(dist_xy, dist_xy_norm) run_test(torch.randn(5, device=device), torch.randn(5, device=device)) x = torch.zeros(3, device=device) y = torch.zeros(3, device=device) y[1] = 1. run_test(x, y) # Ensures that median throws nondeterministic alerts in the correct cases @dtypes(torch.double) def test_nondeterministic_alert_median(self, device, dtype): def test_func(slf, device, call_type): S = 10 a = torch.randn(S, device=device) if call_type == 'function': torch.median(a) elif call_type == 'function with indices': torch.median(a, 0) elif call_type == 'method': a.median() elif call_type == 'method with indices': a.median(0) elif call_type == 'out with indices': result = torch.empty_like(a) indices = torch.empty((), dtype=torch.long, device=device) torch.median(a, 0, out=(result, indices)) else: self.fail(f"'{call_type}' is not a valid call type") @expectedAlertNondeterministic('median CUDA with indices output', ['cuda']) def test_func_expect_error(slf, device, call_type): test_func(slf, device, call_type) test_func(self, device, 'function') test_func_expect_error(self, device, 'function with indices') test_func(self, device, 'method') test_func_expect_error(self, device, 'method with indices') test_func_expect_error(self, device, 'out with indices') # FIXME: move to test_scatter_gather_ops def _test_gather_backward_one_dim(self, device, deterministic: bool = False) -> None: with DeterministicGuard(deterministic): m = random.randint(2000, 3000) elems = random.randint(10 * m, 20 * m) dim = 0 src = torch.randn(m, device=device, requires_grad=True) idx = torch.randint(m, (elems,), device=device) res = torch.gather(src, dim, idx) weight = torch.rand_like(res, device=device) * 10 ** 6 res.backward(weight) grad = src.grad.detach().clone() if torch.device(device).type == 'cuda': for _ in range(2): src.grad.data.zero_() res = torch.gather(src, dim, idx) res.backward(weight) self.assertEqual(src.grad, grad, atol=0, rtol=0) else: expected = torch.zeros_like(src, device=device) for i in range(elems): expected[idx[i]] += weight[i] self.assertEqual(grad, expected, atol=0, rtol=0) # FIXME: move to test_scatter_gather_ops @onlyNativeDeviceTypes def test_gather_backward_deterministic_path(self, device) -> None: self._test_gather_backward_one_dim(device, True) # FIXME: move to test_scatter_gather_ops @onlyCPU def test_gather_backward_one_dim(self, device) -> None: self._test_gather_backward_one_dim(device, False) # FIXME: move to test_scatter_gather_ops @onlyNativeDeviceTypes def test_scatter_add_one_dim_deterministic(self, device) -> None: with DeterministicGuard(True): m = random.randint(20, 30) elems = random.randint(2000 * m, 3000 * m) dim = 0 src = torch.randn(elems, device=device) idx = torch.randint(m, (elems,), device=device) x = torch.zeros(m, device=device) res = x.scatter_add(dim, idx, src) expected = torch.zeros(m, device=device) for i in range(elems): expected[idx[i]] += src[i] self.assertEqual(res, expected, atol=0, rtol=0) # FIXME: move to test_scatter_gather_ops @onlyNativeDeviceTypes def test_scatter_zero_size_index(self, device) -> None: null_index = torch.zeros((0, 4), dtype=torch.int64) null_arr = torch.zeros((0, 4)) original = torch.arange(4, dtype=torch.float32) result = original.scatter(0, null_index, null_arr) self.assertEqual(result, original, atol=0, rtol=0) @onlyCUDA def test_sync_warning(self, device): def _sync_raises_helper(f, level): with CudaSyncGuard(level): if level == 1: with self.assertWarnsRegex(UserWarning, "called a synchronizing "): f() elif level == 2: with self.assertRaisesRegex(RuntimeError, "called a synchronizing "): f() def _no_sync_helper(f, level): with CudaSyncGuard(level): f() def _ind_put_fn(x, ind, val): x[ind] = val return x def _ind_get_fn(x, ind): return x[ind] def _cond_fn(x): if x: # taking boolean value of a tensor synchronizes return x else: return 2 * x # prepare inputs for subsequent ops size = 4 x = torch.rand(size, device=device) y = torch.rand((), device=device) ind = torch.randint(size, (3,), device=device) ind_cpu = ind.cpu() repeats = torch.full((1,), 2, device=device) mask = torch.randint(2, (size,), device=device, dtype=bool) expect_no_sync = (lambda: _ind_put_fn(x, mask, 1.), lambda: _ind_put_fn(x, ind, y), lambda: _ind_get_fn(x, ind), lambda: torch.nn.functional.one_hot(ind, num_classes=size), lambda: torch.randperm(20000, device=device), lambda: torch.repeat_interleave(x, 2, output_size=2 * size), lambda: torch.repeat_interleave(x, repeats, output_size=2 * size)) expect_sync = (lambda: _ind_put_fn(x, mask, y), lambda: _ind_put_fn(x, ind_cpu, y), lambda: _ind_get_fn(x, mask), lambda: _ind_get_fn(x, ind_cpu), lambda: x.nonzero(), lambda: _cond_fn(y), lambda: torch.nn.functional.one_hot(ind), lambda: torch.repeat_interleave(x, 2), lambda: torch.repeat_interleave(x, repeats)) for f, level in product(expect_no_sync, (1, 2)): _no_sync_helper(f, level) for f, level in product(expect_sync, (1, 2)): _sync_raises_helper(f, level) @dtypes(*floating_types_and(torch.half, torch.bfloat16)) @skipIfMps def test_log_normal(self, device, dtype): a = torch.tensor([10], dtype=dtype, device=device).log_normal_() self.assertEqual(a.dtype, dtype) self.assertEqual(a.size(), torch.Size([1])) @dtypes(*all_types_and(torch.half, torch.bfloat16)) @skipIfMps def test_geometric(self, device, dtype): a = torch.tensor([10], dtype=dtype, device=device).geometric_(0.5) self.assertEqual(a.dtype, dtype) self.assertEqual(a.size(), torch.Size([1])) @skipIfMps def test_repeat_interleave(self, device): y = torch.tensor([[1, 2], [3, 4]], device=device) # exercise single argument function signature temp = y.repeat_interleave(2) self.assertEqual(torch.Size([8]), temp.size()) for dtype in [torch.int, torch.long]: lengths = torch.tensor([1, 2], dtype=dtype, device=device) output_size = torch.sum(lengths) a = torch.repeat_interleave( y, lengths, dim=0, ) self.assertEqual(a.dtype, y.dtype) self.assertEqual(a.size(), torch.Size([3, 2])) a_with_output = torch.repeat_interleave( y, lengths, dim=0, output_size=output_size, ) self.assertEqual(a_with_output.dtype, y.dtype) self.assertEqual(a_with_output.size(), torch.Size([3, 2])) @dtypes(*floating_types()) @dtypesIfCPU(*floating_types_and(torch.bfloat16)) @dtypesIfCUDA(*floating_types_and(torch.half)) def test_bernoulli_p(self, device, dtype): for trivial_p in ([0, 1], [1, 0, 1, 1, 0, 1]): x = torch.tensor(trivial_p, dtype=dtype, device=device) self.assertEqual(x.bernoulli().tolist(), trivial_p) def isBinary(t): return torch.ne(t, 0).mul_(torch.ne(t, 1)).sum().item() == 0 p = torch.rand(5, 5, dtype=dtype, device=device) self.assertTrue(isBinary(p.bernoulli())) p = torch.rand(5, dtype=dtype, device=device).expand(5, 5) self.assertTrue(isBinary(p.bernoulli())) p = torch.rand(5, 5, dtype=dtype, device=device) torch.bernoulli(torch.rand_like(p), out=p) self.assertTrue(isBinary(p)) # RngUniform not implemented for Integral type in XLA test @dtypes(*floating_types()) @dtypesIfCPU(*all_types_and(torch.bool)) @dtypesIfCUDA(*all_types_and(torch.bool, torch.half)) def test_bernoulli_self(self, device, dtype): def isBinary(t): return torch.ne(t, 0).mul_(torch.ne(t, 1)).sum().item() == 0 t = torch.empty(10, 10, dtype=dtype, device=device) t.fill_(2) t.bernoulli_(0.5) self.assertTrue(isBinary(t)) for p_dtype in floating_types_and(*[torch.half] if device.startswith('cuda') else []): p = torch.rand(10, dtype=p_dtype, device=device).expand(10, 10) t.fill_(2) t.bernoulli_(p) self.assertTrue(isBinary(t)) t.fill_(2) torch.bernoulli(torch.rand_like(t, dtype=p_dtype), out=t) self.assertTrue(isBinary(t)) t.fill_(2) t.bernoulli_(torch.rand_like(t, dtype=p_dtype)) self.assertTrue(isBinary(t)) @slowTest @dtypes(*floating_types()) @dtypesIfCUDA(*floating_types_and(torch.half)) def test_bernoulli_edge_cases(self, device, dtype): # Need to draw a lot of samples to cover every random floating point number. a = torch.zeros(10000, 10000, dtype=dtype, device=device) # probability of drawing "1" is 0 num_ones = (torch.bernoulli(a) == 1).sum() self.assertEqual(num_ones, 0) b = torch.ones(10000, 10000, dtype=dtype, device=device) # probability of drawing "1" is 1 num_zeros = (torch.bernoulli(b) == 0).sum() self.assertEqual(num_zeros, 0) @dtypes(*floating_types_and(torch.half, torch.bfloat16)) @skipIfMps def test_exponential(self, device, dtype): a = torch.tensor([10], dtype=dtype, device=device).exponential_(0.5) self.assertEqual(a.dtype, dtype) self.assertEqual(a.size(), torch.Size([1])) # Tests extremal behavior tests = ((-0, float('inf')), (0, float('inf')), (float('inf'), 0)) for test in tests: t = torch.empty((1,), device=device, dtype=dtype).exponential_(test[0]) self.assertTrue(t.item() == test[1]) # Tests that negative lambda fails with self.assertRaises(RuntimeError): torch.empty((1,), device=device, dtype=dtype).exponential_(-0.5) @onlyCUDA @dtypes(torch.half, torch.float) def test_exponential_no_zero(self, device, dtype): # naively, 0 in exponential can be generated with probability 2^-24 # so we need more samples to check if it's not generated # instead of doing one # don't test CPU, that would be a long test x = torch.empty(50000000, device=device, dtype=dtype).exponential_() self.assertTrue(x.min() > 0) def _generate_correlation_tensors(self, device, dtype): yield make_tensor((0, 0), dtype=dtype, device=device) yield make_tensor((1, 0), dtype=dtype, device=device) yield make_tensor((0, 1), dtype=dtype, device=device) yield make_tensor((2,), dtype=dtype, device=device) yield make_tensor((2, 1), dtype=dtype, device=device) yield make_tensor((2, 2), dtype=dtype, device=device) yield make_tensor((2, 3), dtype=dtype, device=device) yield make_tensor((5, 10), dtype=dtype, device=device) yield make_tensor((5, 10), dtype=dtype, device=device, noncontiguous=True) if dtype != torch.int: yield torch.tensor([0, -2, nan, 10.2, inf], dtype=dtype, device=device) @onlyNativeDeviceTypes @dtypes(torch.int, torch.float, torch.cfloat) def test_corrcoef(self, device, dtype): for x in self._generate_correlation_tensors(device, dtype): res = torch.corrcoef(x) ref = np.corrcoef(x.cpu().numpy()) self.assertEqual(res, ref, exact_dtype=False) @dtypes(torch.int, torch.float, torch.cfloat) def test_cov(self, device, dtype): def check(t, correction=1, fweights=None, aweights=None): res = torch.cov(t, correction=correction, fweights=fweights, aweights=aweights) t = t.cpu().numpy() fweights = fweights.cpu().numpy() if fweights is not None else None aweights = aweights.cpu().numpy() if aweights is not None else None ref = np.cov(t, ddof=correction, fweights=fweights, aweights=aweights) self.assertEqual(res, ref, atol=1e-05, rtol=1e-05, exact_dtype=False) for x in self._generate_correlation_tensors(device, dtype): check(x) num_observations = x.numel() if x.ndim < 2 else x.size(1) if num_observations > 0: fweights = torch.randint(1, 10, (num_observations,), device=device) aweights = make_tensor((num_observations,), dtype=torch.float, device=device, low=1) for correction, fw, aw in product([0, 1, 2], [None, fweights], [None, aweights]): check(x, correction, fweights, aweights) @skipIfNoSciPy @dtypes(*floating_types_and(torch.half, torch.bfloat16)) def test_uniform_kstest(self, device, dtype): from scipy import stats size = 1000 for from_ in [-42, 0, 4.2]: for to_ in [-4.2, 0, 42]: if to_ > from_: t = torch.empty(size, dtype=dtype, device=device).uniform_(from_, to_) res = stats.kstest(t.cpu().to(torch.double), 'uniform', args=(from_, (to_ - from_))) self.assertTrue(res.statistic < 0.1) @skipIfNoSciPy @dtypes(*floating_types_and(torch.half)) @dtypesIfCUDA(*floating_types_and(torch.half, torch.bfloat16)) def test_normal_kstest(self, device, dtype): from scipy import stats size = 1000 for mean in [-10, 0, 50]: for std in [1, 5, 10]: t = torch.empty(size, dtype=dtype, device=device).normal_(mean=mean, std=std) res = stats.kstest(t.cpu().to(torch.double), 'norm', args=(mean, std)) self.assertTrue(res.statistic < 0.1) @skipIfMps @skipIfNoSciPy @dtypes(*floating_types_and(torch.half, torch.bfloat16)) def test_lognormal_kstest(self, device, dtype): from scipy import stats size = 1000 for mean in [-3, 0, 7]: for std in [1, 5, 7]: t = torch.empty(size, dtype=dtype, device=device).log_normal_(mean=mean, std=std) res = stats.kstest(t.cpu().to(torch.double), 'lognorm', args=(std, 0, math.exp(mean))) if dtype == torch.half: self.assertTrue(res.statistic < 0.3) else: self.assertTrue(res.statistic < 0.1) @skipIfMps @skipIfNoSciPy @dtypes(*floating_types_and(torch.half, torch.bfloat16)) def test_exponential_kstest(self, device, dtype): from scipy import stats size = 1000 for lambd in [0.5, 1.0, 5.0]: t = torch.empty(size, dtype=dtype, device=device).exponential_(lambd=lambd) res = stats.kstest(t.cpu().to(torch.double), 'expon', args=(0, 1 / lambd,)) self.assertTrue(res.statistic < 0.1) @skipIfMps @skipIfNoSciPy @dtypes(*floating_types_and(torch.half, torch.bfloat16)) def test_cauchy_kstest(self, device, dtype): from scipy import stats size = 1000 for median in [-10, 0, 50]: for sigma in [0.5, 1.0, 10.0]: t = torch.empty(size, dtype=dtype, device=device).cauchy_(median=median, sigma=sigma) res = stats.kstest(t.cpu().to(torch.double), 'cauchy', args=(median, sigma)) self.assertTrue(res.statistic < 0.1) @slowTest @onlyCUDA @dtypes(torch.bfloat16, torch.float32) def test_cauchy_no_inf(self, device, dtype): # torch.float16 will have `inf` because of its smaller range. for _ in range((2**16) * 2): x = torch.empty((2**16), dtype=dtype, device=device) x.cauchy_() self.assertFalse(x.isinf().sum()) @skipIfMps @skipIfNoSciPy @dtypes(*all_types_and(torch.half, torch.bfloat16)) def test_geometric_kstest(self, device, dtype): from scipy import stats size = 1000 for p in [0.2, 0.5, 0.8]: t = torch.empty(size, dtype=dtype, device=device).geometric_(p=p) actual = np.histogram(t.cpu().to(torch.double), np.arange(1, 100))[0] expected = stats.geom(p).pmf(np.arange(1, 99)) * size res = stats.chisquare(actual, expected) self.assertEqual(res.pvalue, 1.0, atol=0.1, rtol=0) # FIXME: find test suite for pdist and cdist def test_pairwise_distance_empty(self, device): shape = (2, 0) x = torch.randn(shape, device=device) y = torch.randn(shape, device=device) self.assertEqual(torch.zeros(2, device=device), torch.pairwise_distance(x, y)) self.assertEqual(torch.zeros((2, 1), device=device), torch.pairwise_distance(x, y, keepdim=True)) shape = (0, 2) x = torch.randn(shape, device=device) y = torch.randn(shape, device=device) self.assertEqual(torch.zeros(0, device=device), torch.pairwise_distance(x, y)) self.assertEqual(torch.zeros((0, 1), device=device), torch.pairwise_distance(x, y, keepdim=True)) def test_pdist_empty(self, device): shape = (0, 2) x = torch.randn(shape, device=device) self.assertEqual(torch.empty(0, device=device), torch.pdist(x)) shape = (1, 2) x = torch.randn(shape, device=device) self.assertEqual(torch.empty(0, device=device), torch.pdist(x)) shape = (3, 0) x = torch.randn(shape, device=device) self.assertEqual(torch.zeros(3, device=device), torch.pdist(x)) def test_cdist_empty(self, device): x = torch.randn((0, 5), device=device) y = torch.randn((4, 5), device=device) self.assertEqual(torch.empty(0, 4, device=device), torch.cdist(x, y)) x = torch.randn((2, 5), device=device) y = torch.randn((0, 5), device=device) self.assertEqual(torch.empty(2, 0, device=device), torch.cdist(x, y)) x = torch.randn((2, 0), device=device) y = torch.randn((3, 0), device=device) self.assertEqual(torch.zeros(2, 3, device=device), torch.cdist(x, y)) x = torch.randn((2, 0), device=device) y = torch.randn((0, 0), device=device) self.assertEqual(torch.empty(2, 0, device=device), torch.cdist(x, y)) def _brute_cdist(self, x, y, p=2): r1 = x.shape[-2] r2 = y.shape[-2] if r1 == 0 or r2 == 0: return torch.empty(r1, r2, device=x.device) return torch.norm(x[..., None, :] - y[..., None, :, :], p=p, dim=-1) @skipIfMps def test_cdist_norm(self, device): for r1 in [3, 4, 5, 6]: for m in [2, 3, 4, 10]: for r2 in [4, 6, 7, 8]: for p in [0, 1, 2, 3, 1.5, 2.5, float('inf')]: x = torch.randn(r1, m, device=device) y = torch.randn(r2, m, device=device) if p == 2: for cm in ['use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']: actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertEqual(expected, actual, rtol=0, atol=0.02) else: actual = torch.cdist(x, y, p=p) expected = self._brute_cdist(x, y, p=p) self.assertEqual(expected, actual) @skipIfMps def test_cdist_norm_batch(self, device): for r1 in [3, 4, 5, 6]: for m in [2, 3, 4, 10]: for r2 in [4, 6, 7, 8]: for p in [0, 1, 2, 3, 1.5, 2.5, float('inf')]: x = torch.randn(2, 3, 6, r1, m, device=device) y = torch.randn(2, 3, 6, r2, m, device=device) if p == 2: for cm in ['use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']: actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertEqual(expected, actual, rtol=0, atol=0.02) else: actual = torch.cdist(x, y, p=p) expected = self._brute_cdist(x, y, p=p) self.assertEqual(expected, actual) @onlyCUDA def test_cdist_cuda_backward(self, device): for l1 in [1, 511, 513]: for l2 in [1, 511, 513]: for p in [0, 1, 2, 3, 1.5, 2.5, float('inf')]: x1 = torch.randn(4, l1, 32, device=device, requires_grad=True) x2 = x1.clone().detach_().requires_grad_() y1 = torch.randn(4, l2, 32, device=device, requires_grad=True) y2 = y1.clone().detach_().requires_grad_() if p == 2: for cm in ['use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']: z1 = torch.cdist(x1, y1, p=2, compute_mode=cm).mean() z2 = self._brute_cdist(x2, y2, p=2).mean() z1.backward() z2.backward() self.assertEqual(x1.grad, x2.grad, rtol=0, atol=0.001) self.assertEqual(y1.grad, y2.grad, rtol=0, atol=0.001) else: z1 = torch.cdist(x1, y1, p=p).mean() z2 = self._brute_cdist(x2, y2, p=p).mean() self.assertEqual(x1.grad, x2.grad, rtol=0, atol=0.001) self.assertEqual(y1.grad, y2.grad, rtol=0, atol=0.001) @tf32_on_and_off(0.005) def test_cdist_large(self, device): for cm in ['use_mm_for_euclid_dist_if_necessary', 'use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']: x = torch.randn(1000, 10, device=device) y = torch.randn(1000, 10, device=device) actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertEqual(expected, actual) @slowTest @tf32_on_and_off(0.01) def test_cdist_large_batch(self, device): for cm in ['use_mm_for_euclid_dist_if_necessary', 'use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']: x = torch.randn(4, 3, 1000, 10, device=device) y = torch.randn(4, 3, 1000, 10, device=device) actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertEqual(expected, actual) @tf32_on_and_off(0.005) def test_cdist_non_contiguous(self, device): for cm in ['use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']: x = torch.randn(5, 7, device=device).mT y = torch.randn(5, 3, device=device).mT actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertFalse(x.is_contiguous()) self.assertFalse(y.is_contiguous()) self.assertEqual(expected, actual) x = torch.randn(7, 5, device=device) y = torch.randn(5, 3, device=device).t() actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertTrue(x.is_contiguous()) self.assertFalse(y.is_contiguous()) self.assertEqual(expected, actual) x = torch.randn(5, 7, device=device).t() y = torch.randn(3, 5, device=device) actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertFalse(x.is_contiguous()) self.assertTrue(y.is_contiguous()) self.assertEqual(expected, actual) @tf32_on_and_off() def test_cdist_non_contiguous_batch(self, device): for cm in ['use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']: x = torch.randn(4, 3, 2, 5, 7, device=device).mT y = torch.randn(4, 3, 2, 5, 3, device=device).mT actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertFalse(x.is_contiguous()) self.assertFalse(y.is_contiguous()) self.assertEqual(expected, actual) x = torch.randn(7, 2, 7, 5, device=device) y = torch.randn(7, 2, 5, 3, device=device).mT actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertTrue(x.is_contiguous()) self.assertFalse(y.is_contiguous()) self.assertEqual(expected, actual) x = torch.randn(4, 5, 7, device=device).mT y = torch.randn(4, 3, 5, device=device) actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertFalse(x.is_contiguous()) self.assertTrue(y.is_contiguous()) self.assertEqual(expected, actual) # Maybe merge into OpInfo? def test_cdist_euclidean_large(self, device): def _test_euclidean_large_cdist(sizex, sizey=None): if sizey is None: sizey = sizex x = torch.randn(sizex, device=device, dtype=torch.float) y = torch.randn(sizey, device=device, dtype=torch.float) eps = 1e-6 # to avoid extremum x = x - (((x - y) < eps).float() * 2 * eps) x.requires_grad = True y.requires_grad = True dist = torch.cdist(x, y, p=2) # Do a backward pass to check that it is valid for large # matrices loss = dist.sum() loss.backward() _test_euclidean_large_cdist((2000, 5)) # Ensure that cdist backward with p<1 does not produce NaNs @skipIfMps def test_cdist_grad_p_lt_1_no_nan(self, device): for p in [0.99, 0.7, 0.5, 0.1, 0.01]: x = torch.randn(1, 2, device=device) y = x.clone().detach() + torch.tensor([[1., 0.]], device=device) x.requires_grad = True y.requires_grad = True result = torch.cdist(x, y, p=p) result.backward(torch.ones_like(result)) self.assertFalse(torch.isnan(x.grad).any()) self.assertFalse(torch.isnan(y.grad).any()) def test_cdist_same_inputs(self, device): # Test to detect issues in cdist gradient calculation # When the distances are 0 sizex = (1, 27, 32) for p in [0, 1, 2, 3, 1.5, 2.5, float('inf')]: x = torch.randn(sizex, device=device, dtype=torch.float) dist_grad = torch.randn((1, 27, 27), device=device, dtype=torch.float) y = x.clone() eps = 1e-6 x.requires_grad = True d = torch.cdist(x, y) d.backward(dist_grad) # Check that the backward passs does not contain invalid # values such as nan or inf assert torch.isfinite(x.grad).all() @skipIfMps def test_cumsum(self, device): x = torch.rand(100, 100, device=device) res1 = torch.cumsum(x, 1) res2 = torch.tensor([]).to(device) torch.cumsum(x, 1, out=res2) self.assertEqual(res1, res2) x.cumsum_(1) self.assertEqual(res1, x) a = torch.tensor([[True, False, True], [False, False, False], [True, True, True]], device=device) b = a.byte() aRes = torch.cumsum(a, 0) bRes = torch.cumsum(b, 0) self.assertEqual(aRes, bRes) self.assertEqual(aRes, torch.tensor([[1, 0, 1], [1, 0, 1], [2, 1, 2]])) aRes = torch.cumsum(a, 1) bRes = torch.cumsum(b, 1) self.assertEqual(aRes, bRes) self.assertEqual(aRes, torch.tensor([[1, 1, 2], [0, 0, 0], [1, 2, 3]])) # Check that cummulative sum over a zero length dimension doesn't crash on backprop. # Also check that cumsum over other dimensions in a tensor with a zero-length # dimensiuon also works # Also include a basic suite of similar tests for other bases cases. shapes = [[2, 0], [2, 1, 4], [0, 2, 3], [1], [5]] for shape in shapes: for dim in range(len(shape)): raw_tensor = torch.zeros(*shape, requires_grad=True) integrated = raw_tensor.cumsum(dim=dim) # Check that backward does not crash integrated.sum().backward() # Check that output maintained correct shape self.assertEqual(raw_tensor.shape, raw_tensor.grad.shape) # Check a scalar example raw_tensor = torch.tensor(3., requires_grad=True) integrated = raw_tensor.cumsum(dim=-1) self.assertEqual(raw_tensor, integrated) # Check that backward does not crash integrated.sum().backward() # Check that output maintained correct shape self.assertEqual(raw_tensor.shape, raw_tensor.grad.shape) @skipIfMps def test_cumprod(self, device): x = torch.rand(100, 100, device=device) res1 = torch.cumprod(x, 1) res2 = torch.tensor([]).to(device) torch.cumprod(x, 1, out=res2) self.assertEqual(res1, res2) x.cumprod_(1) self.assertEqual(res1, x) a = torch.tensor([[True, False, True], [False, False, False], [True, True, True]], dtype=torch.bool, device=device) b = a.byte() aRes = torch.cumprod(a, 0) bRes = torch.cumprod(b, 0) self.assertEqual(aRes, bRes) self.assertEqual(aRes, torch.tensor([[1, 0, 1], [0, 0, 0], [0, 0, 0]])) aRes = torch.cumprod(a, 1) bRes = torch.cumprod(b, 1) self.assertEqual(aRes, bRes) self.assertEqual(aRes, torch.tensor([[1, 0, 0], [0, 0, 0], [1, 1, 1]])) # Check that cummulative prod over a zero length dimension doesn't crash on backprop. # Also check that cumprod over other dimensions in a tensor with a zero-length # dimensiuon also works # Also include a basic suite of similar tests for other bases cases. shapes = [[2, 0], [2, 1, 4], [0, 2, 3], [1], [5]] for shape in shapes: for dim in range(len(shape)): raw_tensor = torch.zeros(*shape, requires_grad=True) integrated = raw_tensor.cumprod(dim=dim) # Check that backward does not crash integrated.sum().backward() # Check that output maintained correct shape self.assertEqual(raw_tensor.shape, raw_tensor.grad.shape) # Check a scalar example raw_tensor = torch.tensor(3., requires_grad=True) integrated = raw_tensor.cumprod(dim=-1) self.assertEqual(raw_tensor, integrated) # Check that backward does not crash integrated.sum().backward() # Check that output maintained correct shape self.assertEqual(raw_tensor.shape, raw_tensor.grad.shape) @skipIfMps def test_cummax_cummin(self, device): def test_ops(op, string_of_function_name, expected_output1, expected_output2): x = torch.rand(100, 100, device=device) out1 = op(x, 1) res2 = torch.empty(0, device=device) indices2 = torch.empty(0, dtype=torch.int64, device=device) op(x, 1, out=(res2, indices2)) self.assertEqual(out1[0], res2) self.assertEqual(out1[1], indices2) a = torch.tensor([[True, False, True], [False, False, False], [True, True, True]], dtype=torch.bool, device=device) b = a.byte() aRes = op(a, 0) bRes = op(b, 0) self.assertEqual(aRes[0], bRes[0].bool()) self.assertEqual(aRes[0], expected_output1.bool()) # test inf and nan input x = torch.tensor([4, inf, 1.5, -inf, 0, nan, 1]) xRes = op(x, 0)[0] self.assertEqual(xRes, expected_output2) # op shouldn't support values, indices with a dtype, device type or layout # different from that of input tensor t = torch.randn(10) values = torch.empty(0, dtype=torch.int16) indices = torch.empty(0, dtype=torch.int64) with self.assertRaisesRegex( RuntimeError, 'expected scalar_type Float but found Short'): op(t, 0, out=(values, indices)) # Check that op over a zero length dimension doesn't crash on backprop. # Also check that op over other dimensions in a tensor with a zero-length # dimension also works # Also include a basic suite of similar tests for other bases cases. shapes = [[2, 0], [2, 1, 4], [0, 2, 3], [1], [5]] for shape in shapes: for dim in range(len(shape)): raw_tensor = torch.zeros(*shape, requires_grad=True) integrated = getattr(raw_tensor, string_of_function_name)(dim=dim) # Check that backward does not crash integrated[0].sum().backward() # Check that output maintained correct shape self.assertEqual(raw_tensor.shape, raw_tensor.grad.shape) # Check a scalar example raw_tensor = torch.tensor(3., requires_grad=True) integrated = getattr(raw_tensor, string_of_function_name)(dim=-1) # Check that backward does not crash integrated[0].sum().backward() # Check that output maintained correct shape self.assertEqual(raw_tensor.shape, raw_tensor.grad.shape) expected_out = torch.tensor([4, inf, inf, inf, inf, nan, nan]) test_ops(torch.cummax, "cummax", torch.tensor([[1, 0, 1], [1, 0, 1], [1, 1, 1]]), expected_out) expected_out = torch.tensor([4, 4, 1.5, -inf, -inf, nan, nan]) test_ops(torch.cummin, "cummin", torch.tensor([[1, 0, 1], [0, 0, 0], [0, 0, 0]]), expected_out) @skipIfMps def test_logcumsumexp(self, device): def logcumsumexp(a, axis): return torch.cumsum(a.exp(), axis=axis).log_() axis = -1 a = torch.randn(100, 100, device=device) actual = a.logcumsumexp(axis) expected = logcumsumexp(a, axis) self.assertEqual(a.dtype, actual.dtype) self.assertEqual(expected.shape, actual.shape) self.assertEqual(expected, actual) # check -inf and nan handling x = torch.tensor([-float('inf'), -float('inf'), 1.0, 1.0, float('inf'), float('inf'), float('nan'), 1.0, 1.0], device=device) x2d = x.unsqueeze(0).expand(2, -1) for inp in (x, x2d): actual = inp.logcumsumexp(axis) expected = logcumsumexp(inp, axis) self.assertEqual(expected, actual) # Check that out is actually inplace b = torch.randn(5, 2, device=device) inplace_out = torch.zeros(5, 2, device=device) expected = logcumsumexp(b, axis) torch.logcumsumexp(b, axis=axis, out=inplace_out) self.assertEqual(inplace_out, expected) # Check input and inplace_output type mismatch b = torch.randn(5, 2, device=device, dtype=torch.float64) inplace_out = torch.zeros(5, 2, device=device, dtype=torch.float32) with self.assertRaisesRegex( RuntimeError, 'expected scalar_type Double but found Float'): torch.logcumsumexp(b, axis, out=inplace_out) def _test_diff_numpy(self, t, dims=None): # Helper for test_diff to compare with NumPy reference implementation def to_np(t): if t.dtype == torch.bfloat16: return t.to(dtype=torch.float, device="cpu").numpy() else: return t.cpu().numpy() for dim in dims if dims else range(t.dim()): prepend = t.narrow(dim, 0, 1) append = t.narrow(dim, 0, 1) np_t = to_np(t) # test when no prepend and append for n in range(t.size(dim)): actual = torch.diff(t, dim=dim, n=n) expected = torch.from_numpy(np.diff(np_t, axis=dim, n=n)) self.assertEqual(actual, expected.to(t.dtype)) # test when prepend and append's size along dim is 1 for n in range(1, t.size(dim) + 4): actual = torch.diff(t, dim=dim, n=n, prepend=prepend, append=append) expected = torch.from_numpy(np.diff(np_t, axis=dim, n=n, prepend=to_np(prepend), append=to_np(append))) self.assertEqual(actual, expected.to(t.dtype)) # test when prepend and append's size along dim != 1 for n in range(1, t.size(dim) * 3): actual = torch.diff(t, dim=dim, n=n, prepend=t, append=t) expected = torch.from_numpy(np.diff(np_t, axis=dim, n=n, prepend=np_t, append=np_t)) self.assertEqual(actual, expected.to(t.dtype)) # All tensors appear contiguous on XLA @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half, torch.bool)) def test_diff_noncontig(self, device, dtype): shapes = ( (1,), (1, 5), (3, 5), (1, 5, 1), (2, 3, 5)) for shape in shapes: contig = make_tensor(shape, dtype=dtype, device=device, low=-9, high=9) non_contig = torch.empty(shape + (2, 2), device=device, dtype=dtype)[..., 0] non_contig = non_contig.select(-1, -1) non_contig.copy_(contig) self.assertTrue(not non_contig.is_contiguous() or shape == (1,)) self._test_diff_numpy(non_contig) # RngNormal not implemented for type f16 for XLA @dtypes(*all_types_and_complex_and(torch.bool)) @dtypesIfCPU(*all_types_and_complex_and(torch.half, torch.bool)) @dtypesIfCUDA(*all_types_and_complex_and(torch.half, torch.bool)) def test_diff(self, device, dtype): shapes = ( (1,), (1, 5), (3, 5), (1, 5, 1), (2, 3, 5)) for shape in shapes: contig = make_tensor(shape, dtype=dtype, device=device, low=-9, high=9) self._test_diff_numpy(contig) t = torch.ones(2, 3) with self.assertRaisesRegex( RuntimeError, 'diff expects prepend or append to be the same dimension as input'): invalid_prepend = torch.tensor([1, 2, 3], device=device, dtype=dtype) t.diff(dim=0, prepend=invalid_prepend) with self.assertRaisesRegex( RuntimeError, 'diff expects the shape of tensor to prepend or append to match that of input'): invalid_prepend = torch.tensor([[0, 1]], device=device, dtype=dtype) t.diff(dim=0, prepend=invalid_prepend) with self.assertRaisesRegex( RuntimeError, 'diff expects input to be at least one-dimensional'): scalar = torch.tensor(2, device=device, dtype=dtype) torch.diff(scalar) # if the given input arg is not a list, it returns a list of single element: [arg] def _wrap_to_list(self, input_array): return input_array if isinstance(input_array, list) else [input_array] # To ensure inf, -inf, and nan values do not cause divergence between Numpy and PyTorch. # There are two types of possible divergence: # 1. When we compute a,b both real numbers and has very small absolute values (i.e. very near to 0.0) # then, result of a/b be inf, -inf and nan, and this cause divergence. # 2. When we are dividing complex numbers by zero. For example, when a = torch.tensor(3+5j) we have # a/0 to be equal to nan + nan*j in PyTorch and inf + inf*j in Numpy. def _inf_nan_preprocess(self, actual, expected): for i in range(len(expected)): expected[i] = np.nan_to_num(expected[i], nan=nan, posinf=nan, neginf=nan) # nan_to_num is not defined for complex tensors in PyTorch. if actual[i].dtype == torch.complex64 : actual[i].real = torch.nan_to_num(actual[i].real, nan=nan, posinf=nan, neginf=nan) actual[i].imag = torch.nan_to_num(actual[i].imag, nan=nan, posinf=nan, neginf=nan) else: actual[i] = torch.nan_to_num(actual[i], nan=nan, posinf=nan, neginf=nan) return actual, expected @onlyNativeDeviceTypes @dtypes(torch.long, torch.float32, torch.complex64) def test_gradient_all(self, device, dtype): def create_scalar(shape): return make_tensor((1,), device='cpu', dtype=dtype, low=1.).item() def create_list(shape): return make_tensor((len(shape),), device='cpu', dtype=dtype, low=1.).tolist() def create_coordinate_tensors(shape): tensor_list = [] for i in range(len(shape)): tensor_list.append(make_tensor((shape[i],), device=device, dtype=dtype)) return tensor_list def filter_shape(shape, dim): filtered_shape = [] for i in range(len(dim)): filtered_shape.append(shape[dim[i]]) return filtered_shape # shape, dims format test_cases = ( ((5,), (0,)), ((4, 4), (0, 1)), ((3, 3, 3), (-1, 0)), ((4, 4, 4), (2,)), ((4, 4, 4), (0, 1)), ((4, 4, 4, 3), (0, 2, 3)), ((4, 5, 3, 4, 3), (1, 2)), ((4, 3, 6, 5, 3), (2, 4)), ((4, 3, 3, 5, 3), (0, 1, 2, 3, 4)), ((1, 3, 3), (1, 2)), ((1, 5), (1,)), ) for case, contig, edge_order, space_fn in product(test_cases, [True, False], [1, 2], (create_scalar, create_list, create_coordinate_tensors)): shape, dims = case # filter shape by dims before passing filtered shape to create_* functions filtered_shape = filter_shape(shape, dims) spacing = space_fn(filtered_shape) t = make_tensor(shape, device=device, dtype=dtype, noncontiguous=not contig) t_np = t.cpu().numpy() actual = torch.gradient(t, spacing=spacing, dim=dims, edge_order=edge_order) if space_fn == create_coordinate_tensors and spacing[0].device != 'cpu': spacing = [space.cpu().detach().numpy() for space in spacing] expected = np.gradient(t_np, *self._wrap_to_list(spacing), axis=dims, edge_order=edge_order) actual, expected = self._inf_nan_preprocess(list(actual), self._wrap_to_list(expected)) self.assertEqual(actual, expected, equal_nan=True, atol=1e-4, rtol=0, exact_dtype=False) @onlyNativeDeviceTypes @dtypes(torch.long, torch.float32, torch.complex64) def test_gradient_extreme_cases(self, device, dtype): # Test behaviour for inf and nan values actual = torch.gradient(torch.tensor([2, -2, inf, inf, -inf, -inf, inf, 3, -inf, 2, nan, nan, 3, inf, nan])) expected = np.gradient(np.array([2, -2, inf, inf, -inf, -inf, inf, 3, -inf, 2, nan, nan, 3, inf, nan])) self.assertEqual(actual, self._wrap_to_list(expected), exact_dtype=False) # Test behaviour in very big tensors large_size = 100000 t = make_tensor((large_size,), dtype=dtype, device=device) t_np = t.cpu().numpy() coordinates_np = list(np.random.randn(large_size)) coordinates = [torch.tensor(coordinates_np, device=device)] actual = torch.gradient(t, spacing=coordinates, dim=0, edge_order=1) expected = [np.gradient(t_np, coordinates_np, axis=0, edge_order=1)] self.assertEqual(actual, expected, exact_dtype=False) actual = torch.gradient(t, spacing=coordinates, dim=0, edge_order=2) expected = [np.gradient(t_np, coordinates_np, axis=0, edge_order=2)] self.assertEqual(actual, expected, exact_dtype=False) @onlyNativeDeviceTypes def test_gradient_type_promotion(self, device): inputs = ( make_tensor((4, 4), device=device, dtype=torch.float32), make_tensor((4, 4), device=device, dtype=torch.complex64), make_tensor((4, 4), device=device, dtype=torch.int64), ) spacing = ( make_tensor((1,), device='cpu', dtype=torch.float32).item(), make_tensor((1,), device='cpu', dtype=torch.int64).item(), make_tensor((1,), device='cpu', dtype=torch.complex64).item(), make_tensor((2,), device='cpu', dtype=torch.float32, low=0.1).tolist(), make_tensor((2,), device='cpu', dtype=torch.int64, low=1).tolist(), make_tensor((2,), device='cpu', dtype=torch.complex64).tolist(), [make_tensor((4,), device=device, dtype=torch.float32), make_tensor((4,), device=device, dtype=torch.float32)], [make_tensor((4,), device=device, dtype=torch.int64), make_tensor((4,), device=device, dtype=torch.int64)], [make_tensor((4,), device=device, dtype=torch.complex64), make_tensor((4,), device=device, dtype=torch.complex64)], ) for input, spacing_or_coord, edge_order in product(inputs, spacing, [1, 2]): input_np = input.cpu().numpy() input_np = input.cpu().numpy() actual = torch.gradient(input, spacing=spacing_or_coord, dim=(0, 1), edge_order=edge_order) spacing_or_coord_wrapped = self._wrap_to_list(spacing_or_coord) spacing_or_coord_np = [] if torch.is_tensor(spacing_or_coord_wrapped[0]) and torch.device(spacing_or_coord_wrapped[0].device).type != 'cpu': for i in range(len(spacing_or_coord_wrapped)): spacing_or_coord_np.append(spacing_or_coord_wrapped[i].detach().clone().cpu().numpy()) else: spacing_or_coord_np = spacing_or_coord_wrapped expected = np.gradient(input_np, *spacing_or_coord_np, axis=(0, 1), edge_order=edge_order) if actual[0].dtype == torch.complex64 and input.dtype != torch.complex64: for i in range(len(actual)): self.assertEqual(actual[i].real, expected[i].real, exact_dtype=False) # Type promotion fails on Numpy when spacing is given as complex number and input is given as real. # Result is given just as real number and all the imaginary parts to be equal to zero. self.assertEqual(expected[i].imag, torch.zeros(actual[i].shape), exact_dtype=False) else: actual, expected = self._inf_nan_preprocess(list(actual), expected) self.assertEqual(actual, expected, equal_nan=True, exact_dtype=False) def _test_large_cum_fn_helper(self, x, fn): x_cpu = x.cpu().float() expected = fn(x_cpu) actual = fn(x).cpu().float() self.assertEqual(expected, actual.cpu().float()) @unittest.skipIf(IS_FBCODE and IS_REMOTE_GPU, "sandcastle OOM with current tpx gpu/re configuration") @onlyCUDA @dtypes(torch.half) # only small dtype not to get oom def test_large_cumsum(self, device, dtype): # initialization to avoid overflow and half caveats x = torch.empty(2**30 + 200, device=device, dtype=dtype) x[::3] = -3 x[1::3] = 2 x[2::3] = 1 self._test_large_cum_fn_helper(x, lambda x: torch.cumsum(x, 0)) @onlyCUDA @dtypes(torch.half) # only small dtype not to get oom def test_large_cumprod(self, device, dtype): # initialization to avoid overflow and half caveats x = torch.empty(2**30 + 200, device=device, dtype=dtype) x[::3] = 8 x[1::3] = .25 x[2::3] = .5 self._test_large_cum_fn_helper(x, lambda x: torch.cumprod(x, 0)) @skipIfMps def test_discontiguous_out_cumsum(self, device): x = torch.randn(4, 8, device=device) y = torch.empty(4, 16, device=device)[:, ::2] out = torch.cumsum(x, 0) torch.cumsum(x, 0, out=y) self.assertFalse(y.is_contiguous()) self.assertEqual(out, y, atol=0., rtol=0.) def _test_cumminmax_helper(self, x, fn, expected_val, expected_ind): val, ind = fn(x, -1) self.assertEqual(val, expected_val, atol=0, rtol=0) self.assertEqual(ind, expected_ind, atol=0, rtol=0) out_val = torch.empty_like(val).t().contiguous().t() out_ind = torch.empty_like(ind).t().contiguous().t() fn(x, -1, out=(out_val, out_ind)) self.assertFalse(out_val.is_contiguous()) self.assertFalse(out_ind.is_contiguous()) self.assertEqual(out_val, expected_val, atol=0, rtol=0) self.assertEqual(out_ind, expected_ind, atol=0, rtol=0) @skipIfMps def test_cummax_discontiguous(self, device): x = torch.tensor([[0, 1, 2, 3, 2, 1], [4, 5, 6, 5, 6, 7]], device=device, dtype=torch.float).t().contiguous().t() expected_val = torch.tensor([[0, 1, 2, 3, 3, 3], [4, 5, 6, 6, 6, 7]], device=device, dtype=torch.float) expected_ind = torch.tensor([[0, 1, 2, 3, 3, 3], [0, 1, 2, 2, 4, 5]], device=device, dtype=torch.long) self._test_cumminmax_helper(x, torch.cummax, expected_val, expected_ind) @skipIfMps def test_cummin_discontiguous(self, device): x = torch.tensor([[3, 2, 1, 0, 1, 2], [7, 6, 5, 4, 5, 2]], device=device, dtype=torch.float).t().contiguous().t() expected_val = torch.tensor([[3, 2, 1, 0, 0, 0], [7, 6, 5, 4, 4, 2]], device=device, dtype=torch.float) expected_ind = torch.tensor([[0, 1, 2, 3, 3, 3], [0, 1, 2, 3, 3, 5]], device=device, dtype=torch.long) self._test_cumminmax_helper(x, torch.cummin, expected_val, expected_ind) def test_bool_tensor_value_change(self, device): x = torch.tensor([True, False], dtype=torch.bool, device=device) x[0] = False x[1] = True self.assertEqual(x, torch.tensor([False, True], dtype=torch.bool, device=device)) # FIXME: move to shape ops test suite def test_unfold_all_devices_and_dtypes(self, device): for dt in all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16): if dt == torch.bool: x = torch.empty((0, 1, 3, 0), dtype=dt, device=device) self.assertEqual((0, 1, 1, 0, 3), x.unfold(2, 3, 2).shape) else: x = torch.empty((0, 1, 3, 0), dtype=dt, device=device) self.assertEqual((0, 1, 1, 0, 3), x.unfold(2, 3, 2).shape) # FIXME: move to shape ops test suite def test_unfold_scalars(self, device): x = torch.tensor(0.5, device=device) # unfold on a 0-dimensional tensor should always return a 1-d dimensional # tensor of shape [size] (i.e., the second parameter to unfold) self.assertEqual(torch.empty(0, device=device), x.unfold(0, 0, 1)) self.assertEqual(torch.empty(0, device=device), x.unfold(0, 0, 2)) self.assertEqual(torch.tensor([0.5], device=device), x.unfold(0, 1, 1)) # FIXME: move to data movement test suite def test_copy_all_dtypes_and_devices(self, device): from copy import copy for dt in all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16): x = torch.tensor([1, 2, 3, 4], dtype=dt, device=device) x_clone = x.clone() y = copy(x) y.fill_(1) # copy is a shallow copy, only copies the tensor view, # not the data self.assertEqual(x, y) # FIXME: move to data movement test suite @onlyNativeDeviceTypes def test_copy_math_view(self, device): for dst_dtype, src_dtype in [ (torch.float32, torch.float32), (torch.float64, torch.float32), (torch.int64, torch.int32), (torch.complex128, torch.complex64), ]: src = make_tensor((100,), dtype=src_dtype, device=device) dst = torch.empty(100, dtype=dst_dtype, device=device) dst.copy_(src) self.assertEqual(dst, src, exact_dtype=False) dst.copy_(src._neg_view()) self.assertEqual(dst, src.neg(), exact_dtype=False) dst._neg_view().copy_(torch._neg_view(src)) self.assertEqual(dst, src, exact_dtype=False) dst._neg_view().copy_(src) self.assertEqual(dst, src.neg(), exact_dtype=False) for dst_dtype, src_dtype in [ (torch.complex64, torch.complex64), (torch.complex128, torch.complex64), ]: src = make_tensor((100,), dtype=src_dtype, device=device) dst = torch.empty(100, dtype=dst_dtype, device=device) dst.conj().copy_(src) self.assertEqual(dst, src.conj_physical(), exact_dtype=False) dst.conj().copy_(src._neg_view()) self.assertEqual(dst, src.neg().conj_physical(), exact_dtype=False) # FIXME: move to data movement test suite @onlyNativeDeviceTypes @dtypes(torch.int64, torch.float32, torch.complex64) def test_copy_transpose_math_view(self, device, dtype): src = make_tensor((100, 100), dtype=dtype, device=device).transpose(0, 1) dst = torch.empty((100, 100), dtype=dtype, device=device) dst._neg_view().copy_(src) self.assertEqual(dst, -src) dst._neg_view().copy_(src._neg_view()) self.assertEqual(dst, src) dst.copy_(src._neg_view()) self.assertEqual(dst, -src) if dtype.is_complex: dst.conj().copy_(src) self.assertEqual(dst, src.conj_physical()) dst.conj().copy_(src.conj()) self.assertEqual(dst, src) dst.copy_(src.conj()) self.assertEqual(dst, src.conj_physical()) def test_clone_all_dtypes_and_devices(self, device): for dt in all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16): x = torch.tensor((1, 1), dtype=dt, device=device) y = x.clone() self.assertEqual(x, y) def test_clone_zero_stride_dim(self, device): # stride zero, size 1 axis, not contiguous x = torch.randn(10) y = x.as_strided([2, 1, 5], [1, 0, 2]) self.assertEqual(y, y.clone()) def test_clone_not_memory_dense(self): # github issue: https://github.com/pytorch/pytorch/issues/64176 x = torch.randn(10, 8).t()[::2, ::2] y = x.clone() # should retain permutation after densification self.assertTrue(y.stride() == (1, 4)) # FIXME: move to elementwise ternary test suite @dtypesIfCUDA(*set(get_all_math_dtypes('cuda'))) @dtypes(*set(get_all_math_dtypes('cpu'))) def test_addcmul(self, device, dtype): # Returns floating or integral scalar corresponding to dtype def _number(floating, integer, dtype): if dtype in [torch.half, torch.float, torch.double, torch.bfloat16]: return floating elif dtype in [torch.cfloat, torch.cdouble]: return floating * (1 + 1j) else: return integer def rand_tensor(size, dtype, device): if dtype.is_floating_point or dtype.is_complex: return torch.rand(size=size, dtype=dtype, device=device) if dtype == torch.uint8: return torch.randint(1, 5, size=size, dtype=dtype, device=device) else: return torch.randint(-5, 5, size=size, dtype=dtype, device=device) a = rand_tensor((2, 2), dtype=dtype, device=device) b = rand_tensor((2, 2), dtype=dtype, device=device) c = rand_tensor((2, 2), dtype=dtype, device=device) alpha = _number(0.5, 3, dtype) actual = torch.addcmul(a, b, c, value=alpha) expected = a + alpha * b * c self.assertEqual(expected, actual) with self.assertWarnsOnceRegex( UserWarning, "This overload of addcmul is deprecated"): self.assertEqual(actual, torch.addcmul(a, alpha, b, c)) if self.device_type == 'cuda' and dtype == torch.half: a = torch.tensor([60000.0], device=device, dtype=dtype) b = torch.tensor([60000.0], device=device, dtype=dtype) c = torch.tensor([2.0], device=device, dtype=dtype) out = torch.addcmul(a, b, c, value=-1) self.assertTrue(not (out.isnan() or out.isinf())) # FIXME: move to shape ops test suite def test_narrow_empty(self, device): x = torch.randn(2, 3, 4, device=device) for d in range(x.dim()): y = x.narrow(d, x.size(d), 0) sz = list(x.size()) sz[d] = 0 self.assertEqual(sz, y.size()) # FIXME: move to indexing test suite @parametrize("reduce", ['prod', 'amin', 'amax', 'mean']) @dtypes(*floating_types_and(torch.half, torch.bfloat16)) def test_index_reduce(self, device, dtype, reduce): size = (3, 4, 5) index_dtypes = [torch.int, torch.long] include_selfs = [True, False] reduction_init = {'prod': 1, 'mean': 0, 'amin': float('inf'), 'amax': -float('inf')} for dest_contig, src_contig, index_contig in product([True, False], repeat=3): for idx_dtype, include_self in product(index_dtypes, include_selfs): for dim in range(len(size)): num_src = np.random.randint(10) num_dest = size[dim] dest = torch.randn(size, dtype=dtype, device=device) if not dest_contig: dest = make_tensor(size, device=device, dtype=dtype, noncontiguous=True) src = torch.randn(*size[:dim], num_src, *size[dim + 1:], dtype=dtype, device=device) if not src_contig: # noncontiguous_like fails with RuntimeError: XLA tensors do not have storage src = torch.testing.make_non_contiguous(src) idx = torch.randint(num_dest, (num_src,), dtype=idx_dtype, device=device) if not index_contig: # noncontiguous_like fails with RuntimeError: XLA tensors do not have storage idx = torch.testing.make_non_contiguous(idx) expected = dest.clone() dest.index_reduce_(dim, idx, src, reduce, include_self=include_self) # fill rows in idx with reduction inits if include_self=False if (not include_self): expected.index_fill_(dim, idx.long(), reduction_init[reduce]) expected = expected.transpose(0, dim) src = src.transpose(0, dim) for i in range(num_src): if reduce == 'prod': expected[idx[i]] *= src[i] elif reduce == 'amin': torch.minimum(expected[idx[i]], src[i], out=expected[idx[i]]) elif reduce == 'amax': torch.maximum(expected[idx[i]], src[i], out=expected[idx[i]]) else: expected[idx[i]] += src[i] if reduce == 'mean': counts = torch.ones_like(expected) if include_self else torch.zeros_like(expected) counts.index_add_(0, idx, torch.ones_like(src)) counts.masked_fill_(counts == 0, 1) expected /= counts expected = expected.transpose(0, dim) self.assertEqual(dest, expected) # FIXME: move to test indexing @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) def test_index_copy(self, device, dtype): # We just test for num_copy <= num_dest, as otherwise there are repeated indices # and the behavior is undefined num_copy, num_dest = 3, 5 def make_arg(batch_sizes, n, dim, contig): size_arg = batch_sizes[:dim] + (n,) + batch_sizes[dim:] return make_tensor(size_arg, dtype=dtype, device=device, low=None, high=None, noncontiguous=not contig) def ref_index_copy(tgt, dim, idx, src): for i in range(idx.size(0)): idx_dest = dim * (slice(None),) + (idx[i],) idx_src = dim * (slice(None),) + (i,) tgt[idx_dest] = src[idx_src] # More thorough testing as in index_add for dest_contig, src_contig, index_contig in product([True, False], repeat=3): for other_sizes in ((), (4, 5)): for dim in range(len(other_sizes)): dest = make_arg(other_sizes, num_dest, dim, dest_contig) src = make_arg(other_sizes, num_copy, dim, src_contig) idx = torch.randperm(num_dest, dtype=torch.int64, device=device)[:num_copy] if not index_contig: idx = torch.repeat_interleave(idx, 2, dim=-1) idx = idx[..., ::2] dest2 = dest.clone() dest.index_copy_(dim, idx, src) ref_index_copy(dest2, dim, idx, src) self.assertEqual(dest, dest2) # FIXME: move to test indexing # onlyNativeDeviceTypes due to an XLA error: # https://github.com/pytorch/pytorch/issues/53256 @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) def test_index_copy_scalars(self, device, dtype): # Create the 8 possible combinations of scalar sizes for target / index / source scalars = ((make_tensor(size_t, dtype=dtype, device=device, low=None, high=None), make_tensor(size_i, dtype=torch.int64, device=device, low=0, high=1), make_tensor(size_s, dtype=dtype, device=device, low=None, high=None)) for size_t, size_i, size_s in product([(), (1,)], repeat=3)) for target, idx, source in scalars: target.index_copy_(0, idx, source) self.assertEqual(target.item(), source.item()) # FIXME: move to test indexing @onlyCPU def test_errors_index_copy(self, device): # We do not test the GPU as the CUDA_ASSERT would break the CUDA context idx_dim = 8 tgt_dim = 5 batch_dim = 3 # Too large of an index a = torch.randn(batch_dim, tgt_dim, device=device) idx = torch.full((idx_dim,), tgt_dim, device=device) c = torch.zeros(batch_dim, idx_dim, device=device) with self.assertRaises(IndexError): a.index_copy_(1, idx, c) # Too small (negative indices) idx = torch.full((idx_dim,), -1, device=device) with self.assertRaises(IndexError): a.index_copy_(1, idx, c) # Too small (very negative indices) - they should be unsupported even # when support for negative indices is implemented for index_copy_ idx = torch.full((idx_dim,), -tgt_dim - 1, device=device) with self.assertRaises(IndexError): a.index_copy_(1, idx, c) def _prepare_data_for_index_copy_and_add_deterministic( self, dim: int, device: torch.device ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: assert (dim >= 0 and dim < 3) a = [5, 4, 3] a[dim] = 2000 x = torch.zeros(a, device=device) b = a.copy() elems = a[dim] * 20 b[dim] = elems src = torch.rand(b, device=device) index = torch.randint(a[dim], (elems,), device=device) return (x, index, src) # FIXME: move to test indexing @onlyNativeDeviceTypes def test_index_copy_deterministic(self, device: torch.device) -> None: for dim in range(3): x, index, src = self._prepare_data_for_index_copy_and_add_deterministic(dim, device) with DeterministicGuard(True): y0 = torch.index_copy(x, dim, index, src) x0 = x.clone().detach() index_list = index.tolist() for i in range(len(index_list)): if dim == 0: x0[index_list[i], :, :] = src[i, :, :] elif dim == 1: x0[:, index_list[i], :] = src[:, i, :] elif dim == 2: x0[:, :, index_list[i]] = src[:, :, i] self.assertEqual(x0, y0, atol=0, rtol=0) # FIXME: move to test indexing @onlyNativeDeviceTypes def test_index_add_deterministic(self, device: torch.device) -> None: for dim in range(3): x, index, src = self._prepare_data_for_index_copy_and_add_deterministic(dim, device) alpha = random.random() + 1 # on CPU it should be deterministic regardless of the deterministic mode with DeterministicGuard(True): y0 = torch.index_add(x, dim, index, src, alpha=alpha) for _ in range(3): y = torch.index_add(x, dim, index, src, alpha=alpha) self.assertEqual(y, y0, atol=0, rtol=0) with DeterministicGuard(False): for _ in range(3): y_nd = torch.index_add(x, dim, index, src, alpha=alpha) self.assertEqual(y_nd, y0, atol=1e-3, rtol=1e-5) # FIXME: find a test suite for the put operator @onlyNativeDeviceTypes def test_index_put_non_accumulate_deterministic(self, device) -> None: with DeterministicGuard(True): for i in range(3): m = random.randint(10, 20) elems = random.randint(20000, 30000) values = torch.rand(elems, device=device) indices = torch.randint(m, (elems,), device=device) input = torch.rand(m, device=device) output = input.index_put((indices,), values, accumulate=False) input_list = input.tolist() indices_list = indices.tolist() values_list = values.tolist() for i, v in zip(indices_list, values_list): input_list[i] = v self.assertEqual(output, input_list) # FIXME: move to test indexing @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) @skipIfMps def test_index_fill(self, device, dtype): x = torch.tensor([[1, 2], [4, 5]], dtype=dtype, device=device) index = torch.tensor([0], device=device) x.index_fill_(1, index, 0) self.assertEqual(x, torch.tensor([[0, 2], [0, 5]], dtype=dtype, device=device)) if not x.is_complex() and not device == "meta": with self.assertRaisesRegex(RuntimeError, r"Scalar"): x.index_fill_(1, index, 1 + 1j) # Make sure that the result stays 0-dim while applied to # a 0-dim input x = torch.tensor(1, dtype=dtype, device=device) self.assertEqual(0, x.index_fill(0, index, -1).dim()) self.assertEqual(0, x.index_fill_(0, index, -1).dim()) # FIXME: move to test indexing # The test fails for zero-dimensional tensors on XLA @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) def test_index_select(self, device, dtype): num_src, num_out = 3, 5 def make_arg(batch_sizes, n, dim, contig): size_arg = batch_sizes[:dim] + (n,) + batch_sizes[dim:] return make_tensor(size_arg, dtype=dtype, device=device, low=None, high=None, noncontiguous=not contig) def ref_index_select(src, dim, idx): # bfloat16 is just used on GPU, so it's not supported on numpy if dtype == torch.bfloat16: src = src.float() out = torch.from_numpy(np.take(src.cpu().numpy(), idx.cpu().numpy(), axis=dim)) if dtype == torch.bfloat16: out = out.to(device=device, dtype=dtype) return out for src_contig, idx_contig in product([True, False], repeat=2): for other_sizes in ((), (4, 5)): for dim in range(len(other_sizes)): src = make_arg(other_sizes, num_src, dim, src_contig) idx = make_tensor( (num_out,), dtype=torch.int64, device=device, low=0, high=num_src, noncontiguous=not idx_contig ) out = torch.index_select(src, dim, idx) out2 = ref_index_select(src, dim, idx) self.assertEqual(out, out2) for idx_type in (torch.int32, torch.int64): other_sizes = (3, 2) dim = 1 src = make_arg(other_sizes, num_src, dim, True) idx = make_tensor((num_out,), dtype=idx_type, device=device, low=0, high=num_src, noncontiguous=False) out = torch.index_select(src, dim, idx) out2 = ref_index_select(src, dim, idx) self.assertEqual(out, out2) # Create the 4 possible combinations of scalar sizes for index / source scalars = ((make_tensor(size_s, dtype=dtype, device=device), torch.zeros(size_i, dtype=torch.int64, device=device)) for size_s, size_i in product([(), (1,)], repeat=2)) for source, idx in scalars: out = source.index_select(0, idx) self.assertEqual(out.item(), source.item()) # FIXME: find a test suite for the take operator @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) def test_take(self, device, dtype): idx_size = (4,) make_arg = partial(make_tensor, device=device, dtype=dtype) make_idx = partial(make_tensor, low=0, device=device, dtype=torch.int64) def ref_take(src, idx): if dtype == torch.bfloat16: src = src.half() src = src.cpu().numpy() idx = idx.cpu().numpy() out = torch.from_numpy(np.take(src, idx)).to(device=device, dtype=dtype) return out for src_contig, idx_contig, idx_reshape in product([True, False], repeat=3): for src_size in ((5,), (4, 5)): src = make_arg(src_size, noncontiguous=not src_contig) idx = make_idx(idx_size, high=src.numel(), noncontiguous=not idx_contig) if idx_reshape: idx = idx.reshape(2, 2) out = torch.take(src, idx) out2 = ref_take(src, idx) self.assertEqual(out, out2) # Create the 4 possible combinations of scalar sizes for source / index for size_s, size_i in product([(), (1,)], repeat=2): source = make_arg(size_s) idx = make_idx(size_i, high=1) out = source.take(idx) self.assertEqual(out.item(), source.item()) # FIXME: find a test suite for the put operator # The bool instance does not work on GPU. See # https://github.com/pytorch/pytorch/issues/54317 @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16)) def test_put(self, device, dtype): src_size = (4,) make_arg = partial(make_tensor, device=device, dtype=dtype) make_idx = partial(make_tensor, low=0, device=device, dtype=torch.int64) def ref_put(dst, idx, src, accumulate): new_dst = dst.clone(memory_format=torch.contiguous_format).view(-1) new_idx = idx.contiguous().view(-1) new_src = src.contiguous().view(-1) method = new_dst.index_add_ if accumulate else new_dst.index_copy_ return method(0, new_idx, new_src).view_as(dst) for dst_contig, src_contig, idx_contig, idx_reshape, accumulate in product([True, False], repeat=5): for dst_size in ((5,), (4, 5)): dst = make_arg(dst_size, noncontiguous=not dst_contig) src = make_arg(src_size, noncontiguous=not src_contig) # If accumulate=True, `put_` should be deterministic regardless of the inputs on CPU # On CUDA it may not be, but the test has enough tolerance to account for this if accumulate: idx = make_idx(src_size, high=dst.numel()) else: idx = torch.randperm(dst.numel(), dtype=torch.int64, device=device)[:src_size[0]] if not idx_contig: idx = torch.repeat_interleave(idx, 2, dim=-1)[..., ::2] if idx_reshape: idx = idx.reshape(2, 2) out = torch.put(dst, idx, src, accumulate) # out-place reference = ref_put(dst, idx, src, accumulate) self.assertEqual(out, reference) # in-place dst.put_(idx, src, accumulate) self.assertEqual(dst, reference) # Create the 8 possible combinations of scalar sizes for target / index / source scalars = ((make_arg(size_t), make_idx(size_i, high=1), make_arg(size_s)) for size_t, size_i, size_s in product([(), (1,)], repeat=3)) for (dest, idx, source), accumulate in product(scalars, [True, False]): dest_init = dest.clone() # out-place out = torch.put(dest, idx, source, accumulate=accumulate) # in-place dest1 = dest.clone() dest1.put_(idx, source, accumulate=accumulate) for d in [out, dest1]: if accumulate: self.assertEqual(d.item(), (dest_init + source).item()) else: self.assertEqual(d.item(), source.item()) # Empty case dest = make_arg((3, 2)) reference = dest.clone() idx = make_idx((0,), high=1) source = make_arg((0,)) for accumulate in [True, False]: out = torch.put(dest, idx, source, accumulate=accumulate) self.assertEqual(out, reference) dest.put_(idx, source, accumulate=accumulate) self.assertEqual(dest, reference) # FIXME: find a test suite for the put operator # The bool instance does not work on GPU. See # https://github.com/pytorch/pytorch/issues/54317 @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16)) def test_put_accumulate(self, device, dtype): # Test for parallel adds with accumulate == True low_precision = dtype == torch.half or dtype == torch.bfloat16 # Less numbers to avoid overflow with low_precision # Grainsize is 3000 for the for_loop to be parallized on CPU sizes = ((100,)) if low_precision else ((200,), (3002,)) # Bfloat16 has a particularly bad performance here # This operation is nondeterministic on GPU, so we are generous with the rtol rtol, atol = (1e-1, 1e-2) if low_precision else (1e-3, 1e-4) make_arg = partial(make_tensor, low=-2, high=3, device=device, dtype=dtype) # Dump everything into the 0-th position make_idx = partial(torch.zeros, device=device, dtype=torch.int64) args = ((make_idx(size), make_arg(size)) for size in sizes) for idx, source in args: orig = make_arg((1,)) out = orig.put(idx, source, accumulate=True) self.assertEqual(out, orig + source.sum(), rtol=rtol, atol=atol) # FIXME: find a test suite for the take operator @skipIfMps def test_take_empty(self, device): for input_shape in [(0,), (0, 1, 2, 0), (1, 2, 3)]: for indices_shape in [(0,), (0, 1, 2, 0)]: input = torch.empty(input_shape, device=device) indices = torch.empty(indices_shape, dtype=torch.int64, device=device) self.assertEqual(indices, torch.take(input, indices), exact_dtype=False) # FIXME: find a test suite for the put operator def test_put_empty(self, device): for dst_shape in [(0,), (0, 1, 2, 0), (1, 2, 3)]: for indices_shape in [(0,), (0, 1, 2, 0)]: for accumulate in [False, True]: dst = torch.randn(dst_shape, device=device) indices = torch.empty(indices_shape, dtype=torch.int64, device=device) src = torch.randn(indices_shape, device=device) self.assertEqual(dst, dst.put_(indices, src, accumulate=accumulate)) # FIXME: port to test_scatter_gather_ops.py def scatter_allow_reduce(self, device, dtype, reduceop): device_type = torch.device(device).type return device_type != 'cuda' or (reduceop == 'multiply' and dtype.is_floating_point) @dtypes(*floating_and_complex_types()) @dtypesIfCPU(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) @dtypesIfCUDA(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) def test_scatter_reduce_operations_to_large_input(self, device, dtype): index = torch.tensor([[1], [2]], device=device, dtype=torch.long) test_data = [ (torch.zeros(4, 4, device=device, dtype=dtype), torch.ones(2, 2, device=device, dtype=dtype), torch.tensor([[0, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0]], device=device, dtype=dtype), "add"), (torch.tensor([2], device=device, dtype=dtype).repeat(4, 4), torch.tensor([6], device=device, dtype=dtype).repeat(2, 2), torch.tensor([[2, 2, 2, 2], [12, 2, 2, 2], [12, 2, 2, 2], [2, 2, 2, 2]], device=device, dtype=dtype), "multiply"), ] for input, src, result, operation in test_data: if not self.scatter_allow_reduce(device, dtype, operation): continue input.scatter_(0, index, src, reduce=operation) self.assertEqual(input, result) @dtypes(*floating_and_complex_types()) @dtypesIfCPU(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) @dtypesIfCUDA(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) def test_scatter_reduce_scalar(self, device, dtype): index = torch.tensor([[1], [2]], device=device, dtype=torch.long) test_data = [ (torch.zeros(4, 4, device=device, dtype=dtype), 1, torch.tensor([[0, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0]], device=device, dtype=dtype), "add"), (torch.tensor([2], device=device, dtype=dtype).repeat(4, 4), 2, torch.tensor([[2, 2, 2, 2], [4, 2, 2, 2], [4, 2, 2, 2], [2, 2, 2, 2]], device=device, dtype=dtype), "multiply"), ] for input, src, result, operation in test_data: if not self.scatter_allow_reduce(device, dtype, operation): continue input.scatter_(0, index, src, reduce=operation) self.assertEqual(input, result) # FIXME: port to test_scatter_gather_ops.py # TODO: remove this after scatter_add_ is deprecated. def test_scatter_add_non_unique_index(self, device): height = 2 width = 65536 input = torch.ones(height, width, device=device) index = torch.zeros(height, width, dtype=torch.long, device=device) src = torch.ones(height, width, device=device) input.scatter_add_(0, index, src) self.assertEqual(input, torch.tensor([[3], [1]], device=device, dtype=torch.float32).repeat(1, width)) @dtypes(*floating_and_complex_types()) @dtypesIfCPU(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) @dtypesIfCUDA(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) def test_scatter_reduce_non_unique_index(self, device, dtype): height = 2 width = 2 index = torch.zeros(height, width, dtype=torch.long, device=device) test_data = [ (torch.ones(height, width, device=device, dtype=dtype), torch.ones(height, width, device=device, dtype=dtype), torch.tensor([[3], [1]], device=device, dtype=dtype).repeat(1, width), "add"), (torch.tensor([2], device=device, dtype=dtype).repeat(height, width), torch.tensor([2], device=device, dtype=dtype).repeat(height, width), torch.tensor([[8], [2]], device=device, dtype=dtype).repeat(1, width), "multiply"), ] for input, src, result, operation in test_data: if not self.scatter_allow_reduce(device, dtype, operation): continue input.scatter_(0, index, src, reduce=operation) self.assertEqual(input, result, msg=f"result: {result} input: {input} method: {str(operation)}") @onlyCUDA @dtypes(*integral_types(), *complex_types()) def test_scatter_reduce_multiply_unsupported_dtypes(self, device, dtype): height = 2 width = 2 index = torch.zeros(height, width, dtype=torch.long, device=device) input = torch.ones(height, width, device=device, dtype=dtype) src = torch.ones(height, width, device=device, dtype=dtype) with self.assertRaises(RuntimeError): input.scatter_(0, index, src, reduce="multiply") # FIXME: port to test_scatter_gather_ops.py def test_scatter_to_large_input(self, device): input = torch.zeros(4, 4, device=device) src = torch.ones(2, 2, device=device) index = torch.tensor([[1], [2]], device=device, dtype=torch.long) input.scatter_(0, index, src) self.assertEqual(input, torch.tensor([[0, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0]], device=device, dtype=torch.float32)) # FIXME: port to test_scatter_gather_ops.py def test_scatter_add_to_large_input(self, device): input = torch.zeros(4, 4, device=device) src = torch.ones(2, 2, device=device) index = torch.tensor([[1], [2]], device=device, dtype=torch.long) input.scatter_add_(0, index, src) self.assertEqual(input, torch.tensor([[0, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0]], device=device, dtype=torch.float32)) # FIXME: port to test_scatter_gather_ops.py def test_scatter_bool(self, device): x = torch.tensor([[True, True, True], [True, True, True]], device=device) res = torch.zeros(3, 3, dtype=torch.bool, device=device) res = res.scatter_(0, torch.tensor([[0, 1, 2], [0, 1, 2]], device=device), x) self.assertEqual(res, torch.tensor([[True, False, False], [False, True, False], [False, False, True]], device=device)) # FIXME: port to test_scatter_gather_ops.py def test_scatter_add_bool(self, device): x = torch.tensor([[True, True, True, True, True], [True, True, True, True, True]], device=device) res = torch.zeros(3, 5, dtype=torch.bool, device=device) res = res.scatter_add_(0, torch.tensor([[0, 1, 2, 0, 0], [2, 0, 0, 1, 2]], device=device), x) self.assertEqual(res, torch.tensor([[True, True, True, True, True], [False, True, False, True, False], [True, False, True, False, True]], device=device)) # FIXME: find a test suite for the masked scatter operator @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) def test_masked_scatter(self, device, dtype): dt = dtype with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") for maskType in [torch.uint8, torch.bool]: num_copy, num_dest = 3, 10 dest = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=dt, device=device) dest2 = dest.clone() dest_ones = dest.clone() dest_ones_expected = dest.clone() src = torch.tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=dt, device=device) src_ones = torch.tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=dt, device=device) mask = torch.tensor((0, 0, 0, 0, 1, 0, 1, 0, 1, 0), dtype=maskType, device=device) if dt == torch.bool: # torch.bool is a special case and is being tested # in a separate test return dest.masked_scatter_(mask, src) j = 0 for i in range(num_dest): if mask[i]: dest2[i] = src[j] dest_ones_expected[i] = src_ones[j] j += 1 self.assertEqual(dest, dest2, atol=0, rtol=0) dest_ones.masked_scatter_(mask, src_ones) self.assertEqual(dest_ones, dest_ones_expected, atol=0, rtol=0) # Bound checking in CUDA is done inside a kernel # in order to avoid synchronization, but this means # we can not clear the failures. So there is no way # to test it then recover. if self.device_type != 'cuda': # make src smaller. this should fail src = torch.zeros(num_copy - 1, dtype=dt, device=device) with self.assertRaises(RuntimeError): dest.masked_scatter_(mask, src) # empty tensor dest = torch.empty((5, 0, 5), dtype=dt, device=device) mask = torch.ones_like(dest, dtype=maskType, device=device) src = torch.empty((0,), dtype=dt, device=device) dest.masked_scatter_(mask, src) dest = torch.empty((5, 0, 5), dtype=dt, device=device) mask = torch.ones((5, 1, 5), dtype=maskType, device=device) src = torch.empty((0,), dtype=dt, device=device) dest.masked_scatter_(mask, src) if self.device_type != 'cuda': self.assertEqual(len(w), 5) else: self.assertEqual(len(w), 4) warn = 'masked_scatter_ received a mask with dtype torch.uint8,' for wi in w: self.assertEqual(str(wi.message)[0:55], str(warn)) # FIXME: find a test suite for the masked scatter operator @skipIfMps def test_masked_scatter_bool_tensor(self, device): src = torch.tensor([True, True, True], device=device) dst = torch.tensor([False, False, False], device=device) mask = torch.tensor([False, True, False], device=device) dst.masked_scatter_(mask, src) self.assertEqual(dst, torch.tensor([False, True, False], device=device)) mask = torch.tensor([True, False, True], device=device) dst = dst.masked_scatter(mask, src) self.assertEqual(dst, torch.tensor([True, True, True], device=device)) # FIXME: find a test suite for the masked scatter operator # test_scatter_gather_ops or test_masked_ops? @onlyCUDA @largeTensorTest('30GB') def test_masked_scatter_large_tensor(self, device): t_cpu = torch.empty(2**31 + 1, dtype=torch.bool).random_() t = t_cpu.to(device) result_cpu = t_cpu.masked_scatter(t_cpu, t_cpu) result = t.masked_scatter(t, t) self.assertEqual(result, result_cpu) # FIXME: find a test suite for the masked select operator @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) def test_masked_select(self, device, dtype): if device == 'cpu': warn = 'masked_select received a mask with dtype torch.uint8,' else: warn = 'indexing with dtype torch.uint8 is now deprecated, pl' for maskType in [torch.uint8, torch.bool]: num_src = 10 src = torch.tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=dtype, device=device) mask = torch.randint(2, (num_src,), device=device, dtype=maskType) with warnings.catch_warnings(record=True) as w: dst = src.masked_select(mask) if maskType is torch.uint8: self.assertEqual(len(w), 1) self.assertEqual(str(w[0].message)[0:53], str(warn)) dst2 = [] for i in range(num_src): if mask[i]: dst2 += [src[i]] self.assertEqual(dst, torch.tensor(dst2), atol=0, rtol=0) dst3 = torch.empty(0, device=device, dtype=dtype) torch.masked_select(src, mask, out=dst3) self.assertEqual(dst3, torch.tensor(dst2, dtype=dst3.dtype), atol=0, rtol=0) # Since half on CPU is not supported, need to skip the remaining test cases if dtype == torch.half and torch.device(device).type == 'cpu': return # Ensure that masks are expanded to match tensor properly a = torch.rand(100, 100, device=device).mul(100).to(dtype) mask_first_el_each_row = torch.zeros(100, device=device, dtype=torch.bool) mask_first_el_each_row[0] = True a_masked = a.masked_select(mask_first_el_each_row) self.assertEqual(a_masked, a[:, 0]) mask_first_row = torch.zeros(100, 1, device=device, dtype=torch.bool) mask_first_row[0][0] = True a_masked = a.masked_select(mask_first_row) self.assertEqual(a_masked, a[0, :]) # Ensure that tensor is expanded to match mask properly a = torch.rand(100, device=device).mul(100).to(dtype) mask_copy_3_times = torch.tensor([[True], [True], [False], [True]], device=device) a_masked = a.masked_select(mask_copy_3_times) self.assertEqual(a_masked, a.unsqueeze(0).expand(3, 100).flatten()) # FIXME: find a test suite for the masked select operator def test_masked_select_discontiguous(self, device): for size in (10, 200): vals = torch.rand(size, size, device=device) mask = torch.full((size, size), False, dtype=torch.bool, device=device) mask[:, ::2] = True vals_list = (vals, vals.t()) mask_list = (mask, mask.t()) out_dc = torch.empty(size * size, device=device)[::2] for v, m in product(vals_list, mask_list): if m.is_contiguous(): expected = v[:, ::2].clone().reshape((-1, )) else: expected = v[::2].clone().reshape((-1, )) out = torch.masked_select(v, m) self.assertEqual(out, expected, atol=0, rtol=0) torch.masked_select(v, m, out=out_dc) self.assertEqual(out_dc, expected, atol=0, rtol=0) # FIXME: find a test suite for the masked fill operator @dtypes(*product(all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16), (torch.uint8, torch.bool))) def test_masked_fill(self, device, dtypes): dtype = dtypes[0] mask_dtype = dtypes[1] with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") num_dest = 10 dst = torch.zeros(num_dest, dtype=dtype) mask = torch.randint(2, (num_dest,), dtype=mask_dtype) val = random.random() dst2 = dst.clone() dst.masked_fill_(mask, val) for i in range(num_dest): if mask[i]: dst2[i] = val self.assertEqual(dst, dst2, atol=0, rtol=0) # test non-contiguous case dst = ((torch.randn(num_dest, num_dest, num_dest) * 10).to(dtype)).permute((2, 0, 1)) dst2 = dst.contiguous() if dtype.is_complex: mask = dst.abs() > 0 else: mask = dst > 0 self.assertTrue(not dst.is_contiguous()) self.assertTrue(dst2.is_contiguous()) dst.masked_fill_(mask.to(mask_dtype), val) dst2.masked_fill_(mask.to(mask_dtype), val) self.assertEqual(dst, dst2, atol=0, rtol=0) if mask_dtype == torch.uint8: self.assertEqual(len(w), 3) warn = 'masked_fill_ received a mask with dtype torch.uint8,' for wi in w: self.assertEqual(str(wi.message)[0:52], str(warn)) else: self.assertEqual(len(w), 0) # FIXME: find a test suite for the masked fill operator def test_masked_fill_bool_tensor(self, device): dst = torch.tensor([True, False, True], device=device) mask = torch.tensor([False, True, False], device=device) dst.masked_fill_(mask, True) self.assertEqual(dst, torch.tensor([True, True, True], device=device)) dst = dst.masked_fill(mask, False) self.assertEqual(dst, torch.tensor([True, False, True], device=device)) def test_tensor_shape_empty(self, device): x = torch.randn((0, 1, 3, 0), device=device) # flatten self.assertEqual((0,), torch.flatten(x, 0, 3).shape) self.assertEqual((0, 0), torch.flatten(x, 0, 2).shape) self.assertEqual((0, 3, 0), torch.flatten(x, 1, 2).shape) # squeeze, unsqueeze self.assertEqual((0, 1, 1, 3, 0), torch.unsqueeze(x, 1).shape) self.assertEqual((0, 3, 0), torch.squeeze(x, 1).shape) self.assertEqual((0, 3, 0), torch.squeeze(x).shape) # transpose, t self.assertEqual((0, 0, 3, 1), torch.transpose(x, 1, 3).shape) y = torch.randn((5, 0), device=device) self.assertEqual((0, 5), y.t().shape) # select self.assertEqual((0, 1, 0), torch.select(x, 2, 2).shape) # repeat, permute self.assertEqual((9, 0, 5, 6, 0), x.repeat(9, 7, 5, 2, 3).shape) self.assertEqual((3, 0, 0, 1), x.permute(2, 3, 0, 1).shape) # diagonal, diagflat self.assertEqual((0,), torch.diagonal(torch.randn((5, 0), device=device)).shape) self.assertEqual((0,), torch.diagonal(torch.randn((0, 5), device=device)).shape) # off the end offsets are valid self.assertEqual((0,), torch.diagonal(torch.randn((5, 0), device=device), offset=1).shape) self.assertEqual((0,), torch.diagonal(torch.randn((0, 5), device=device), offset=1).shape) # check non-zero sized offsets off the end self.assertEqual((5, 6, 0), torch.diagonal(torch.randn((3, 4, 5, 6), device=device), offset=45252).shape) self.assertEqual((5, 6, 0), torch.diagonal(torch.randn((3, 4, 5, 6), device=device), offset=-45252).shape) self.assertEqual((0, 0), torch.diagflat(torch.tensor([], device=device)).shape) self.assertEqual(torch.zeros(1, 1), torch.diagflat(torch.tensor([], device=device), offset=1)) self.assertEqual((0, 0), torch.diagflat(torch.tensor([[]], device=device)).shape) self.assertEqual(torch.zeros(1, 1), torch.diagflat(torch.tensor([[]], device=device), offset=1)) # stack, split, chunk self.assertEqual((4, 0, 1, 3, 0), torch.stack((x, x, x, x)).shape) self.assertEqual([(0, 1, 3, 0)], [z.shape for z in torch.chunk(x, 1, dim=0)]) self.assertEqual([(0, 1, 3, 0), ] * 3, [z.shape for z in torch.chunk(x, 3, dim=0)]) self.assertEqual([(0, 1, 1, 0), ] * 3, [z.shape for z in torch.chunk(x, 3, dim=2)]) # NOTE: split_with_sizes behaves differently than NumPy in that it # takes sizes rather than offsets self.assertEqual([(0, 1, 0, 0), (0, 1, 1, 0), (0, 1, 2, 0)], [z.shape for z in torch.split(x, (0, 1, 2), dim=2)]) self.assertRaises(RuntimeError, lambda: torch.split(x, 0, dim=1)) # This is strange because the split size is larger than the dim size, but consistent with # how split handles that case generally (when no 0s are involved). self.assertEqual([(0, 1, 3, 0)], [z.shape for z in torch.split(x, 1, dim=0)]) self.assertEqual([(0, 1, 3, 0)], [z.shape for z in torch.split(x, 0, dim=0)]) # functions that operate over a dimension but don't reduce. def test_dim_function_empty(self, device): shape = (0, 1, 2, 0) x = torch.randn(shape, device=device) # size stride self.assertEqual(0, x.size(3)) self.assertEqual(2, x.size(2)) self.assertEqual(2, x.stride(0)) self.assertEqual(1, x.stride(2)) self.assertEqual(x, torch.nn.functional.glu(x, 0)) self.assertEqual((0, 1, 1, 0), torch.nn.functional.glu(x, 2).shape) # softmax, logsoftmax self.assertEqual(x, torch.nn.functional.softmax(x, 0)) self.assertEqual(x, torch.nn.functional.softmax(x, 2)) self.assertEqual(x, torch.nn.functional.softmax(x, 3)) self.assertEqual(x, torch.nn.functional.log_softmax(x, 0)) self.assertEqual(x, torch.nn.functional.log_softmax(x, 2)) self.assertEqual(x, torch.nn.functional.log_softmax(x, 3)) # cumsum, cumprod, cummax, cummin self.assertEqual(shape, torch.cumsum(x, 0).shape) self.assertEqual(shape, torch.cumsum(x, 2).shape) self.assertEqual(shape, torch.cumprod(x, 0).shape) self.assertEqual(shape, torch.cumprod(x, 2).shape) self.assertEqual(shape, torch.cummax(x, 0)[0].shape) self.assertEqual(shape, torch.cummax(x, 2)[0].shape) self.assertEqual(shape, torch.cummin(x, 0)[0].shape) self.assertEqual(shape, torch.cummin(x, 2)[0].shape) self.assertEqual(shape, torch.logcumsumexp(x, 0).shape) self.assertEqual(shape, torch.logcumsumexp(x, 2).shape) # flip self.assertEqual(x, x.flip(0)) self.assertEqual(x, x.flip(2)) # roll self.assertEqual(x, x.roll(0, 1).roll(0, -1)) self.assertEqual(x, x.roll(1, x.size(1))) self.assertEqual(x, x.roll(1)) self.assertEqual(x, x.roll((1, 1), (3, 1))) # unbind self.assertEqual((), x.unbind(0)) self.assertEqual((torch.empty((0, 1, 0), device=device), torch.empty((0, 1, 0), device=device)), x.unbind(2)) # cross y = torch.randn((0, 1, 3, 0), device=device) self.assertEqual(y.shape, torch.cross(y, y).shape) # renorm self.assertEqual(shape, torch.renorm(x, 1, 0, 5).shape) self.assertEqual(shape, torch.renorm(x, 1, 2, 5).shape) # sort self.assertEqual([shape, shape], [z.shape for z in torch.sort(x, dim=0)]) self.assertEqual([shape, shape], [z.shape for z in torch.sort(x, dim=2)]) # topk self.assertEqual([shape, shape], [z.shape for z in torch.topk(x, 0, dim=0)]) self.assertEqual([(0, 1, 1, 0), (0, 1, 1, 0)], [z.shape for z in torch.topk(x, 1, dim=2)]) y = torch.randn((2, 3, 4), device=device) self.assertEqual([(2, 3, 0), (2, 3, 0)], [z.shape for z in torch.topk(y, 0)]) # gather self.assertEqual(shape, torch.gather(x, 0, torch.empty(shape, dtype=torch.int64, device=device)).shape) self.assertEqual(shape, torch.gather(x, 2, torch.empty(shape, dtype=torch.int64, device=device)).shape) larger_shape = torch.empty((0, 1, 3, 0), dtype=torch.int64, device=device) self.assertEqual(larger_shape.shape, torch.gather(x, 2, larger_shape).shape) smaller_shape = torch.empty((0, 1, 0, 0), dtype=torch.int64, device=device) self.assertEqual(smaller_shape.shape, torch.gather(x, 2, smaller_shape).shape) y = torch.randn((2, 3, 4), device=device) self.assertEqual((0, 3, 4), torch.gather(y, 0, torch.empty((0, 3, 4), dtype=torch.int64, device=device)).shape) # scatter, scatter_add for dim in [0, 2]: y = torch.randn(shape, device=device) y_src = torch.randn(shape, device=device) ind = torch.empty(shape, dtype=torch.int64, device=device) self.assertEqual(shape, y.scatter_(dim, ind, y_src).shape) self.assertEqual(shape, y.scatter_add_(dim, ind, y_src).shape) z = torch.randn((2, 3, 4), device=device) z_src = torch.randn((2, 3, 4), device=device) self.assertEqual(z, z.scatter_(2, torch.empty((2, 3, 0), dtype=torch.int64, device=device), z_src)) self.assertEqual(z, z.scatter_add_(2, torch.empty((2, 3, 0), dtype=torch.int64, device=device), z_src)) # index_fill, index_copy, index_add c = x.clone() c_clone = c.clone() ind_empty = torch.tensor([], dtype=torch.int64, device=device) ind_01 = torch.tensor([0, 1], dtype=torch.int64, device=device) self.assertEqual(c_clone, c.index_fill_(0, ind_empty, -1)) self.assertEqual(c_clone, c.index_fill_(2, ind_empty, -1)) self.assertEqual(c_clone, c.index_fill_(2, ind_01, -1)) self.assertEqual(c_clone, c.index_copy_(0, ind_empty, torch.empty((0, 1, 2, 0), device=device))) self.assertEqual(c_clone, c.index_copy_(2, ind_empty, torch.empty((0, 1, 0, 0), device=device))) self.assertEqual(c_clone, c.index_copy_(2, ind_01, torch.empty((0, 1, 2, 0), device=device))) self.assertEqual(c_clone, c.index_add_(0, ind_empty, torch.empty((0, 1, 2, 0), device=device))) self.assertEqual(c_clone, c.index_add_(2, ind_empty, torch.empty((0, 1, 0, 0), device=device))) self.assertEqual(c_clone, c.index_add_(2, ind_01, torch.empty((0, 1, 2, 0), device=device))) c = torch.randn((0, 1, 2), device=device) c_clone = c.clone() self.assertEqual(c_clone, c.index_fill_(0, ind_empty, -1)) self.assertEqual(c_clone, c.index_copy_(0, ind_empty, torch.empty((0, 1, 2), device=device))) self.assertEqual(c_clone, c.index_add_(0, ind_empty, torch.empty((0, 1, 2), device=device))) self.assertEqual(c_clone, c.index_fill_(0, ind_empty, -1)) self.assertEqual(c_clone, c.index_copy_(0, ind_empty, torch.empty((0, 1, 2), device=device))) self.assertEqual(c_clone, c.index_add_(0, ind_empty, torch.empty((0, 1, 2), device=device))) # index fill/copy/add non-empty z = torch.randn((2, 3, 4), device=device) self.assertEqual(z, z.index_fill_(0, ind_empty, -1)) z = torch.randn((2, 3, 4), device=device) self.assertEqual(z, z.index_copy_(0, ind_empty, torch.empty((0, 3, 4), device=device))) z = torch.randn((2, 3, 4), device=device) self.assertEqual(z, z.index_add_(0, ind_empty, torch.empty((0, 3, 4), device=device))) # index_select self.assertEqual(x, x.index_select(0, ind_empty)) self.assertEqual((0, 1, 0, 0), x.index_select(2, ind_empty).shape) self.assertEqual(x, x.index_select(2, ind_01)) z = torch.randn((2, 3, 4), device=device) # non-empty self.assertEqual((0, 3, 4), z.index_select(0, ind_empty).shape) c = torch.randn((0, 1, 2), device=device) self.assertEqual(c, c.index_select(0, ind_empty)) c = torch.randn((0, 1, 2), device=device) self.assertEqual(c, c.index_select(0, ind_empty)) w = torch.randn((0, 3), device=device) self.assertEqual((0, 2), w.index_select(1, ind_01).shape) w = torch.randn((3, 0), device=device) self.assertEqual((2, 0), w.index_select(0, ind_01).shape) ind_01_int32 = torch.tensor([0, 1], dtype=torch.int32, device=device) self.assertEqual((2, 0), w.index_select(0, ind_01_int32).shape) if device == 'cpu': w = torch.randn((0, 3), device=device) with self.assertRaisesRegex(RuntimeError, "self indexing axis dim should be positive"): torch.index_select(w, 0, ind_01) ind_05 = torch.tensor([0, 5], dtype=torch.int64, device=device) with self.assertRaisesRegex(RuntimeError, "INDICES element is out of DATA bounds"): torch.index_select(w, 1, ind_05) # FIXME: find a test suite for the pdist operator def _brute_pdist(self, inp, p=2): """Computes the same as torch.pdist using primitives""" n = inp.shape[-2] k = n * (n - 1) // 2 if k == 0: # torch complains about empty indices return torch.empty(inp.shape[:-2] + (0,), dtype=inp.dtype, device=inp.device) square = torch.norm(inp[..., None, :] - inp[..., None, :, :], p=p, dim=-1) unroll = square.view(square.shape[:-2] + (n * n,)) inds = torch.ones(k, dtype=torch.int) inds[torch.arange(n - 1, 1, -1, dtype=torch.int).cumsum(0)] += torch.arange(2, n, dtype=torch.int) return unroll[..., inds.cumsum(0)] # FIXME: find a test suite for the pdist operator def _pdist_single(self, shape, device, p, dtype, trans, grad_check=False): x = torch.randn(shape, dtype=dtype, device=device) if trans: x.transpose_(-2, -1) if grad_check: x.requires_grad_() y = x.detach().clone().requires_grad_() else: y = x actual = torch.pdist(x, p=p) expected = self._brute_pdist(y, p=p) self.assertEqual(expected.shape, actual.shape) self.assertEqual(expected, actual) if grad_check and expected.size() != torch.Size([0]): g0 = torch.rand_like(actual) actual.backward(g0) expected.backward(g0) self.assertEqual(x.grad, y.grad) # FIXME: find a test suite for the pdist operator @slowTest def test_pdist_norm_forward(self, device): for shape in [(4, 5), (3, 2), (2, 1), (1500, 1)]: for p in [0, 1, 2, 3, 1.5, 2.5, float('inf')]: for trans in [False, True]: for dtype in [torch.float32, torch.float64]: self._pdist_single(shape, device, p, dtype, trans, grad_check=False) # do a simplified comparison with big inputs, see: # https://github.com/pytorch/pytorch/issues/15511 for dtype in [torch.float32, torch.float64]: self._pdist_single((1000, 2), device, 2, dtype, trans=False, grad_check=False) # FIXME: find a test suite for the pdist operator @slowTest def test_pdist_norm_backward(self, device): for shape in [(4, 5), (3, 2), (2, 1), (1500, 1)]: for p in [0, 1, 2, 3, 1.5, 2.5, float('inf')]: for trans in [False, True]: self._pdist_single(shape, device, p, torch.float64, trans, grad_check=True) # FIXME: find a test suite for the pdist operator @unittest.skipIf(IS_FBCODE and IS_REMOTE_GPU, "sandcastle OOM with current tpx gpu/re configuration") @skipIfRocm @onlyCUDA @largeTensorTest('10GB', device='cpu') @largeTensorTest('5GB', device='cuda') def test_pdist_norm_large(self, device): # use dim0>=46342 for forward, see: # https://github.com/pytorch/pytorch/issues/30583 # Compare output using GPU with the CPU implementation, as brute_pdist uses too much memory x = torch.randn(50000, 1, dtype=torch.float32) # 50k * 4 bytes = 200 KB # Will require 1249975000 float32s expected_cpu = torch.pdist(x, p=2) # ~1250M * 4 bytes = 5 GB on CPU actual_gpu = torch.pdist(x.to(device), p=2) # 5 GB on GPU self.assertEqual(expected_cpu, actual_gpu.cpu()) # Another 5 GB on CPU # FIXME: move to elementwise ternary test suite @onlyNativeDeviceTypes @dtypesIfCUDA(*set(get_all_math_dtypes('cuda'))) @dtypes(*set(get_all_math_dtypes('cpu'))) def test_addcdiv(self, device, dtype): # Returns floating or integral scalar corresponding to dtype def _number(floating, integer, dtype): if dtype in [torch.half, torch.float, torch.double, torch.bfloat16]: return floating elif dtype in [torch.cfloat, torch.cdouble]: return floating * (1 + 1j) else: return integer def non_zero_rand(size, dtype, device): if dtype.is_floating_point or dtype.is_complex: a = torch.rand(size=size, dtype=dtype, device=device) elif dtype == torch.uint8: a = torch.randint(1, 5, size=size, dtype=dtype, device=device) else: a = torch.randint(-5, 5, size=size, dtype=dtype, device=device) return a + (a == 0).to(dtype) def _test_addcdiv(): a = non_zero_rand((2, 2), dtype=dtype, device=device) b = non_zero_rand((2, 2), dtype=dtype, device=device) c = non_zero_rand((2, 2), dtype=dtype, device=device) alpha = _number(0.5, 3, dtype) expected = a + (alpha * b) / c actual = torch.addcdiv(a, b, c, value=alpha) self.assertEqual(expected, actual) with self.assertWarnsOnceRegex( UserWarning, "This overload of addcdiv is deprecated"): self.assertEqual(actual, torch.addcdiv(a, alpha, b, c)) if not (dtype.is_floating_point or dtype.is_complex): # Integer division with addcdiv is prohibited with self.assertRaises(RuntimeError): _test_addcdiv() else: _test_addcdiv() if self.device_type == 'cuda' and dtype == torch.half: a = torch.tensor([60000.0], device=device, dtype=dtype) b = torch.tensor([60000.0], device=device, dtype=dtype) c = torch.tensor([1.0], device=device, dtype=dtype) out = torch.addcmul(a, b, c, value=-2) self.assertTrue(not (out.isnan() or out.isinf())) def test_nullary_op_mem_overlap(self, device): ops = ( ("random_", ()), ("uniform_", ()), ("cauchy_", ()), ("log_normal_", ()), ("exponential_", ()), ("geometric_", (0.5,)), ("normal_", ()), ) x = torch.rand((1, 3)).expand((3, 3)) for op, args in ops: with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): getattr(x, op)(*args) # FIXME: move to an elementwise ternary test suite and make this an OpInfo test @dtypes(torch.double) def test_ternary_op_mem_overlap(self, device, dtype): ops = [ ("addcmul", True, True, 'cpu'), ("addcmul", True, True, 'cuda'), ("addcdiv", True, True, 'cpu'), ("addcdiv", True, True, 'cuda'), ("lerp", True, True, 'cpu'), ("lerp", True, True, 'cuda') ] for (fn, has_input_output_mem_overlap_check, has_internal_mem_overlap_check, dev) in ops: if dev != device: continue out_op = getattr(torch, fn) inplace_op = getattr(torch.Tensor, fn + '_') self.check_internal_mem_overlap( inplace_op, 3, dtype, device, expected_failure=not has_internal_mem_overlap_check) self.ternary_check_input_output_mem_overlap(out_op, dev, expected_failure=not has_input_output_mem_overlap_check) @expectedFailureMeta # RuntimeError not raised @dtypes(torch.double) @onlyNativeDeviceTypes def test_copy_mem_overlap(self, device, dtype): self.check_internal_mem_overlap( torch.Tensor.copy_, num_inputs=2, dtype=dtype, device=device) sz = 9 doubles = torch.randn(2 * sz, dtype=dtype, device=device) self.unary_check_input_output_mem_overlap( doubles, sz, lambda input, out: out.copy_(input)) # FIXME: convert to ErrorInputs @onlyNativeDeviceTypes def test_index_add_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) y = torch.rand((6,), device=device) ind = torch.tensor([2, 1, 0], device=device) value = torch.rand((3,), device=device) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.index_add_(0, ind, value) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): y.index_add_(0, ind, y[:3]) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_add_(0, ind, ind.clone()) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_add_(0, ind.clone(), ind) # FIXME: convert to ErrorInputs @onlyNativeDeviceTypes def test_index_copy_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) y = torch.rand((6,), device=device) ind = torch.tensor([2, 1, 0], device=device) value = torch.rand((3,), device=device) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.index_copy_(0, ind, value) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): y.index_copy_(0, ind, y[:3]) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_copy_(0, ind, ind.clone()) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_copy_(0, ind.clone(), ind) # FIXME: convert to ErrorInputs @expectedFailureMeta # Warning not triggered @onlyNativeDeviceTypes def test_index_fill_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) y = torch.rand((6,), device=device) ind = torch.tensor([2, 1, 0], device=device) value = torch.rand((3,), device=device) with self.assertWarnsRegex(UserWarning, "index_fill_ on expanded tensors"): x.index_fill_(0, ind, 1.0) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_fill_(0, ind, 0) # FIXME: convert to ErrorInputs @expectedFailureMeta # RuntimeError not raised @onlyNativeDeviceTypes def test_shift_mem_overlap(self, device): x = torch.rand(3, device=device) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x[:-1] <<= x[1:] with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x[:-1] >>= x[1:] # FIXME: convert to ErrorInputs @expectedFailureMeta # RuntimeError not raised @onlyNativeDeviceTypes def test_bernoulli_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.bernoulli_() with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.bernoulli_(p=0.1) p = torch.rand(6, device=device) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.bernoulli_(p=p) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): torch.bernoulli(torch.rand_like(x), out=x) # FIXME: convert to ErrorInputs @expectedFailureMeta # RuntimeError not raised @onlyNativeDeviceTypes def test_put_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) y = torch.rand((6,), device=device) ind = torch.tensor([2, 1, 0], device=device) value = torch.rand((3,), device=device) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.put_(ind, value) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): y.put_(ind[0], y[0]) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.put_(ind, ind) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): y.put_(ind, y[:3]) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.put_(ind, ind.clone()) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.put_(ind.clone(), ind) # FIXME: convert to ErrorInputs @expectedFailureMeta # UserWarning not triggered @onlyNativeDeviceTypes def test_index_put_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) y = torch.rand((6,), device=device) ind = torch.tensor([2, 1, 0], device=device) value = torch.rand((3,), device=device) with self.assertWarnsRegex(UserWarning, 'expanded tensors'): x.index_put_((ind,), value) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): y.index_put_((ind,), y[0]) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_put_((ind,), ind) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): y.index_put_((ind,), y[:3]) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_put_((ind,), ind.clone()) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_put_((ind.clone(),), ind) # FIXME: convert to ErrorInputs @expectedFailureMeta # UserWarning not triggered @onlyNativeDeviceTypes def test_masked_fill_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) mask = torch.tensor([True, False, True, True, False, False], device=device) with self.assertWarnsRegex(UserWarning, 'expanded tensors'): x.masked_fill_(mask, 0.) fill_val = torch.tensor(0., device=device) with self.assertWarnsRegex(UserWarning, 'expanded tensors'): x.masked_fill_(mask, fill_val) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): mask[1:].masked_fill_(mask[:-1], False) # FIXME: convert to ErrorInputs @expectedFailureMeta # RuntimeError not raised @onlyNativeDeviceTypes def test_masked_scatter_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) src = torch.rand((3,), device=device) mask = torch.tensor([True, False, True, True, False, False], device=device) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.masked_scatter_(mask, src) # FIXME: convert to ErrorInputs @onlyNativeDeviceTypes def test_scatter_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) src = torch.rand((3,), device=device) ind = torch.tensor([2, 1, 0], device=device, dtype=torch.int64) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.scatter_(0, ind, src) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): src.scatter_(0, ind, src) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.scatter_(0, ind, ind.clone()) # FIXME: move to test distributions @onlyCUDA def test_multinomial_device_constrain(self, device): x = torch.empty(0, device="cpu") y = torch.empty(0, device=device) self.assertRaisesRegex( RuntimeError, "Expected all tensors to be on the same device", lambda: torch.multinomial(x, 2, out=y)) # FIXME: move to test distributions @deviceCountAtLeast(2) @onlyCUDA def test_multinomial_gpu_device_constrain(self, devices): x = torch.empty(0, device=devices[0]) y = torch.empty(0, device=devices[1]) self.assertRaisesRegex( RuntimeError, "Expected all tensors to be on the same device", lambda: torch.multinomial(x, 2, out=y)) # FIXME: convert this to an automated OpInfo test @deviceCountAtLeast(2) @onlyCUDA def test_device_guard(self, devices): # verify that all operators with `device_guard: False` behave properly with multiple devices. # TODO: if we had operator introspection we could figure out this set of operators automatically... x = torch.randn((1, 2, 3), device=devices[1]) y = torch.zeros((1, 3, 2), device=devices[1]) scalar = torch.tensor(5, device=devices[1]) # property ops torch.cudnn_is_acceptable(x) x.is_distributed() x.is_floating_point() x.is_complex() x.is_same_size(y) x.is_signed() x.size(0) x.stride(0) x.numel() x.is_set_to(y) x.data_ptr() scalar.is_nonzero() # sparse property ops y[0][1] = 5 y_sparse = y.to_sparse() y_sparse.sparse_dim() y_sparse._dimI() y_sparse.dense_dim() y_sparse._dimV() y_sparse._nnz() y_sparse.is_coalesced() y_sparse._indices() y_sparse._values() y_sparse.indices() y_sparse.values() # in-place ops def inplace(): return torch.randn((1, 2, 3), device=devices[1]) inplace().as_strided_(y.size(), y.stride()) inplace().resize_(y.size()) inplace().squeeze_() inplace().squeeze_(0) inplace().unsqueeze_(2) inplace().transpose_(1, 2) inplace().squeeze_().t_() inplace().set_(x.storage()) inplace().set_(x.storage(), x.storage_offset(), x.size(), x.stride()) inplace().set_(x) inplace().set_() y_sparse._coalesced_(True) # shape modification x.as_strided(y.size(), y.stride()) x.expand((5, 2, 3)) x.expand_as(x) x.sum_to_size((1,)) torch.broadcast_tensors(x , x) x.reshape((1, 3, 2)) x.reshape_as(y) x.squeeze() x.squeeze(0) x.squeeze().t() x.transpose(1, 2) x.unsqueeze(2) x.view((1, 3, 2)) x.view_as(y) # chunk, split, etc. x.chunk(2, dim=1) x.split(1, dim=2) x.split_with_sizes([1, 2], dim=2) x.unfold(dimension=2, size=1, step=1) x.narrow(1, 1, 1) x.select(1, 1) torch.isnan(x) torch.empty((1, 3, 2), out=y) torch.empty_like(x) torch.empty_like(x, dtype=torch.int64) # to x.to(x) x.to(y) x.to(x, copy=True) def test_is_signed(self, device): self.assertEqual(torch.IntTensor(5).to(device).is_signed(), True) self.assertEqual(torch.ByteTensor(5).to(device).is_signed(), False) self.assertEqual(torch.CharTensor(5).to(device).is_signed(), True) self.assertEqual(torch.FloatTensor(5).to(device).is_signed(), True) self.assertEqual(torch.HalfTensor(10).to(device).is_signed(), True) # Note - reports a leak of 512 bytes on CUDA device 1 @deviceCountAtLeast(2) @skipCUDAMemoryLeakCheckIf(True) @onlyCUDA def test_tensor_set_errors_multigpu(self, devices): f_cuda0 = torch.randn((2, 3), dtype=torch.float32, device=devices[0]) f_cuda1 = torch.randn((2, 3), dtype=torch.float32, device=devices[1]) self.assertRaises(RuntimeError, lambda: f_cuda0.set_(f_cuda1.storage())) self.assertRaises(RuntimeError, lambda: f_cuda0.set_(f_cuda1.storage(), 0, f_cuda1.size(), f_cuda1.stride())) self.assertRaises(RuntimeError, lambda: f_cuda0.set_(f_cuda1)) # FIXME: move to test_serialization @onlyCUDA @deviceCountAtLeast(1) # Note: Tests works with one but prefers more devices def test_serialization(self, devices): def _test_serialization(filecontext_lambda): t0 = torch.cuda.FloatTensor(5).fill_(1) with torch.cuda.device(devices[-1]): tn = torch.cuda.FloatTensor(3).fill_(2) torch.cuda.set_device(devices[0]) b = (t0, tn) with filecontext_lambda() as f: torch.save(b, f) f.seek(0) c = torch.load(f) self.assertEqual(b, c, atol=0, rtol=0) u0, un = c self.assertEqual(str(u0.device), devices[0]) self.assertEqual(str(un.device), devices[-1]) _test_serialization(tempfile.NamedTemporaryFile) _test_serialization(BytesIOContext) # FIXME: move memory format tests to their own test class/suite def test_memory_format_preserved_after_permute(self, device): x = torch.randn(4, 3, 8, 8, device=device) nhwc = x.contiguous(memory_format=torch.channels_last) y = nhwc.permute(0, 1, 3, 2).permute(0, 1, 3, 2) self.assertTrue(y.is_contiguous(memory_format=torch.channels_last)) x = torch.randn(4, 3, 8, 8, 8, device=device) ndhwc = x.contiguous(memory_format=torch.channels_last_3d) y = ndhwc.permute(0, 1, 4, 3, 2).permute(0, 1, 4, 3, 2) self.assertTrue(y.is_contiguous(memory_format=torch.channels_last_3d)) def test_memory_format_propagation_rules(self, device): contiguous = torch.rand(10, 3, 5, 5, device=device) cl = torch.rand(10, 3, 5, 5, device=device).contiguous(memory_format=torch.channels_last) ambiguous = torch.rand(10, 3, 1, 1, device=device).contiguous(memory_format=torch.channels_last) self.assertTrue(ambiguous.is_contiguous(memory_format=torch.channels_last)) self.assertTrue(ambiguous.is_contiguous(memory_format=torch.contiguous_format)) bias = torch.rand(1, 1, 1, 1, device=device).contiguous(memory_format=torch.channels_last) def _test_propagation_rules(self, contiguous, cl, ambiguous, bias): options = ((ambiguous, contiguous, torch.contiguous_format), (ambiguous, cl, torch.channels_last), (contiguous, ambiguous, torch.contiguous_format), (contiguous, cl, torch.contiguous_format), (cl, ambiguous, torch.channels_last), (cl, contiguous, torch.channels_last), (bias, cl, torch.channels_last), (cl, bias, torch.channels_last),) for a, b, mf in options: result = a + b self.assertTrue(result.is_contiguous(memory_format=mf)) _test_propagation_rules(self, contiguous, cl, ambiguous, bias) cl = cl.to(memory_format=torch.channels_last) ambiguous = ambiguous.to(memory_format=torch.channels_last) bias = bias.to(memory_format=torch.channels_last) _test_propagation_rules(self, contiguous, cl, ambiguous, bias) # test cases when strides matter in ambiguous tensors for mf in (torch.channels_last, torch.contiguous_format): ambiguous = torch.rand(10, 3, 1, 1, device=device).to(memory_format=mf) bias = torch.rand(3, 1, 1, device=device) result = ambiguous + bias self.assertEqual(ambiguous.stride(), result.stride()) result = bias + ambiguous self.assertEqual(ambiguous.stride(), result.stride()) result = ambiguous * 5 self.assertEqual(ambiguous.stride(), result.stride()) @skipIfMps def test_memory_format_empty_like(self, device): def test_helper(x, memory_format): xc = x.contiguous(memory_format=memory_format) like = torch.empty_like(xc, memory_format=torch.preserve_format) self.assertFalse(like.is_contiguous()) self.assertTrue(like.is_contiguous(memory_format=memory_format)) like_x = torch.empty_like(x, memory_format=torch.preserve_format) self.assertTrue(like_x.is_contiguous()) self.assertFalse(like_x.is_contiguous(memory_format=memory_format)) like = torch.empty_like(x, memory_format=memory_format) self.assertFalse(like.is_contiguous()) self.assertTrue(like.is_contiguous(memory_format=memory_format)) like = torch.empty_like(xc, memory_format=torch.contiguous_format) self.assertTrue(like.is_contiguous()) self.assertFalse(like.is_contiguous(memory_format=memory_format)) like = torch.empty_like(xc) self.assertFalse(like.is_contiguous()) self.assertTrue(like.is_contiguous(memory_format=memory_format)) sparse = x.to_sparse() with self.assertRaises(RuntimeError): z = torch.empty_like(sparse, memory_format=torch.preserve_format) test_helper(torch.randn(4, 3, 8, 8, device=device), torch.channels_last) test_helper(torch.randn(4, 3, 8, 8, 8, device=device), torch.channels_last_3d) def test_memory_format_consistency(self, device): x = torch.randn(10, 3, 1, 1, device=device) x_rep = x.as_strided(x.size(), x.stride()) self.assertEqual(x.size(), x_rep.size()) self.assertEqual(x.stride(), x_rep.stride()) self.assertEqual(x.is_contiguous(), x_rep.is_contiguous()) self.assertEqual(x.is_contiguous(memory_format=torch.channels_last), x_rep.is_contiguous(memory_format=torch.channels_last)) self.assertEqual( x.is_contiguous(memory_format=torch.channels_last_3d), x_rep.is_contiguous(memory_format=torch.channels_last_3d)) # FIXME: make this a elementwise unary and elementwise binary OpInfo test def test_memory_format_operators(self, device): def _chunk_op(x, y): x1, x2 = x.chunk(2, dim=1) return x1 + x2 def _unsqueeze_op_add(x, y): return x[0].unsqueeze(0) + 3 def _unsqueeze_op_clone(x, y): return x[0].unsqueeze(0).clone() def _test_helper(x, y, bias, memory_format): return_contig_fns = [ lambda x, y: y + x, lambda x, y: y * x, lambda x, y: y.addcdiv(x, y, value=2), lambda x, y: y.addcmul(x, y, value=2), ] bias_fns = [ lambda x, b: x + b, lambda x, b: b + x, ] fns = [ lambda x, y: x.clone(), lambda x, y: x + 3, lambda x, y: 3 * x, lambda x, y: x + y, lambda x, y: x * y, lambda x, y: abs(x), lambda x, y: x.abs(), lambda x, y: x.abs_(), lambda x, y: x.acos(), lambda x, y: x.acos_(), lambda x, y: x.add(y, alpha=3), lambda x, y: x.add_(y, alpha=3), lambda x, y: x.addcdiv(y, y, value=2), lambda x, y: x.addcdiv_(y, y, value=2), lambda x, y: x.addcmul(y, y, value=2), lambda x, y: x.addcmul_(y, y, value=2), lambda x, y: x.acosh(), lambda x, y: x.acosh_(), lambda x, y: x.asinh(), lambda x, y: x.asinh_(), lambda x, y: x.atanh(), lambda x, y: x.atanh_(), lambda x, y: x.asin(), lambda x, y: x.asin_(), lambda x, y: x.atan(), lambda x, y: x.atan2(y), lambda x, y: x.atan2_(y), lambda x, y: x.ceil(), lambda x, y: x.ceil_(), lambda x, y: x.clamp(-1, 1), lambda x, y: x.cos(), lambda x, y: x.cosh(), lambda x, y: x.div(0.5), lambda x, y: x.div_(0.5), lambda x, y: x.div(y), lambda x, y: x.div_(y), lambda x, y: x.digamma(), lambda x, y: x.digamma_(), lambda x, y: x.erf(), lambda x, y: x.erfc(), lambda x, y: x.erfinv(), lambda x, y: x.erfinv_(), lambda x, y: x.exp(), lambda x, y: x.expm1(), lambda x, y: x.expm1_(), lambda x, y: x.floor(), lambda x, y: x.floor_(), lambda x, y: x.fmod(2), lambda x, y: x.frac(), lambda x, y: x.hypot(y), lambda x, y: x.hypot_(y), lambda x, y: x.i0(), lambda x, y: x.i0_(), lambda x, y: x.lerp(y, 0.5), lambda x, y: x.log(), lambda x, y: x.log_(), lambda x, y: x.log10(), lambda x, y: x.log10_(), lambda x, y: x.log1p(), lambda x, y: x.log1p_(), lambda x, y: x.log2(), lambda x, y: x.log2_(), lambda x, y: x.mul(3), lambda x, y: x.mul_(3), lambda x, y: x.neg(), lambda x, y: x.neg_(), lambda x, y: x.pow(3), lambda x, y: x.pow_(3), lambda x, y: x.pow(0.0), lambda x, y: x.pow(1.0), lambda x, y: x.reciprocal(), lambda x, y: x.remainder(2), lambda x, y: x.round(), lambda x, y: x.round_(), lambda x, y: x.rsqrt(), lambda x, y: x.rsqrt_(), lambda x, y: x.sigmoid(), lambda x, y: x.sigmoid_(), lambda x, y: x.logit(), lambda x, y: x.logit_(), lambda x, y: x.logit(1e-6), lambda x, y: x.logit_(1e-6), lambda x, y: x.sign(), lambda x, y: x.sign_(), lambda x, y: x.sgn(), lambda x, y: x.sgn_(), lambda x, y: x.sin(), lambda x, y: x.sin_(), lambda x, y: x.sinh(), lambda x, y: x.sinh_(), lambda x, y: x.sqrt(), lambda x, y: x.sqrt_(), lambda x, y: x.tan(), lambda x, y: x.tanh(), lambda x, y: x.trunc(), lambda x, y: x.trunc_(), _chunk_op, _unsqueeze_op_add, _unsqueeze_op_clone, ] for fn in fns: x_c = x.contiguous() y_c = y.contiguous() result_c = fn(x_c, y_c) result = fn(x, y) self.assertEqual(result, result_c) self.assertTrue( result.is_contiguous(memory_format=memory_format), "result of the '{}' is not in '{}' format".format(inspect.getsource(fn).strip(), memory_format)) for fn in bias_fns: x_c = x.contiguous() b_c = bias.contiguous() result_c = fn(x_c, b_c) result = fn(x, bias) self.assertEqual(result, result_c) self.assertTrue( result.is_contiguous(memory_format=memory_format), "result of the '{}' is not in '{}' format".format(inspect.getsource(fn).strip(), memory_format)) for fn in return_contig_fns: x_c = x.contiguous() y_c = y.contiguous() result_c = fn(x_c, y_c) result = fn(x, y) self.assertEqual(result, result_c) self.assertTrue( result.is_contiguous(memory_format=torch.contiguous_format), "result of the '{}' is not in '{}' format".format(inspect.getsource(fn).strip(), torch.contiguous_format)) _test_helper( torch.randn((4, 3, 8, 8), device=device).contiguous(memory_format=torch.channels_last), abs(torch.randn((4, 3, 8, 8), device=device)) + 1, torch.randn((1, 3, 1, 1), device=device).contiguous(memory_format=torch.channels_last), torch.channels_last) _test_helper( torch.randn((4, 3, 8, 8, 8), device=device).contiguous(memory_format=torch.channels_last_3d), abs(torch.randn((4, 3, 8, 8, 8), device=device)) + 1, torch.randn((1, 3, 1, 1, 1), device=device).contiguous(memory_format=torch.channels_last_3d), torch.channels_last_3d) # FIXME: make this a elementwise unary and elementwise binary OpInfo test def test_strides_propagation(self, device): def _test_helper(x, op, unary=False): def compare_strides(s1, s2, div): sdiv = [s // div for s in s1] self.assertEqual(sdiv, s2) dim = x.dim() # we produce memory dense outputs, so when input is strided on the last dimension # we need to divide by that dimension stride to compare input and result strides div = x.stride(-1) for p in permutations(range(dim)): xp = x.permute(p) if not unary: y = torch.randn(xp.size(-1), device=x.device, dtype=x.dtype) for inputs in ((xp, xp), (xp, y), (y, xp)): res = op(*inputs) compare_strides(xp.stride(), res.stride(), div) self.assertEqual(xp.size(), res.size()) out = torch.empty(0, device=xp.device, dtype=res.dtype) res = op(*inputs, out=out) compare_strides(xp.stride(), res.stride(), div) self.assertEqual(xp.size(), res.size()) else: res = op(xp) compare_strides(xp.stride(), res.stride(), div) self.assertEqual(xp.size(), res.size()) out = torch.empty(0, device=xp.device, dtype=res.dtype) res = op(xp, out=out) compare_strides(xp.stride(), res.stride(), div) self.assertEqual(xp.size(), res.size()) # torch.eq by default calls TensorIterator with defined output, torch.add with undefined binary_ops = (torch.eq, torch.add) unary_ops = (torch.exp,) # memory dense, sliced and ambiguous sliced (ambiguous dense loses permutation information) xs = (torch.randn(2, 3, 4, device=device), torch.randn(2, 3, 8, device=device)[:, :, ::2], torch.randn(1, 1, 4, 12, device=device)[:, :, :, ::2]) for op in binary_ops: for x in xs: _test_helper(x, op) for op in unary_ops: for x in xs: _test_helper(x, op, unary=True) # FIXME: move dlpack tests to their own test class/suite @skipMeta @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16)) def test_dlpack_capsule_conversion(self, device, dtype): # DLpack does not explicitly support bool (xref dmlc/dlpack#75) x = make_tensor((5,), dtype=dtype, device=device) z = from_dlpack(to_dlpack(x)) self.assertEqual(z, x) @skipMeta @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16)) def test_dlpack_protocol_conversion(self, device, dtype): x = make_tensor((5,), dtype=dtype, device=device) z = from_dlpack(x) self.assertEqual(z, x) @skipMeta @onlyNativeDeviceTypes def test_dlpack_shared_storage(self, device): x = make_tensor((5,), dtype=torch.float64, device=device) z = from_dlpack(to_dlpack(x)) z[0] = z[0] + 20.0 self.assertEqual(z, x) @skipMeta @onlyCUDA @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16)) def test_dlpack_conversion_with_streams(self, device, dtype): # Create a stream where the tensor will reside stream = torch.cuda.Stream() with torch.cuda.stream(stream): # Do an operation in the actual stream x = make_tensor((5,), dtype=dtype, device=device) + 1 # DLPack protocol helps establish a correct stream order # (hence data dependency) at the exchange boundary. # DLPack manages this synchronization for us, so we don't need to # explicitly wait until x is populated stream = torch.cuda.Stream() with torch.cuda.stream(stream): z = from_dlpack(x) stream.synchronize() self.assertEqual(z, x) @skipMeta @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16)) def test_from_dlpack(self, device, dtype): x = make_tensor((5,), dtype=dtype, device=device) y = torch.from_dlpack(x) self.assertEqual(x, y) @skipMeta @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16)) def test_from_dlpack_noncontinguous(self, device, dtype): x = make_tensor((25,), dtype=dtype, device=device).reshape(5, 5) y1 = x[0] y1_dl = torch.from_dlpack(y1) self.assertEqual(y1, y1_dl) y2 = x[:, 0] y2_dl = torch.from_dlpack(y2) self.assertEqual(y2, y2_dl) y3 = x[1, :] y3_dl = torch.from_dlpack(y3) self.assertEqual(y3, y3_dl) y4 = x[1] y4_dl = torch.from_dlpack(y4) self.assertEqual(y4, y4_dl) y5 = x.t() y5_dl = torch.from_dlpack(y5) self.assertEqual(y5, y5_dl) @skipMeta @onlyCUDA @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16)) def test_dlpack_conversion_with_diff_streams(self, device, dtype): stream_a = torch.cuda.Stream() stream_b = torch.cuda.Stream() # DLPack protocol helps establish a correct stream order # (hence data dependency) at the exchange boundary. # the `tensor.__dlpack__` method will insert a synchronization event # in the current stream to make sure that it was correctly populated. with torch.cuda.stream(stream_a): x = make_tensor((5,), dtype=dtype, device=device) + 1 z = torch.from_dlpack(x.__dlpack__(stream_b.cuda_stream)) stream_a.synchronize() stream_b.synchronize() self.assertEqual(z, x) @skipMeta @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16)) def test_from_dlpack_dtype(self, device, dtype): x = make_tensor((5,), dtype=dtype, device=device) y = torch.from_dlpack(x) assert x.dtype == y.dtype @skipMeta @onlyCUDA def test_dlpack_default_stream(self, device): class DLPackTensor: def __init__(self, tensor): self.tensor = tensor def __dlpack_device__(self): return self.tensor.__dlpack_device__() def __dlpack__(self, stream=None): if torch.version.hip is None: assert stream == 1 else: assert stream == 0 capsule = self.tensor.__dlpack__(stream) converted = True return capsule # CUDA-based tests runs on non-default streams with torch.cuda.stream(torch.cuda.default_stream()): x = DLPackTensor(make_tensor((5,), dtype=torch.float32, device=device)) from_dlpack(x) @skipMeta @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16)) def test_dlpack_tensor_invalid_stream(self, device, dtype): with self.assertRaises(TypeError): x = make_tensor((5,), dtype=dtype, device=device) x.__dlpack__(stream=object()) @skipMeta def test_dlpack_error_on_bool_tensor(self): x = torch.tensor([True], dtype=torch.bool) with self.assertRaises(RuntimeError): to_dlpack(x) # TODO: increase tests once NumPy supports the `__dlpack__` protocol @skipMeta def test_dlpack_export_requires_grad(self): x = torch.zeros(10, dtype=torch.float32, requires_grad=True) with self.assertRaisesRegex(RuntimeError, r"require gradient"): x.__dlpack__() @skipMeta def test_dlpack_export_is_conj(self): x = torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]) y = torch.conj(x) with self.assertRaisesRegex(RuntimeError, r"conjugate bit"): y.__dlpack__() @skipMeta def test_dlpack_export_non_strided(self): x = torch.sparse_coo_tensor([[0]], [1], size=(1,)) y = torch.conj(x) with self.assertRaisesRegex(RuntimeError, r"strided"): y.__dlpack__() @onlyCUDA @unittest.skipIf(PYTORCH_CUDA_MEMCHECK, "is_pinned uses failure to detect pointer property") def test_pin_memory_from_constructor(self, device): def _get_like(t, **kwargs): return [ torch.rand_like(t, **kwargs), torch.randn_like(t, **kwargs), torch.empty_like(t, **kwargs), torch.full_like(t, 4, **kwargs), torch.zeros_like(t, **kwargs), torch.ones_like(t, **kwargs), ] def _get_tensors(**kwargs): return [ torch.tensor([10, 11], **kwargs), torch.randn(3, 5, **kwargs), torch.rand(3, **kwargs), # torch.randint(3, 5, **kwargs), // unsupported torch.zeros(3, **kwargs), torch.randperm(3, **kwargs), torch.empty(6, **kwargs), torch.ones(6, **kwargs), torch.eye(6, **kwargs), torch.arange(3, 5, **kwargs)] pinned_tensors = _get_tensors(pin_memory=True) + _get_like(torch.empty(5, dtype=torch.float64), pin_memory=True) for x in pinned_tensors: self.assertTrue(x.is_pinned()) tensors = _get_tensors() + _get_like(torch.empty(5, dtype=torch.float64, pin_memory=True)) for x in tensors: self.assertFalse(x.is_pinned()) @deviceCountAtLeast(1) @onlyCUDA def test_storage_all_devices(self, devices): for device in devices: t = torch.tensor((), device=device) self.assertEqual(t.dtype, t.storage().dtype) # FIXME: move to test distributions @skipIfMps @dtypesIfCUDA(torch.float, torch.double, torch.half) @dtypes(torch.float, torch.double) def test_multinomial(self, device, dtype): def make_prob_dist(shape, is_contiguous): if is_contiguous: if dtype == torch.half: return torch.zeros(shape, device=device).uniform_().to(dtype=torch.half) return torch.zeros(shape, device=device, dtype=dtype).uniform_() elif len(shape) == 1: if dtype == torch.half: return torch.zeros((shape + [5]), device=device).uniform_().to(dtype=torch.half)[:, 2] return torch.zeros((shape + [5]), device=device, dtype=dtype).uniform_()[:, 2] else: # num dim = 2 new_shape = [2, shape[1], 7, 1, shape[0], 1, 10] if dtype == torch.half: prob_dist = torch.zeros(new_shape, device=device).uniform_().to(dtype=torch.half) else: prob_dist = torch.zeros(new_shape, device=device, dtype=dtype).uniform_() prob_dist = prob_dist.transpose(1, 4) prob_dist = prob_dist[1, :, 5, 0, :, 0, 4] assert not prob_dist.is_contiguous() # sanity check return prob_dist for is_contiguous in (True, False): # with replacement n_row = 3 for n_col in range(4, 5 + 1): prob_dist = make_prob_dist([n_row, n_col], is_contiguous) # indices that shouldn't be sampled (<0 means none) zero_prob_indices = torch.LongTensor(n_row).random_(-2, n_col).tolist() for i, j in enumerate(zero_prob_indices): if j >= 0: prob_dist[i, j] = 0 n_sample = n_col * 3 sample_indices = torch.multinomial(prob_dist, n_sample, True) self.assertEqual(prob_dist.dim(), 2) self.assertEqual(sample_indices.size(1), n_sample) for i in range(n_row): zero_prob_idx = zero_prob_indices[i] if zero_prob_idx < 0: continue for j in range(n_sample): self.assertNotEqual(sample_indices[i, j], zero_prob_idx, msg="sampled an index with zero probability") # without replacement n_row = 3 for n_col in range(2, 10 + 1, 2): prob_dist = make_prob_dist([n_row, n_col], is_contiguous) # indices that shouldn't be sampled (<0 means none) zero_prob_indices = torch.LongTensor(n_row).random_(-1, n_col).tolist() for i, j in enumerate(zero_prob_indices): if j >= 0: prob_dist[i, j] = 0 n_sample = max(1, n_col - 2) sample_indices = torch.multinomial(prob_dist, n_sample, False) self.assertEqual(prob_dist.dim(), 2) self.assertEqual(sample_indices.size(1), n_sample) for i in range(n_row): row_samples = {} zero_prob_idx = zero_prob_indices[i] for j in range(n_sample): sample_idx = sample_indices[i, j] if zero_prob_idx >= 0: self.assertNotEqual(sample_idx, zero_prob_idx, msg="sampled an index with zero probability") self.assertNotIn(sample_idx, row_samples, "sampled an index twice") row_samples[sample_idx] = True # vector n_col = 4 prob_dist = make_prob_dist([n_col], is_contiguous).fill_(1) zero_prob_idx = 1 # index that shouldn't be sampled prob_dist[zero_prob_idx] = 0 n_sample = 20 sample_indices = torch.multinomial(prob_dist, n_sample, True) for sample_index in sample_indices: self.assertNotEqual(sample_index, zero_prob_idx, msg="sampled an index with zero probability") s_dim = sample_indices.dim() self.assertEqual(sample_indices.dim(), 1, msg="wrong number of dimensions") self.assertEqual(prob_dist.dim(), 1, msg="wrong number of prob_dist dimensions") self.assertEqual(sample_indices.size(0), n_sample, msg="wrong number of samples") # CUDA misalignment issue (#46702) n_row, n_col = 2, 3 prob_dist = make_prob_dist([n_row, n_col], True) n_sample = 1 sample_indices = torch.multinomial(prob_dist, n_sample, True) self.assertEqual(sample_indices.dim(), 2, msg="wrong number of dimensions") self.assertEqual(sample_indices.size(1), n_sample, msg="wrong number of samples") # FIXME: move to test distributions @onlyCUDA @dtypes(torch.float, torch.double, torch.half) def test_multinomial_deterministic(self, device, dtype): gen = torch.Generator(device=device) trials = 5 seed = 0 prob_dist = torch.rand(10000, 1000, device=device, dtype=dtype) n_sample = 1 for i in range(trials): gen.manual_seed(seed) samples_1 = torch.multinomial(prob_dist, n_sample, True, generator=gen) gen.manual_seed(seed) samples_2 = torch.multinomial(prob_dist, n_sample, True, generator=gen) self.assertEqual(samples_1, samples_2) self.assertEqual(samples_1.dim(), 2, msg="wrong number of dimensions") self.assertEqual(samples_1.size(1), n_sample, msg="wrong number of samples") # FIXME: move to test distributions @slowTest @dtypes(torch.float) def test_multinomial_rng_state_advance(self, device, dtype): corpus_size = 100000 freqs = torch.ones(corpus_size, dtype=torch.float, device=device) n_sample = 100 samples1 = torch.multinomial(freqs, n_sample, replacement=True) samples2 = torch.multinomial(freqs, n_sample, replacement=True) samples = torch.cat([samples1, samples2]) # expect no more than 1 repeating elements generated in 2 attempts # the probability of at least element being repeated is surprisingly large, 18% self.assertLessEqual(2 * n_sample - samples.unique().size(0), 2) samples1 = torch.multinomial(freqs, n_sample, replacement=False) samples2 = torch.multinomial(freqs, n_sample, replacement=False) samples = torch.cat([samples1, samples2]) # expect no more than 1 repeating elements generated in 2 attempts self.assertLessEqual(2 * n_sample - samples.unique().size(0), 1) def _test_memory_format_transformations(self, device, input_generator_fn, transformation_fn, memory_format, compare_data=True, default_is_preserve=False): assert(memory_format == torch.channels_last or memory_format == torch.channels_last_3d) # xc is a channels last tensor xc = input_generator_fn(device) # xc is not memory dense, but looks like channels last if memory_format == torch.channels_last: xc = xc[..., ::2, ::2] else: xc = xc[..., ::2, ::2, ::2] clone = transformation_fn(xc, memory_format=torch.preserve_format) self.assertFalse(clone.is_contiguous()) self.assertTrue(clone.is_contiguous(memory_format=memory_format)) self.assertFalse(xc.is_contiguous()) self.assertFalse(xc.is_contiguous(memory_format=memory_format)) if compare_data: self.assertEqual(xc, clone.to(xc)) xc = input_generator_fn(device) clone = transformation_fn(xc, memory_format=torch.contiguous_format) self.assertTrue(clone.is_contiguous()) self.assertFalse(clone.is_contiguous(memory_format=memory_format)) if compare_data: self.assertEqual(xc, clone.to(xc)) xc = input_generator_fn(device) clone = transformation_fn(xc) if default_is_preserve: self.assertFalse(clone.is_contiguous()) self.assertTrue(clone.is_contiguous(memory_format=memory_format)) else: self.assertTrue(clone.is_contiguous()) self.assertFalse(clone.is_contiguous(memory_format=memory_format)) if compare_data: self.assertEqual(xc, clone.to(xc)) x = torch.randn((3, 4, 5, 6, 7, 8, 9), device=device) for _ in range(10): permutation = list(range(len(x.shape))) random.shuffle(permutation) x = x.permute(permutation) self.assertEqual(x.stride(), transformation_fn(x, memory_format=torch.preserve_format).stride()) def test_memory_format_to(self, device): def get_generator(memory_format, shape): def input_generator_fn(device): return torch.randn(shape, device=device, dtype=torch.float32).contiguous(memory_format=memory_format) return input_generator_fn def transformation_fn(tensor, **kwargs): return tensor.to(dtype=torch.float64, **kwargs) formats_shapes = ( (torch.channels_last, (4, 3, 8, 8)), (torch.channels_last_3d, (4, 3, 8, 8, 8))) for mf, shape in formats_shapes: self._test_memory_format_transformations( device, get_generator(mf, shape), transformation_fn, mf, default_is_preserve=True) def test_memory_format_type(self, device): def get_generator(memory_format, shape): def input_generator_fn(device): return torch.randn(shape, device=device, dtype=torch.float32).contiguous(memory_format=memory_format) return input_generator_fn def transformation_fn(tensor, **kwargs): return tensor.to(torch.float64, **kwargs) formats_shapes = ( (torch.channels_last, (4, 3, 8, 8)), (torch.channels_last_3d, (4, 3, 8, 8, 8))) for mf, shape in formats_shapes: self._test_memory_format_transformations( device, get_generator(mf, shape), transformation_fn, mf, default_is_preserve=True) def test_memory_format_clone(self, device): def get_generator(memory_format, shape): def input_generator_fn(device): return torch.randn(shape, device=device, dtype=torch.float32).contiguous(memory_format=memory_format) return input_generator_fn def transformation_fn(tensor, **kwargs): return tensor.clone(**kwargs) formats_shapes = ( (torch.channels_last, (4, 3, 8, 8)), (torch.channels_last_3d, (4, 3, 8, 8, 8))) for mf, shape in formats_shapes: self._test_memory_format_transformations( device, get_generator(mf, shape), transformation_fn, mf, True, default_is_preserve=True) def test_memory_format_factory_like_functions_preserve(self, device): def get_generator(memory_format, shape): def input_generator_fn(device): return torch.randn(shape, device=device, dtype=torch.float32).contiguous(memory_format=memory_format) return input_generator_fn transformation_fns = [ lambda t, **kwargs: torch.zeros_like(t, **kwargs), lambda t, **kwargs: torch.ones_like(t, **kwargs), lambda t, **kwargs: torch.randint_like(t, 10, 100, **kwargs), lambda t, **kwargs: torch.randint_like(t, 100, **kwargs), lambda t, **kwargs: torch.randn_like(t, **kwargs), lambda t, **kwargs: torch.rand_like(t, **kwargs), lambda t, **kwargs: torch.full_like(t, 7, **kwargs), lambda t, **kwargs: torch.empty_like(t, **kwargs)] formats_shapes = ( (torch.channels_last, (4, 3, 8, 8)), (torch.channels_last_3d, (4, 3, 8, 8, 8))) for mf, shape, in formats_shapes: for transformation_fn in transformation_fns: self._test_memory_format_transformations( device, get_generator(mf, shape), transformation_fn, mf, compare_data=False, default_is_preserve=True) def test_memory_format_type_shortcuts(self, device): def get_generator(memory_format, shape, dtype): def input_generator_fn(device): return torch.randn(shape, device=device, dtype=dtype).clamp(0, 1) \ .round().contiguous(memory_format=memory_format) return input_generator_fn def get_fn(fn_name): def transformation_fn(tensor, **kwargs): fn = getattr(tensor, fn_name) return fn(**kwargs) return transformation_fn shortcuts = ['byte', 'char', 'double', 'bool', 'half', 'int', 'long', 'short'] if device == 'cpu': shortcuts += ['bfloat16'] formats_shapes = ( (torch.channels_last, (4, 3, 8, 8)), (torch.channels_last_3d, (4, 3, 8, 8, 8))) for mf, shape in formats_shapes: for fn_name in shortcuts: self._test_memory_format_transformations( device, get_generator(mf, shape, torch.float32), get_fn(fn_name), mf, default_is_preserve=True) # Test 'float' separately to avoid float->float no-op. for mf, shape in formats_shapes: self._test_memory_format_transformations( device, get_generator(mf, shape, torch.float64), get_fn('float'), mf, default_is_preserve=True) @onlyCUDA def test_memory_format_cpu_and_cuda_ops(self, device): def get_generator(memory_format, shape): def input_generator_fn(device): return torch.randn(shape, device=device, dtype=torch.float32).contiguous(memory_format=memory_format) return input_generator_fn def transformation_cpu_fn(tensor, **kwargs): return tensor.cpu(**kwargs) def transformation_cuda_fn(tensor, **kwargs): return tensor.cuda(**kwargs) formats_shapes = ( (torch.channels_last, (4, 3, 8, 8)), (torch.channels_last_3d, (4, 3, 8, 8, 8))) for mf, shape in formats_shapes: self._test_memory_format_transformations( 'cuda', get_generator(mf, shape), transformation_cpu_fn, mf, default_is_preserve=True) self._test_memory_format_transformations( 'cpu', get_generator(mf, shape), transformation_cuda_fn, mf, default_is_preserve=True) # FIXME: move to test_serialization def test_pickle_gradscaler(self, device): # This test is not in test_cuda.py because it should pass in 3 cases: # 1. cuda is not available. # 2. cuda is available but device is not cuda. # 3. cuda is available and device is cuda. # In case 1, a and b disable themselves on construction and shouldn't try to pickle workhorse attributes. # In case 2, a and b are enabled. Workhorse attributes participate in pickling, but none are lazy-inited # to cuda Tensors, because I don't want to do cuda things if device is not cuda. # In case 3, a and b are enabled and we may also try lazy-initing _scale to a cuda tensor. device = torch.device(device) try_lazy_inits = (True, False) if device.type == "cuda" else (False,) for lazy_init_scale in try_lazy_inits: a = torch.cuda.amp.GradScaler(init_scale=3., growth_factor=4., backoff_factor=.5, growth_interval=2) self.assertTrue(not a.is_enabled() if torch.cuda.amp.common.amp_definitely_not_available() else a.is_enabled()) if lazy_init_scale: # Dummy a.scale() call lazy-inits a._scale Tensor. a.scale(torch.tensor([4.0], dtype=torch.float32, device=device)) self.assertTrue(isinstance(a._scale, torch.cuda.FloatTensor)) # The following three lines should work whether or not cuda is available. serialized = pickle.dumps(a) b = pickle.loads(serialized) self.assertEqual(b.is_enabled(), a.is_enabled()) if a.is_enabled(): self.assertEqual(b.get_scale(), 3.) self.assertEqual(b.get_growth_factor(), 4.) self.assertEqual(b.get_backoff_factor(), .5) self.assertEqual(b.get_growth_interval(), 2) self.assertEqual(b._init_growth_tracker, 0) # supplies a dummy key to test the defaultdict's default_factory self.assertEqual(b._per_optimizer_states["fdsa"], torch.cuda.amp.grad_scaler._refresh_per_optimizer_state()) if lazy_init_scale: self.assertEqual(b.scale(torch.tensor([4.0], dtype=torch.float32, device=device)), 12.0) # FIXME: convert to ErrorInputs @skipIfMps def test_multinomial_invalid(self, device): def test(probs): with self.assertRaisesRegex(RuntimeError, 'probability tensor contains either `inf`, `nan` or element < 0'): torch.multinomial(probs.to(device), 2) torch.cuda.synchronize() test(torch.tensor([1., -1., 1.])) test(torch.tensor([1., inf, 1.])) test(torch.tensor([1., -inf, 1.])) test(torch.tensor([1., 1., nan])) # FIXME: convert to ErrorInputs @skipIfMps def test_multinomial_invalid_distribution(self, device): def test(probs, replacement): with self.assertRaisesRegex(RuntimeError, r"invalid multinomial distribution \(sum of probabilities <= 0\)"): torch.multinomial(probs, 2, replacement) torch.cuda.synchronize() x = torch.zeros(3, device=device) y = torch.zeros(3, 3, device=device) z = torch.zeros(3, 3, device=device) z[1, :] = 1 test(x, False) test(y, False) test(z, False) # Verify only for CPU as replacement=True # throws device side assert triggered. if self.device_type == 'cpu': test(x, True) test(y, True) test(z, True) # FIXME: move to test distributions def _test_multinomial_empty(self, device, replacement, num_samples): probs = torch.ones(0, 3, device=device) expected = torch.empty(0, num_samples, dtype=torch.int64) out = torch.multinomial(probs, num_samples=num_samples, replacement=replacement) self.assertEqual(out, expected) # FIXME: move to test distributions def test_multinomial_empty_w_replacement(self, device): self._test_multinomial_empty(device, True, 1) self._test_multinomial_empty(device, True, 2) # FIXME: move to test distributions def test_multinomial_empty_wo_replacement(self, device): self._test_multinomial_empty(device, False, 1) self._test_multinomial_empty(device, False, 2) @dtypesIfCUDA(torch.float, torch.double, torch.half) @dtypesIfCPU(torch.float, torch.double, torch.bfloat16) @dtypes(torch.float, torch.double) def test_multinomial_cpu(self, device, dtype): def make_prob_dist(shape, is_contiguous): if is_contiguous: if dtype == torch.half or dtype == torch.bfloat16: return torch.zeros(shape, device=device).uniform_().to(dtype=dtype) return torch.zeros(shape, device=device, dtype=dtype).uniform_() elif len(shape) == 1: if dtype == torch.half or dtype == torch.bfloat16: return torch.zeros((shape + [5]), device=device).uniform_().to(dtype=dtype)[:, 2] return torch.zeros((shape + [5]), device=device, dtype=dtype).uniform_()[:, 2] else: # num dim = 2 new_shape = [2, shape[1], 7, 1, shape[0], 1, 10] if dtype == torch.half or dtype == torch.bfloat16: prob_dist = torch.zeros(new_shape, device=device).uniform_().to(dtype=dtype) else: prob_dist = torch.zeros(new_shape, device=device, dtype=dtype).uniform_() prob_dist = prob_dist.transpose(1, 4) prob_dist = prob_dist[1, :, 5, 0, :, 0, 4] assert not prob_dist.is_contiguous() # sanity check return prob_dist # FIXME: move to elementwise ternary test suite # As the test fails with Runtime Error not raised on XLA @onlyNativeDeviceTypes def test_where_scalar_handcrafted_values(self, device): # Tests ScalarxScalar, ScalarxTensor and TensorxScalar # variant of `where` against NumPy version with # handcrafted values. condition_shape = (5, 5) dtypes = ( torch.bool, torch.uint8, torch.int8, torch.int16, torch.int64, torch.float16, torch.float32, torch.float64, torch.complex64, torch.complex128, ) shapes = ((), (5,), (1, 5),) with torch.no_grad(): tensors = (torch.empty(shape, dtype=dtype, device=device).fill_(17) for shape, dtype in product(shapes, dtypes)) # Use different values for `x` and `y` # as they are the output values which are compared. x_vals = (True, 3, 7.0, 1 + 0.5j) y_vals = itertools.chain((False, 4, 8.0, 2 + 0.5j), tensors) for x in x_vals: for y in y_vals: condition = torch.empty(*condition_shape, dtype=torch.bool, device=device).bernoulli_() common_dtype = torch.result_type(x, y) def check_equal(condition, x, y): condition_np = condition.cpu().numpy() x_np = x.cpu().numpy() if isinstance(x, torch.Tensor) else x y_np = y.cpu().numpy() if isinstance(y, torch.Tensor) else y # NumPy aggressively promotes to double, hence cast to output to correct dtype expected = torch.from_numpy(np.where(condition_np, x_np, y_np)).to(common_dtype) result = torch.where(condition, x, y) self.assertEqual(expected, result) check_equal(condition, x, y) check_equal(condition, y, x) def test_hook_remove(self, device): # Reference: https://github.com/pytorch/pytorch/issues/58354 def _test_helper(remove_hook): def install_hook(tensor): handle = None def hook(tensor): if remove_hook: handle.remove() return torch.zeros_like(tensor) handle = tensor.register_hook(hook) t = torch.ones((1, 5), device=device, requires_grad=True) install_hook(t) # First call to backward t.mean().backward() self.assertEqual(t.grad, torch.zeros_like(t)) # Second call to backward t.mean().backward() if remove_hook: # After removing the hook, make sure the usual gradient is returned self.assertEqual(t.grad, 0.2 * torch.ones_like(t)) else: self.assertEqual(t.grad, torch.zeros_like(t)) _test_helper(remove_hook=True) _test_helper(remove_hook=False) # FIXME: get PyTorch/XLA to run test_testing # This test should ideally be in test_testing.py, # but since pytorch/xla runs tests from test_torch.py, we have it here. @skipXLA def test_skip_xla(self, device): if self.device_type == 'xla': # Should not reach here! self.assertTrue(False) # FIXME: get PyTorch/XLA to run test_testing # This test should ideally be in test_testing.py, # but since pytorch/xla runs tests from test_torch.py, we have it here. @expectedFailureXLA def test_expected_failure_xla(self, device): if self.device_type == 'xla': self.assertTrue(False) # FIXME: get PyTorch/XLA to run test_testing # This test should ideally be in test_testing.py, # but since pytorch/xla runs tests from test_torch.py, we have it here. def test_assertRaisesRegex_ignore_msg_non_native_device(self, device): # Verify that self.assertRaisesRegex only checks the Error and ignores # message for non-native devices. x = torch.randn((10, 3), device=device) t = torch.empty(10, dtype=torch.int64, device=device).random_(0, 3) invalid_weight = torch.randn(4, device=device) msg = "weight tensor should be defined either for all 3 classes or no classes" # XLA raises RuntimeError with a different message. with self.assertRaisesRegex(RuntimeError, msg): torch.nn.functional.nll_loss(x, t, weight=invalid_weight) @dtypes(*all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16, torch.complex32)) def test_copy_(self, device, dtype): def can_cast(src_dtype, dst_dtype): # torch.can_cast(torch.int16, torch.uint8) returns True # which isn't actually safe-cast. # This function returns False in this case. def is_unsigned_int(dtype): return dtype is torch.uint8 if is_unsigned_int(dst_dtype): return is_unsigned_int(src_dtype) return torch.can_cast(src_dtype, dst_dtype) def make_tensor_wrapper(shape, dtype): if dtype is not torch.complex32: # Make tensor does not support generating # complex32 tensor return make_tensor(shape, device=device, dtype=dtype) return torch.randn(shape, device=device, dtype=dtype) t = make_tensor_wrapper((50,), dtype) src_dtypes = all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16, torch.complex32) for src_dtype in src_dtypes: src = make_tensor_wrapper((50,), dtype=src_dtype) t.copy_(src) dst = make_tensor_wrapper((50, ), dtype=src_dtype) if can_cast(src_dtype, dtype): rtol = None atol = None if dtype in (torch.half, torch.complex32): rtol = 1e-3 atol = 1e-3 if dtype in (torch.bfloat16,): rtol = 1e-2 atol = 1e-2 self.assertEqual(src, dst.copy_(t), rtol=rtol, atol=atol) @dtypes(*all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16, torch.complex32)) def test_item(self, device, dtype): t = torch.ones((), device=device, dtype=dtype) self.assertEqual(1, t.item()) # Tests that compare a device's computation with the (gold-standard) CPU's. class TestDevicePrecision(TestCase): exact_dtype = True # FIXME: move to indexing test suite @onlyCUDA def test_index_add_bfloat16(self, device): inp_tensor = torch.randn(5, 3, device='cpu').bfloat16() t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.bfloat16, device='cpu') index = torch.tensor([0, 4, 2], device='cpu') out_cpu = inp_tensor.index_add(0, index, t) inp_tensor = inp_tensor.to(device=device) t = t.to(device=device) index = index.to(device=device) out_gpu = inp_tensor.index_add(0, index, t) self.assertEqual(out_cpu, out_gpu, atol=1e-2, rtol=0) # FIXME: move to serialization test suite def test_device_serialization(self, device): x = torch.randn(4, 4, device=device) with tempfile.NamedTemporaryFile() as f: torch.save(x, f) f.seek(0) x_copy = torch.load(f) self.assertEqual(x_copy, x) self.assertIs(type(x_copy), type(x)) self.assertEqual(x_copy.device, x.device) # FIXME: move to serialization test suite @deviceCountAtLeast(2) def test_multidevice_serialization(self, devices): x = [torch.randn(4, 4, device=devices[0]), torch.randn(4, 4, device=devices[1])] with tempfile.NamedTemporaryFile() as f: torch.save(x, f) f.seek(0) x_copy = torch.load(f) for original, cp in zip(x, x_copy): self.assertEqual(cp, original) self.assertIs(type(cp), type(original)) self.assertEqual(cp.device, original.device) # FIXME: move to data movement test suite @deviceCountAtLeast(1) def test_copy_noncontig(self, devices): def do_test(d0, d1): x = torch.tensor([1.5, 2.5, 3.5, 4.5, 5.5, 6.5], device=d0) y = torch.tensor([0, 0, 0, 0, 0, 0], device=d1) self.assertNotEqual(x.dtype, y.dtype) y[::2].copy_(x[::2]) self.assertEqual(y, [1, 0, 3, 0, 5, 0]) do_test('cpu', devices[0]) do_test(devices[0], 'cpu') if len(devices) > 1: do_test(devices[0], devices[1]) @deviceCountAtLeast(2) def test_type_conversions_same_device(self, devices): x = torch.randn(5, 5, device=devices[1]) self.assertEqual(x.int().device, torch.device(devices[1])) self.assertEqual(x.type(torch.int).device, torch.device(devices[1])) self.assertEqual(x.to(torch.int).device, torch.device(devices[1])) @dtypesIfCUDA(torch.half, torch.float, torch.double, torch.int8, torch.short, torch.int, torch.long, torch.uint8) @dtypes(torch.float, torch.double, torch.int8, torch.short, torch.int, torch.long, torch.uint8) def test_from_sequence(self, device, dtype): seq = [list(range(i * 4, i * 4 + 4)) for i in range(5)] reference = torch.arange(0, 20).resize_(5, 4) self.assertEqual(torch.tensor(seq, dtype=dtype, device=device), reference, exact_dtype=False) # FIXME: moved to indexing test suite @deviceCountAtLeast(1) def test_advancedindex_mixed_cpu_devices(self, devices) -> None: def test(x: torch.Tensor, ia: torch.Tensor, ib: torch.Tensor) -> None: # test getitem self.assertEqual(x[:, ia, None, ib, 0].cpu(), x.cpu()[:, ia.cpu(), None, ib.cpu(), 0]) self.assertEqual(x[ia], x.cpu()[ia.cpu()]) # test setitem x_clone1 = x.clone() x_clone2 = x.clone() first_shape = x[:, ia, None, ib, 0].shape second_shape = x[ia].shape x_clone1[:, ia, None, ib, 0] = torch.randn(first_shape).to(x_clone1) x_clone2[ia] = torch.randn(second_shape).to(x_clone2) cpu = torch.device('cpu') for device in devices: # Index cpu tensor with device tensor x = torch.randn(3, 4, 4, 4, 3) ia = torch.tensor([0, 2, 1]).to(device) ib = torch.tensor([0, 2, 1]).to(device) test(x, ia, ib) # Index device tensor with cpu tensor x = x.to(device) ia = ia.to(cpu) ib = ib.to(cpu) test(x, ia, ib) # Index cpu tensor with mixed cpu, device tensors x = x.to(cpu) ia = ia.to(cpu) ib = ib.to(device) test(x, ia, ib) # Index device tensor with mixed cpu, device tensors x = x.to(device) ia = ia.to(cpu) ib = ib.to(device) test(x, ia, ib) if len(devices) > 1: other_device = devices[0] if device == devices[0]: other_device = devices[1] # Index device tensor with mixed cpu, device tensors on different devices x = x.to(device) ia = ia.to(cpu) ib = ib.to(other_device) test(x, ia, ib) # FIXME: move to data movement test suite def test_copy_broadcast(self, device) -> None: x = torch.randn(10, 5) y = torch.randn(5, device=device) x.copy_(y) self.assertEqual(x[3], y) x = torch.randn(10, 5, device=device) y = torch.randn(5) x.copy_(y) self.assertEqual(x[3], y) # FIXME: move to an elementwise ternary test suite @dtypes(torch.int64, torch.float32, torch.float64) def test_clamp(self, device, dtype): test_args = [ *product( [(100, 50), (10, 64), (97,)], # shape (True, False), # non-contiguous ) ] for shape, noncontig in test_args: x = make_tensor(shape, device=device, dtype=dtype, noncontiguous=noncontig) ub = make_tensor(shape, device=device, dtype=dtype, noncontiguous=noncontig) lb = make_tensor(shape, device=device, dtype=dtype, noncontiguous=noncontig) expect = x.max(lb).min(ub) actual = x.clamp(lb, ub) self.assertEqual(expect, actual) expect = np.clip(x.cpu().numpy(), lb.cpu().numpy(), ub.cpu().numpy()) self.assertEqual(expect, actual) expect = x.max(lb) actual = x.clamp(min=lb) self.assertEqual(expect, actual) expect = x.min(ub) actual = x.clamp(max=ub) self.assertEqual(expect, actual) # Test broadcasting min & max expect = x.max(lb[0]).min(ub[..., :1]) actual = x.clamp(lb[0], ub[..., :1]) self.assertEqual(expect, actual) # Test broadcasting x expect = x[..., :1].max(lb).min(ub) actual = x[..., :1].clamp(lb, ub) self.assertEqual(expect, actual) def test_cuda_device_idx(self, device): x = torch.zeros(3, device=device) y = torch._efficientzerotensor(3, device=device) self.assertEqual(x.device, y.device) # we implemented custom deallocation for subclasses, so it behooves # us to make sure all of these bits work. We'll use __del__ to # track if objects die or not class Tracker: def __init__(self, marker): self.marker = marker @staticmethod def make(): marker = [False] return marker, Tracker(marker) def __del__(self): self.marker[0] = True @contextlib.contextmanager def disable_gc(): if gc.isenabled(): try: gc.disable() yield finally: gc.enable() else: yield class TestTorch(TestCase): exact_dtype = True def test_dir(self): dir(torch) def test_wildcard_import(self): exec('from torch import *') def test_newaxis_numpy_comparison(self): def run_test(tensor, *idx): npt = tensor.numpy() self.assertEqual(tensor[idx], npt[idx]) # 1D Tensor Tests x = torch.arange(0, 10) cases = [ [None], [None, None], [Ellipsis, None], [None, Ellipsis], [2, None], [None, 2], [Ellipsis, None, 2], [Ellipsis, 2, None], [2, Ellipsis, None], [2, None, Ellipsis], [None, 2, Ellipsis], [None, Ellipsis, 2], ] for case in cases: run_test(x, *case) # 2D Tensor Tests x = torch.arange(0, 12).view(3, 4) cases = [ [None], [None, None], [None, None, None], [Ellipsis, None], [Ellipsis, None, None], [None, Ellipsis], [None, Ellipsis, None], [None, None, Ellipsis], [2, None], [2, None, Ellipsis], [2, Ellipsis, None], [None, 2, Ellipsis], [Ellipsis, 2, None], [Ellipsis, None, 2], [None, Ellipsis, 2], [1, 2, None], [1, 2, Ellipsis, None], [1, Ellipsis, 2, None], [Ellipsis, 1, None, 2], [Ellipsis, 1, 2, None], [1, None, 2, Ellipsis], [None, 1, Ellipsis, 2], [None, 1, 2, Ellipsis], ] for case in cases: run_test(x, *case) def _consecutive(self, size, start=1): sequence = torch.ones(torch.tensor(size).prod(0)).cumsum(0) sequence.add_(start - 1) return sequence.resize_(*size) def test_newindex(self): reference = self._consecutive((3, 3, 3)) # This relies on __index__() being correct - but we have separate tests for that def checkPartialAssign(index): reference = torch.zeros(3, 3, 3) reference[index] = self._consecutive((3, 3, 3))[index] self.assertEqual(reference[index], self._consecutive((3, 3, 3))[index], atol=0, rtol=0) reference[index] = 0 self.assertEqual(reference, torch.zeros(3, 3, 3), atol=0, rtol=0) checkPartialAssign(0) checkPartialAssign(1) checkPartialAssign(2) checkPartialAssign((0, 1)) checkPartialAssign((1, 2)) checkPartialAssign((0, 2)) checkPartialAssign(torch.LongTensor((0, 2))) with self.assertRaises(IndexError): reference[1, 1, 1, 1] = 1 with self.assertRaises(IndexError): reference[1, 1, 1, (1, 1)] = 1 with self.assertRaises(IndexError): reference[3, 3, 3, 3, 3, 3, 3, 3] = 1 with self.assertRaises(IndexError): reference[0.0] = 1 with self.assertRaises(TypeError): reference[0.0:2.0] = 1 with self.assertRaises(IndexError): reference[0.0, 0.0:2.0] = 1 with self.assertRaises(IndexError): reference[0.0, :, 0.0:2.0] = 1 with self.assertRaises(IndexError): reference[0.0, ..., 0.0:2.0] = 1 with self.assertRaises(IndexError): reference[0.0, :, 0.0] = 1 # FIXME: move to indexing test suite def test_index_add(self): for device in get_all_device_types(): for dest_contig, src_contig, index_contig in product([True, False], repeat=3): for other_sizes in ((), (4, 5)): for dtype in [torch.int, torch.long]: num_copy, num_dest = 3, 3 dest = torch.randn(num_dest, *other_sizes, device=device) if not dest_contig: dest = make_tensor(dest.shape, device=device, dtype=dest.dtype, noncontiguous=True) src = torch.randn(num_copy, *other_sizes, device=device) if not src_contig: src = torch.testing.make_non_contiguous(src) idx = torch.randperm(num_dest, dtype=dtype, device=device).narrow(0, 0, num_copy) if not index_contig: idx = torch.testing.make_non_contiguous(idx) # index_add_ without alpha argument dest2 = dest.clone() dest.index_add_(0, idx, src) for i in range(idx.size(0)): dest2[idx[i]] += src[i] self.assertEqual(dest, dest2) # index_add_ with alpha argument dest2 = dest.clone() dest.index_add_(0, idx, src, alpha=2) for i in range(idx.size(0)): dest2[idx[i]] += src[i] * 2 self.assertEqual(dest, dest2) # FIXME: resolve comment below and move this to indexing test suite # add coverage for issue with atomic add that appeared only for # specific dtypes on cuda: # https://github.com/pytorch/pytorch/issues/29153 def test_index_add_all_dtypes(self): for device in get_all_device_types(): for dtype in get_all_math_dtypes(device): for idx_dtype in [torch.int, torch.long]: size = [5, 5] if dtype.is_floating_point or dtype.is_complex: tensor = torch.rand(size, dtype=dtype, device=device) elif dtype.is_signed: tensor = torch.randint(-5, 15, size, dtype=dtype, device=device) else: tensor = torch.randint(0, 10, size, dtype=dtype, device=device) # index_add calls atomicAdd on cuda. zeros = torch.zeros(size, dtype=dtype, device=device) added = zeros.index_add(0, torch.arange(0, size[0], dtype=idx_dtype, device=device), tensor) self.assertEqual(added, tensor) added = zeros.index_add(0, torch.arange(0, size[0], dtype=idx_dtype, device=device), tensor, alpha=-1) self.assertEqual(added, -tensor) # FIXME: move to shape ops test suite def test_unflatten(self): # test args: tensor, int, sizes self.assertEqual(torch.tensor([]).unflatten(0, (0, 1)), torch.empty(0, 1)) self.assertEqual(torch.tensor([1]).unflatten(0, (1, 1)), torch.tensor([[1]])) self.assertEqual(torch.tensor([1, 2, 3, 4]).unflatten(0, (2, 2)), torch.tensor([[1, 2], [3, 4]])) self.assertEqual(torch.tensor([1, 2, 3, 4]).unflatten(0, [2, 2]), torch.tensor([[1, 2], [3, 4]])) self.assertEqual(torch.tensor([1, 2, 3, 4]).unflatten(0, torch.Size([2, 2])), torch.tensor([[1, 2], [3, 4]])) self.assertEqual(torch.ones(2, 10).unflatten(1, (5, 2)), torch.ones(2, 5, 2)) self.assertEqual(torch.tensor([1, 2, 3, 4]).unflatten(0, (-1, 2)), torch.tensor([[1, 2], [3, 4]])) self.assertEqual(torch.ones(2, 10).unflatten(1, (5, -1)), torch.ones(2, 5, 2)) self.assertEqual(torch.ones(2, 10).unflatten(1, (-1,)), torch.ones(2, 10)) self.assertEqual(torch.ones(2, 3 * 4 * 5 * 6).unflatten(1, (3, 4, -1, 6)), torch.ones(2, 3, 4, 5, 6)) self.assertEqual(torch.ones(2, 0, 2).unflatten(1, (3, -1, 4, 5)), torch.ones(2, 3, 0, 4, 5, 2)) # test invalid args: tensor, str, sizes with self.assertRaisesRegex(TypeError, r"received an invalid combination of arguments"): torch.tensor([1]).unflatten('A', (1, 1)) # test invalid args: tensor, str, namedshape with self.assertRaisesRegex(RuntimeError, r"Name 'A' not found in Tensor\[None\]."): torch.ones(4).unflatten('A', (('A', 2), ('B', 2))) # test other invalid arguments with self.assertRaisesRegex(RuntimeError, r"sizes must be non-empty"): torch.tensor([1]).unflatten(0, []) with self.assertRaisesRegex(RuntimeError, r"Provided sizes \[2, 2\] don't multiply up to the size of dim 0 \(1\)"): torch.tensor([1]).unflatten(0, [2, 2]) with self.assertRaisesRegex(IndexError, r"dimension specified as 0 but tensor has no dimensions"): torch.tensor(1).unflatten(0, [0]) with self.assertRaisesRegex(RuntimeError, r"only one dimension can be inferred"): torch.randn(5, 10).unflatten(1, (-1, -1)) with self.assertRaisesRegex(RuntimeError, r"Provided sizes \[-1, 4\] don't multiply up to the size of dim 1 \(10\)"): torch.randn(5, 10).unflatten(1, (-1, 4)) with self.assertRaisesRegex(RuntimeError, r"the unspecified dimension size -1 can be any value and is ambiguous"): torch.randn(2, 0).unflatten(1, (2, -1, 0)) def test_structseq_repr(self): a = torch.arange(250).reshape(5, 5, 10) expected = """ torch.return_types.max( values=tensor([[ 40, 41, 42, 43, 44, 45, 46, 47, 48, 49], [ 90, 91, 92, 93, 94, 95, 96, 97, 98, 99], [140, 141, 142, 143, 144, 145, 146, 147, 148, 149], [190, 191, 192, 193, 194, 195, 196, 197, 198, 199], [240, 241, 242, 243, 244, 245, 246, 247, 248, 249]]), indices=tensor([[4, 4, 4, 4, 4, 4, 4, 4, 4, 4], [4, 4, 4, 4, 4, 4, 4, 4, 4, 4], [4, 4, 4, 4, 4, 4, 4, 4, 4, 4], [4, 4, 4, 4, 4, 4, 4, 4, 4, 4], [4, 4, 4, 4, 4, 4, 4, 4, 4, 4]]))""" self.assertEqual(repr(a.max(1)), textwrap.dedent(expected).strip()) def test_is_same_size(self): t1 = torch.empty(3, 4, 9, 10) t2 = torch.empty(3, 4) t3 = torch.empty(1, 9, 3, 3) t4 = torch.empty(3, 4, 9, 10) self.assertFalse(t1.is_same_size(t2)) self.assertFalse(t1.is_same_size(t3)) self.assertTrue(t1.is_same_size(t4)) def test_tensor_set(self): t1 = torch.tensor([]) t2 = torch.empty(3, 4, 9, 10).uniform_() t1.set_(t2) self.assertEqual(t1.storage()._cdata, t2.storage()._cdata) size = torch.Size([9, 3, 4, 10]) t1.set_(t2.storage(), 0, size) self.assertEqual(t1.size(), size) t1.set_(t2.storage(), 0, tuple(size)) self.assertEqual(t1.size(), size) self.assertEqual(t1.stride(), (120, 40, 10, 1)) stride = (10, 360, 90, 1) t1.set_(t2.storage(), 0, size, stride) self.assertEqual(t1.stride(), stride) t1.set_(t2.storage(), 0, size=size, stride=stride) self.assertEqual(t1.size(), size) self.assertEqual(t1.stride(), stride) # test argument names t1 = torch.tensor([]) # 1. case when source is tensor t1.set_(source=t2) self.assertEqual(t1.storage()._cdata, t2.storage()._cdata) # 2. case when source is storage t1.set_(source=t2.storage()) self.assertEqual(t1.storage()._cdata, t2.storage()._cdata) # 3. case when source is storage, and other args also specified t1.set_(source=t2.storage(), storage_offset=0, size=size, stride=stride) self.assertEqual(t1.size(), size) self.assertEqual(t1.stride(), stride) t1 = torch.tensor([True, True], dtype=torch.bool) t2 = torch.tensor([False, False], dtype=torch.bool) t1.set_(t2) self.assertEqual(t1.storage()._cdata, t2.storage()._cdata) def test_tensor_set_errors(self): f_cpu = torch.randn((2, 3), dtype=torch.float32) d_cpu = torch.randn((2, 3), dtype=torch.float64) # change dtype self.assertRaises(RuntimeError, lambda: f_cpu.set_(d_cpu.storage())) self.assertRaises(RuntimeError, lambda: f_cpu.set_(d_cpu.storage(), 0, d_cpu.size(), d_cpu.stride())) self.assertRaises(RuntimeError, lambda: f_cpu.set_(d_cpu)) # change device if torch.cuda.is_available(): f_cuda = torch.randn((2, 3), dtype=torch.float32, device='cuda') # cpu -> cuda self.assertRaises(RuntimeError, lambda: f_cpu.set_(f_cuda.storage())) self.assertRaises(RuntimeError, lambda: f_cpu.set_(f_cuda.storage(), 0, f_cuda.size(), f_cuda.stride())) self.assertRaises(RuntimeError, lambda: f_cpu.set_(f_cuda)) # cuda -> cpu self.assertRaises(RuntimeError, lambda: f_cuda.set_(f_cpu.storage())) self.assertRaises(RuntimeError, lambda: f_cuda.set_(f_cpu.storage(), 0, f_cpu.size(), f_cpu.stride())) self.assertRaises(RuntimeError, lambda: f_cuda.set_(f_cpu)) # FIXME: move this test test_testing.py (along with allclose testing) # NOTE: test_equal will be deprecated in favor of torch.testing.assert_close # once torch.testing is out of beta def test_equal(self): # Contiguous, 1D t1 = torch.tensor((3., 4., 9., 10.)) t2 = t1.contiguous() t3 = torch.tensor((1., 9., 3., 10.)) t4 = torch.tensor((3., 4., 9.)) t5 = torch.tensor([]) self.assertTrue(t1.equal(t2)) self.assertFalse(t1.equal(t3)) self.assertFalse(t1.equal(t4)) self.assertFalse(t1.equal(t5)) self.assertTrue(torch.equal(t1, t2)) self.assertFalse(torch.equal(t1, t3)) self.assertFalse(torch.equal(t1, t4)) self.assertFalse(torch.equal(t1, t5)) # Non contiguous, 2D s = torch.tensor(((1, 2, 3, 4), (5, 6, 7, 8))) s1 = s[:, 1:3] s2 = s1.clone() s3 = torch.tensor(((2, 3), (6, 7))) s4 = torch.tensor(((0, 0), (0, 0))) self.assertFalse(s1.is_contiguous()) self.assertTrue(s1.equal(s2)) self.assertTrue(s1.equal(s3)) self.assertFalse(s1.equal(s4)) self.assertTrue(torch.equal(s1, s2)) self.assertTrue(torch.equal(s1, s3)) self.assertFalse(torch.equal(s1, s4)) def test_element_size(self): byte = torch.ByteStorage().element_size() char = torch.CharStorage().element_size() short = torch.ShortStorage().element_size() int = torch.IntStorage().element_size() long = torch.LongStorage().element_size() float = torch.FloatStorage().element_size() double = torch.DoubleStorage().element_size() bool = torch.BoolStorage().element_size() bfloat16 = torch.BFloat16Storage().element_size() complexfloat = torch.ComplexFloatStorage().element_size() complexdouble = torch.ComplexDoubleStorage().element_size() self.assertEqual(byte, torch.ByteTensor().element_size()) self.assertEqual(char, torch.CharTensor().element_size()) self.assertEqual(short, torch.ShortTensor().element_size()) self.assertEqual(int, torch.IntTensor().element_size()) self.assertEqual(long, torch.LongTensor().element_size()) self.assertEqual(float, torch.FloatTensor().element_size()) self.assertEqual(double, torch.DoubleTensor().element_size()) self.assertEqual(bool, torch.BoolTensor().element_size()) self.assertEqual(bfloat16, torch.tensor([], dtype=torch.bfloat16).element_size()) self.assertEqual(complexfloat, torch.tensor([], dtype=torch.complex64).element_size()) self.assertEqual(complexdouble, torch.tensor([], dtype=torch.complex128).element_size()) self.assertGreater(byte, 0) self.assertGreater(char, 0) self.assertGreater(short, 0) self.assertGreater(int, 0) self.assertGreater(long, 0) self.assertGreater(float, 0) self.assertGreater(double, 0) self.assertGreater(bool, 0) self.assertGreater(bfloat16, 0) self.assertGreater(complexfloat, 0) self.assertGreater(complexdouble, 0) # These tests are portable, not necessarily strict for your system. self.assertEqual(byte, 1) self.assertEqual(char, 1) self.assertEqual(bool, 1) self.assertGreaterEqual(short, 2) self.assertGreaterEqual(int, 2) self.assertGreaterEqual(int, short) self.assertGreaterEqual(long, 4) self.assertGreaterEqual(long, int) self.assertGreaterEqual(double, float) def test_permute(self): orig = [1, 2, 3, 4, 5, 6, 7] perm = torch.randperm(7).tolist() x = torch.empty(*orig).fill_(0) new = [i - 1 for i in x.permute(*perm).size()] self.assertEqual(perm, new) self.assertEqual(x.size(), orig) def test_reversed(self): val = torch.arange(0, 10) self.assertEqual(reversed(val), torch.arange(9, -1, -1)) val = torch.arange(1, 10).view(3, 3) self.assertEqual(reversed(val), torch.tensor([[7, 8, 9], [4, 5, 6], [1, 2, 3]])) val = torch.tensor(42) self.assertEqual(reversed(val), torch.tensor(42)) def test_contains(self): x = torch.arange(0, 10) self.assertEqual(4 in x, True) self.assertEqual(12 in x, False) x = torch.arange(1, 10).view(3, 3) val = torch.arange(1, 4) self.assertEqual(val in x, True) val += 10 self.assertEqual(val in x, False) self.assertRaisesRegex( RuntimeError, "Tensor.__contains__ only supports Tensor or scalar, but you passed in a {}.".format(type("foo")), lambda: "foo" in x) self.assertRaisesRegex( RuntimeError, "Tensor.__contains__ only supports Tensor or scalar, but you passed in a {}.".format(type([1, 2])), lambda: [1, 2] in x) def test_deepcopy_parameter(self): from copy import deepcopy l = torch.nn.Linear(10, 1) s = l.state_dict(keep_vars=True) self.assertEqual(torch.nn.Parameter, type(s['weight'])) self.assertEqual(torch.nn.Parameter, type(s['bias'])) s2 = deepcopy(s) self.assertEqual(torch.nn.Parameter, type(s2['weight'])) self.assertEqual(torch.nn.Parameter, type(s2['bias'])) def test_pickle(self): import pickle a = torch.randn(5, 5) serialized = pickle.dumps(a) b = pickle.loads(serialized) self.assertEqual(a, b) def test_pickle_parameter(self): import pickle a = torch.nn.Parameter(torch.randn(5, 5)) serialized = pickle.dumps(a) b = pickle.loads(serialized) self.assertTrue(isinstance(b, torch.nn.Parameter)) self.assertEqual(a.requires_grad, b.requires_grad) self.assertEqual(a, b) def test_pickle_parameter_no_requires_grad(self): import pickle a = torch.nn.Parameter(torch.randn(5, 5), requires_grad=False) serialized = pickle.dumps(a) b = pickle.loads(serialized) self.assertTrue(isinstance(b, torch.nn.Parameter)) self.assertEqual(a.requires_grad, b.requires_grad) self.assertEqual(a, b) def test_pickle_dtype(self): t = torch.float32 serialized = pickle.dumps(t) b = pickle.loads(serialized) self.assertTrue(isinstance(b, torch.dtype)) self.assertEqual(id(b), id(t)) def test_pickle_size(self): a = torch.rand(10).size() serialized = pickle.dumps(a) b = pickle.loads(serialized) self.assertTrue(isinstance(b, torch.Size)) self.assertEqual(a, b) def test_pickle_function(self): # https://github.com/pytorch/pytorch/issues/37703 a = torch.tanh serialized = pickle.dumps(a) b = pickle.loads(serialized) self.assertEqual(a, b) def test_generator_cpu(self): # test default generators are equal self.assertEqual(torch.default_generator, torch.default_generator) # tests Generator API # manual_seed, seed, initial_seed, get_state, set_state g1 = torch.Generator() g2 = torch.Generator() g1.manual_seed(12345) g2.manual_seed(12345) self.assertEqual(g1.initial_seed(), g2.initial_seed()) g1.seed() g2.seed() self.assertNotEqual(g1.initial_seed(), g2.initial_seed()) g1 = torch.Generator() g2_state = g2.get_state() g2_randn = torch.randn(1, generator=g2) g1.set_state(g2_state) g1_randn = torch.randn(1, generator=g1) self.assertEqual(g1_randn, g2_randn) default_state = torch.default_generator.get_state() q = torch.empty(100) g1_normal = q.normal_() g2 = torch.Generator() g2.set_state(default_state) g2_normal = q.normal_(generator=g2) self.assertEqual(g1_normal, g2_normal) def test_invalid_generator_raises(self): self.assertRaises(RuntimeError, lambda: torch.Generator('opengl')) def _sobol_reference_samples(self, scramble: bool) -> torch.Tensor: if not scramble: # theoretical values from Joe Kuo 2010 return torch.tensor( [ [0., 0.], [0.5, 0.5], [0.75, 0.25], [0.25, 0.75], [0.375, 0.375], [0.875, 0.875], [0.625, 0.125], [0.125, 0.625], ], ) else: # theoretical values unknown: convergence properties checked return torch.tensor( [ [0.50860737, 0.29320504], [0.07116939, 0.89594537], [0.49354145, 0.11524881], [0.93097717, 0.70244044], [0.87266153, 0.23887917], [0.31021884, 0.57600391], [0.13687253, 0.42054182], [0.69931293, 0.77336788], ], ) def test_sobolengine_bounds(self, scramble: bool = False): engine = torch.quasirandom.SobolEngine(100, scramble=scramble, seed=123456) sample = engine.draw(512) self.assertTrue(torch.all(sample >= 0)) self.assertTrue(torch.all(sample <= 1)) def test_sobolengine_bounds_scrambled(self): self.test_sobolengine_bounds(scramble=True) def test_sobolengine_draw(self, scramble: bool = False): ref_sample = self._sobol_reference_samples(scramble=scramble) engine = torch.quasirandom.SobolEngine(2, scramble=scramble, seed=123456) sample = engine.draw(n=len(ref_sample)) self.assertEqual(sample, ref_sample) self.assertEqual(engine.num_generated, len(ref_sample)) def test_sobolengine_draw_scrambled(self): self.test_sobolengine_draw(scramble=True) def test_sobolengine_first_point(self): for dtype in (torch.float, torch.double): engine = torch.quasirandom.SobolEngine(2, scramble=False) sample = engine.draw(1, dtype=dtype) self.assertTrue(torch.all(sample == 0)) self.assertEqual(sample.dtype, dtype) for dtype in (torch.float, torch.double): engine = torch.quasirandom.SobolEngine(2, scramble=True, seed=123456) sample = engine.draw(1, dtype=dtype) self.assertTrue(torch.all(sample != 0)) self.assertEqual(sample.dtype, dtype) def test_sobolengine_continuing(self, scramble: bool = False): ref_sample = self._sobol_reference_samples(scramble=scramble) engine = torch.quasirandom.SobolEngine(2, scramble=scramble, seed=123456) n_half = len(ref_sample) // 2 _ = engine.draw(n=n_half) sample = engine.draw(n=n_half) torch.testing.assert_close(sample, ref_sample[n_half:]) def test_sobolengine_continuing_scrambled(self): self.test_sobolengine_continuing(scramble=True) def test_sobolengine_reset(self, scramble: bool = False): ref_sample = self._sobol_reference_samples(scramble=scramble) engine = torch.quasirandom.SobolEngine(2, scramble=scramble, seed=123456) _ = engine.draw(n=len(ref_sample) // 2) engine.reset() self.assertEqual(engine.num_generated, 0) sample = engine.draw(n=len(ref_sample)) torch.testing.assert_close(sample, ref_sample) def test_sobolengine_reset_scrambled(self): self.test_sobolengine_reset(scramble=True) def test_sobolengine_fast_forward(self, scramble: bool = False): ref_sample = self._sobol_reference_samples(scramble=scramble) engine = torch.quasirandom.SobolEngine(2, scramble=scramble, seed=123456) engine.fast_forward(4) sample = engine.draw(n=4) torch.testing.assert_close(sample, ref_sample[4:]) # alternate fast forwarding with sampling engine.reset() even_draws = [] for i in range(8): if i % 2 == 0: even_draws.append(engine.draw()) else: engine.fast_forward(1) torch.testing.assert_close( ref_sample[[i for i in range(8) if i % 2 == 0]], torch.from_numpy(np.concatenate(even_draws)), ) def test_sobolengine_fast_forward_scrambled(self): self.test_sobolengine_fast_forward(scramble=True) def test_sobolengine_distribution(self, scramble=False): d = 50 engine = torch.quasirandom.SobolEngine(d, scramble=scramble, seed=123456) sample = engine.draw(1024) torch.testing.assert_close( torch.mean(sample, dim=0), torch.full((d,), 0.5), atol=2, rtol=2 ) torch.testing.assert_close( np.percentile(sample, 25, axis=0), np.repeat(0.25, d), atol=2, rtol=2 ) torch.testing.assert_close( np.percentile(sample, 75, axis=0), np.repeat(0.75, d), atol=2, rtol=2 ) def test_sobolengine_distribution_scrambled(self): self.test_sobolengine_distribution(scramble=True) def test_sobolengine_draw_base2(self, scramble=False): ref_sample = self._sobol_reference_samples(scramble=scramble) engine = torch.quasirandom.SobolEngine(2, scramble=scramble, seed=123456) sample = engine.draw_base2(2) self.assertEqual(ref_sample[:4], sample) # resampling still having N=2**n sample = engine.draw_base2(2) self.assertEqual(ref_sample[4:8], sample) def test_sobolengine_draw_base2_scrambled(self): self.test_sobolengine_draw_base2(scramble=True) def test_sobolengine_raise(self): maxdim = torch.quasirandom.SobolEngine.MAXDIM with self.assertRaises(ValueError): torch.quasirandom.SobolEngine(maxdim + 1) def test_sobolengine_high_dim(self): engine = torch.quasirandom.SobolEngine(1111, scramble=False, seed=123456) samples1 = engine.draw() vals1, counts1 = torch.unique(samples1, return_counts=True) samples2 = engine.draw() vals2, counts2 = torch.unique(samples2, return_counts=True) self.assertEqual(vals1.item(), 0.0) self.assertEqual(counts1.item(), 1111) self.assertEqual(vals2.item(), 0.5) self.assertEqual(counts1.item(), 1111) def test_parsing_int64(self): # accepts integer arguments x = torch.cumsum(torch.ones(5, 5), 0) self.assertEqual(x, torch.cumsum(torch.ones(5, 5), torch.tensor(0))) # doesn't accept floating point variables self.assertRaises(TypeError, lambda: torch.cumsum(torch.ones(5, 5), torch.tensor(0.))) def test_parsing_double(self): # accepts floating point and integer arguments x = torch.randn(2, 3) torch.isclose(x, x, 1, 1) self.assertTrue(torch.isclose(x, x, 1, 1).all()) self.assertTrue(torch.isclose(x, x, 1.5, 1.).all()) # accepts floating point and integer tensors self.assertTrue(torch.isclose(x, x, torch.tensor(1), torch.tensor(1)).all()) self.assertTrue(torch.isclose(x, x, torch.tensor(1.5), torch.tensor(1.)).all()) # doesn't accept variables with requires_grad self.assertRaises(TypeError, lambda: torch.isclose(x, x, torch.tensor(1.5), torch.tensor(1., requires_grad=True)).all()) def test_parsing_intlist(self): # parse with integer variables self.assertEqual(torch.Size([3, 4]), torch.ones((torch.tensor(3), torch.tensor(4))).shape) self.assertEqual(torch.Size([3, 4]), torch.ones(torch.tensor(3), torch.tensor(4)).shape) # parse with numpy integers self.assertEqual(torch.Size([3, 4]), torch.ones((np.array(3), np.int64(4))).shape) self.assertEqual(torch.Size([3, 4]), torch.ones(np.array(3), np.int64(4)).shape) self.assertEqual(torch.Size([3, 4]), torch.ones((np.int64(3), np.array(4))).shape) self.assertEqual(torch.Size([3, 4]), torch.ones(np.int64(3), np.array(4)).shape) # fail parse with float variables self.assertRaises(TypeError, lambda: torch.ones((torch.tensor(3.), torch.tensor(4)))) # fail parse with numpy floats self.assertRaises(TypeError, lambda: torch.ones((np.float(3.), torch.tensor(4)))) self.assertRaises(TypeError, lambda: torch.ones((np.array(3.), torch.tensor(4)))) # fail parse with > 1 element variables self.assertRaises(TypeError, lambda: torch.ones(torch.tensor(3, 3))) self.assertRaises(TypeError, lambda: torch.ones((torch.tensor(3, 3)))) self.assertRaises(TypeError, lambda: torch.ones(np.array(3, 3))) self.assertRaises(TypeError, lambda: torch.ones((np.array(3, 3)))) # fail parse with additional positional args after intlist arg self.assertRaisesRegex(TypeError, "received an invalid combination of arguments", lambda: torch.LongTensor((6, 0), 1, 1, 0)) self.assertRaisesRegex(TypeError, "missing 1 required positional arguments", lambda: torch.tensor().new_zeros((5, 5), 0)) def test_from_buffer(self): a = bytearray([1, 2, 3, 4]) self.assertEqual(torch.ByteStorage.from_buffer(a).tolist(), [1, 2, 3, 4]) shorts = torch.ShortStorage.from_buffer(a, 'big') self.assertEqual(shorts.size(), 2) self.assertEqual(shorts.tolist(), [258, 772]) ints = torch.IntStorage.from_buffer(a, 'little') self.assertEqual(ints.size(), 1) self.assertEqual(ints[0], 67305985) f = bytearray([0x40, 0x10, 0x00, 0x00]) floats = torch.FloatStorage.from_buffer(f, 'big') self.assertEqual(floats.size(), 1) self.assertEqual(floats[0], 2.25) f = bytearray([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x10, 0x40]) bools = torch.BoolStorage.from_buffer(f, 'big') self.assertEqual(bools.size(), 8) self.assertEqual(bools.tolist(), [False, True, True, True, True, True, True, True]) self.assertEqual(bools.type(), 'torch.BoolStorage') self.assertTrue(isinstance(bools, torch.BoolStorage)) f = bytearray(b'\x80\x02\x8a\nl\xfc\x9cF\xf9 j\xa8P\x19.\x80\x02M\xe9') bools = torch.BoolStorage.from_buffer(f, 'big') self.assertEqual(bools.size(), 19) f = bytearray(b'\0x4A') bools = torch.BoolStorage.from_buffer(f, 'big') self.assertEqual(bools.size(), 4) self.assertEqual(bools.tolist(), [False, True, True, True]) bytes = torch.ByteStorage.from_buffer(a) self.assertEqual(bytes.nbytes(), 4) self.assertEqual(bytes.tolist(), [1, 2, 3, 4]) self.assertTrue(isinstance(bytes, torch.ByteStorage)) def test_storage_error(self): quantized_storages = [ torch.QInt32Storage, torch.QInt8Storage, torch.QUInt2x4Storage, torch.QUInt4x2Storage, torch.QUInt8Storage, ] with self.assertRaisesRegex(RuntimeError, r"Only child classes of _LegacyStorage can be instantiated"): torch.storage._LegacyStorage() for storage_class in torch._storage_classes: if storage_class in [torch._UntypedStorage, torch._TypedStorage]: continue device = 'cuda' if storage_class.__module__ == 'torch.cuda' else 'cpu' dtype = storage_class.dtype if device == 'cuda' and not torch.cuda.is_available(): continue # Legacy <type>Storage constructor errors with self.assertRaisesRegex(RuntimeError, r"'device' cannot be specified"): storage_class(device='cpu') with self.assertRaisesRegex(RuntimeError, r"'dtype' cannot be specified"): storage_class(dtype=torch.float) with self.assertRaisesRegex(TypeError, r"got an unexpected keyword"): storage_class(sdlkjf=torch.float) with self.assertRaisesRegex(RuntimeError, r"Too many positional arguments"): storage_class(0, 0) with self.assertRaisesRegex(TypeError, r"invalid data type"): storage_class('string') with self.assertRaisesRegex(TypeError, r"Argument type not recognized"): storage_class(torch.tensor([])) s = storage_class() with self.assertRaisesRegex(RuntimeError, r"No positional arguments"): storage_class(0, wrap_storage=s._untyped()) with self.assertRaisesRegex(TypeError, r"must be _UntypedStorage"): storage_class(wrap_storage=s) if torch.cuda.is_available(): if storage_class in quantized_storages: with self.assertRaisesRegex(RuntimeError, r"Cannot create CUDA storage with quantized dtype"): s.cuda() else: if s.is_cuda: s_other_device = s.cpu() else: s_other_device = s.cuda() with self.assertRaisesRegex(RuntimeError, r"Device of 'wrap_storage' must be"): storage_class(wrap_storage=s_other_device._untyped()) # _TypedStorage constructor errors with self.assertRaisesRegex(RuntimeError, r"No positional arguments"): torch._TypedStorage(0, wrap_storage=s._untyped(), dtype=dtype) with self.assertRaisesRegex(RuntimeError, r"Argument 'dtype' must be specified"): torch._TypedStorage(wrap_storage=s._untyped()) with self.assertRaisesRegex(TypeError, r"Argument 'dtype' must be torch.dtype"): torch._TypedStorage(wrap_storage=s._untyped(), dtype=0) with self.assertRaisesRegex(RuntimeError, r"Argument 'device' should not be specified"): torch._TypedStorage(wrap_storage=s._untyped(), dtype=dtype, device=device) with self.assertRaisesRegex(TypeError, r"Argument 'wrap_storage' must be _UntypedStorage"): torch._TypedStorage(wrap_storage=s, dtype=dtype) with self.assertRaisesRegex(RuntimeError, r"Storage device not recognized"): torch._TypedStorage(dtype=dtype, device='xla') if torch.cuda.is_available(): if storage_class in quantized_storages: with self.assertRaisesRegex(RuntimeError, r"Cannot create CUDA storage with quantized dtype"): torch._TypedStorage(dtype=dtype, device='cuda') with self.assertRaisesRegex(TypeError, r"Argument type not recognized"): torch._TypedStorage(torch.tensor([]), dtype=dtype, device=device) with self.assertRaisesRegex(RuntimeError, r"Too many positional arguments"): torch._TypedStorage(0, 0, dtype=dtype, device=device) if isinstance(s, torch._TypedStorage): s_other = torch._TypedStorage([1, 2, 3, 4], device=device, dtype=dtype) with self.assertRaisesRegex(RuntimeError, r'cannot set item'): s.fill_(s_other) def test_storage_error_no_attribute(self): storage_classes = [ torch.cuda.ByteStorage, torch.cuda.FloatStorage, ] for storage_class in storage_classes: with self.assertRaisesRegex(RuntimeError, r'Not available for CUDA storage'): storage_class.from_buffer() with self.assertRaisesRegex(RuntimeError, r'Not available for CUDA storage'): storage_class._new_with_weak_ptr() with self.assertRaisesRegex(RuntimeError, r'Not available for CUDA storage'): storage_class._new_shared_filename(0, 0, 0) def test_storage_casts(self): storage = torch.IntStorage([-1, 0, 1, 2, 3, 4]) self.assertEqual(storage.size(), 6) self.assertEqual(storage.tolist(), [-1, 0, 1, 2, 3, 4]) self.assertEqual(storage.type(), 'torch.IntStorage') self.assertIs(storage.dtype, torch.int32) floatStorage = storage.float() self.assertEqual(floatStorage.size(), 6) self.assertEqual(floatStorage.tolist(), [-1, 0, 1, 2, 3, 4]) self.assertEqual(floatStorage.type(), 'torch.FloatStorage') self.assertEqual(floatStorage.int().tolist(), [-1, 0, 1, 2, 3, 4]) self.assertIs(floatStorage.dtype, torch.float32) halfStorage = storage.half() self.assertEqual(halfStorage.size(), 6) self.assertEqual(halfStorage.tolist(), [-1, 0, 1, 2, 3, 4]) self.assertEqual(halfStorage.type(), 'torch.HalfStorage') self.assertEqual(halfStorage.int().tolist(), [-1, 0, 1, 2, 3, 4]) self.assertIs(halfStorage.dtype, torch.float16) bfloat16Storage = storage.bfloat16() self.assertEqual(bfloat16Storage.size(), 6) self.assertEqual(bfloat16Storage.tolist(), [-1, 0, 1, 2, 3, 4]) self.assertEqual(bfloat16Storage.type(), 'torch.BFloat16Storage') self.assertEqual(bfloat16Storage.int().tolist(), [-1, 0, 1, 2, 3, 4]) self.assertIs(bfloat16Storage.dtype, torch.bfloat16) longStorage = storage.long() self.assertEqual(longStorage.size(), 6) self.assertEqual(longStorage.tolist(), [-1, 0, 1, 2, 3, 4]) self.assertEqual(longStorage.type(), 'torch.LongStorage') self.assertEqual(longStorage.int().tolist(), [-1, 0, 1, 2, 3, 4]) self.assertIs(longStorage.dtype, torch.int64) shortStorage = storage.short() self.assertEqual(shortStorage.size(), 6) self.assertEqual(shortStorage.tolist(), [-1, 0, 1, 2, 3, 4]) self.assertEqual(shortStorage.type(), 'torch.ShortStorage') self.assertEqual(shortStorage.int().tolist(), [-1, 0, 1, 2, 3, 4]) self.assertIs(shortStorage.dtype, torch.int16) doubleStorage = storage.double() self.assertEqual(doubleStorage.size(), 6) self.assertEqual(doubleStorage.tolist(), [-1.0, 0.0, 1.0, 2.0, 3.0, 4.0]) self.assertEqual(doubleStorage.type(), 'torch.DoubleStorage') self.assertEqual(doubleStorage.int().tolist(), [-1, 0, 1, 2, 3, 4]) self.assertIs(doubleStorage.dtype, torch.float64) charStorage = storage.char() self.assertEqual(charStorage.size(), 6) self.assertEqual(charStorage.tolist(), [-1.0, 0.0, 1.0, 2.0, 3.0, 4.0]) self.assertEqual(charStorage.type(), 'torch.CharStorage') self.assertEqual(charStorage.int().tolist(), [-1, 0, 1, 2, 3, 4]) self.assertIs(charStorage.dtype, torch.int8) byteStorage = storage.byte() self.assertEqual(byteStorage.size(), 6) self.assertEqual(byteStorage.tolist(), [255, 0, 1, 2, 3, 4]) self.assertEqual(byteStorage.type(), 'torch.ByteStorage') self.assertEqual(byteStorage.int().tolist(), [255, 0, 1, 2, 3, 4]) self.assertIs(byteStorage.dtype, torch.uint8) boolStorage = storage.bool() self.assertEqual(boolStorage.size(), 6) self.assertEqual(boolStorage.tolist(), [True, False, True, True, True, True]) self.assertEqual(boolStorage.type(), 'torch.BoolStorage') self.assertEqual(boolStorage.int().tolist(), [1, 0, 1, 1, 1, 1]) self.assertIs(boolStorage.dtype, torch.bool) complexfloat_storage = torch.ComplexFloatStorage([-1, 0, 1 + 2j, 2.5j, 3.5, 4 - 2j]) self.assertEqual(complexfloat_storage.size(), 6) self.assertEqual(complexfloat_storage.tolist(), [-1, 0, 1 + 2j, 2.5j, 3.5, 4 - 2j]) self.assertEqual(complexfloat_storage.type(), 'torch.ComplexFloatStorage') self.assertIs(complexfloat_storage.dtype, torch.complex64) complexdouble_storage = complexfloat_storage.complex_double() self.assertEqual(complexdouble_storage.size(), 6) self.assertEqual(complexdouble_storage.tolist(), [-1, 0, 1 + 2j, 2.5j, 3.5, 4 - 2j]) self.assertEqual(complexdouble_storage.type(), 'torch.ComplexDoubleStorage') self.assertIs(complexdouble_storage.dtype, torch.complex128) def test_from_file(self): def assert_with_filename(filename): size = 10000 s1 = torch.FloatStorage.from_file(filename, True, size) t1 = torch.FloatTensor(s1).copy_(torch.randn(size)) self.assertEqual(s1.data_ptr(), torch.FloatTensor(s1).data_ptr()) # check mapping s2 = torch.FloatStorage.from_file(filename, True, size) t2 = torch.FloatTensor(s2) self.assertEqual(t1, t2, atol=0, rtol=0) # check changes to t1 from t2 rnum = random.uniform(-1, 1) t1.fill_(rnum) self.assertEqual(t1, t2, atol=0, rtol=0) # check changes to t2 from t1 rnum = random.uniform(-1, 1) t2.fill_(rnum) self.assertEqual(t1, t2, atol=0, rtol=0) # release the tensors del s1, t1, s2, t2 with TemporaryFileName() as fname: assert_with_filename(fname) if IS_FILESYSTEM_UTF8_ENCODING: with TemporaryDirectoryName(suffix='中文') as dname, TemporaryFileName(dir=dname) as fname: assert_with_filename(fname) def test_torch_from_file(self): def assert_with_filename(filename): size = 10000 s1 = torch.from_file(filename, True, size, dtype=torch.float) t1 = torch.FloatTensor(s1).copy_(torch.randn(size)) # check mapping s2 = torch.from_file(filename, True, size, dtype=torch.float) t2 = torch.FloatTensor(s2) self.assertEqual(t1, t2, atol=0, rtol=0) # check changes to t1 from t2 rnum = random.uniform(-1, 1) t1.fill_(rnum) self.assertEqual(t1, t2, atol=0, rtol=0) # check changes to t2 from t1 rnum = random.uniform(-1, 1) t2.fill_(rnum) self.assertEqual(t1, t2, atol=0, rtol=0) # release the tensors del s1, t1, s2, t2 with TemporaryFileName() as fname: assert_with_filename(fname) if IS_FILESYSTEM_UTF8_ENCODING: with TemporaryDirectoryName(suffix='中文') as dname, TemporaryFileName(dir=dname) as fname: assert_with_filename(fname) def test_print(self): default_type = torch.tensor([]).type() for t in torch._tensor_classes: if t == torch.HalfTensor: continue # HalfTensor does not support fill if t.is_sparse: continue if t.is_cuda and not torch.cuda.is_available(): continue obj = t(100, 100).fill_(1) obj.__repr__() str(obj) # test half tensor obj = torch.rand(100, 100, device='cpu').half() obj.__repr__() str(obj) for t in torch._storage_classes: if t == torch.BFloat16Storage: continue # Fix once fill is enabled for bfloat16 if t.is_cuda and not torch.cuda.is_available(): continue if t == torch.BoolStorage or t == torch.cuda.BoolStorage: obj = t(100).fill_(True) else: obj = t(100).fill_(1) obj.__repr__() str(obj) # test complex tensor # complex tensor print uses two formatters, one for real values # and the other for imag values. this is consistent with numpy x = torch.tensor([2.3 + 4j, 7 + 6j]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([2.3000+4.j, 7.0000+6.j])''') # test complex half tensor x = torch.tensor([1.25 + 4j, -7. + 6j], dtype=torch.chalf) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([ 1.2500+4.j, -7.0000+6.j], dtype=torch.complex32)''') # test scientific notation for complex tensors x = torch.tensor([1e28 + 2j , -1e-28j]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1.0000e+28+2.0000e+00j, -0.0000e+00-1.0000e-28j])''') # test big integer x = torch.tensor(2341234123412341) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor(2341234123412341)''') # test scientific notation x = torch.tensor([1e28, 1e-28]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1.0000e+28, 1.0000e-28])''') # test scientific notation using set_printoptions x = torch.tensor([1e2, 1e-2]) torch.set_printoptions(sci_mode=True) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1.0000e+02, 1.0000e-02])''') torch.set_printoptions(sci_mode=False) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([ 100.0000, 0.0100])''') torch.set_printoptions(sci_mode=None) # reset to the default value # test no leading space if all elements positive x = torch.tensor([1, 2]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1, 2])''') # test for leading space if there are negative elements x = torch.tensor([1, -2]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([ 1, -2])''') # test inf and nan x = torch.tensor([4, inf, 1.5, -inf, 0, nan, 1]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([4.0000, inf, 1.5000, -inf, 0.0000, nan, 1.0000])''') y = torch.tensor([4, inf, complex(1.5, inf), complex(-inf, 4), 0, complex(nan, inf), complex(3, nan)]) self.assertEqual(y.__repr__(), str(y)) expected_str = '''\ tensor([4.0000+0.j, inf+0.j, 1.5000+infj, -inf+4.j, 0.0000+0.j, nan+infj, 3.0000+nanj])''' self.assertExpectedInline(str(y), expected_str) # test dtype torch.set_default_dtype(torch.float) x = torch.tensor([1e-324, 1e-323, 1e-322, 1e307, 1e308, 1e309], dtype=torch.float64) self.assertEqual(x.__repr__(), str(x)) expected_str = '''\ tensor([ 0.0000e+00, 9.8813e-324, 9.8813e-323, 1.0000e+307, 1.0000e+308, inf], dtype=torch.float64)''' self.assertExpectedInline(str(x), expected_str) # test changing default dtype torch.set_default_dtype(torch.float64) self.assertEqual(x.__repr__(), str(x)) expected_str = '''\ tensor([ 0.0000e+00, 9.8813e-324, 9.8813e-323, 1.0000e+307, 1.0000e+308, inf])''' self.assertExpectedInline(str(x), expected_str) # test summary x = torch.zeros(10000) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([0., 0., 0., ..., 0., 0., 0.])''') # test internal summary function x = torch.rand(1, 20, 5, 30) summary = torch._tensor_str.get_summarized_data(x) self.assertEqual(summary.shape, (1, 6, 5, 6)) first_and_last = [0, 1, 2, -3, -2, -1] self.assertEqual(summary, x[:, first_and_last][..., first_and_last]) # test device if torch.cuda.is_available(): x = torch.tensor([123], device='cuda:0') self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([123], device='cuda:0')''') # test changing default to cuda torch.set_default_tensor_type(torch.cuda.FloatTensor) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([123])''') # test printing a tensor on a different gpu than current one. if torch.cuda.device_count() >= 2: with torch.cuda.device(1): self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([123], device='cuda:0')''') # test printing cpu tensor when default device is cuda y = torch.tensor([123], device='cpu') self.assertEqual(y.__repr__(), str(y)) self.assertExpectedInline(str(y), '''tensor([123], device='cpu')''') torch.set_default_tensor_type(default_type) # test integral floats and requires_grad x = torch.tensor([123.], requires_grad=True) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([123.], requires_grad=True)''') # test non-contiguous print # sliced tensor should have > PRINT_OPTS.threshold elements x = torch.ones(100, 2, 2, 10) y = x.as_strided(size=(100, 2, 10), stride=(2 * 2 * 10, 2 * 10, 1)) self.assertEqual(str(y), y.__repr__()) expected_str = '''\ tensor([[[1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.]], [[1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.]], [[1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.]], ..., [[1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.]], [[1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.]], [[1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.]]])\ ''' self.assertExpectedInline(str(y), expected_str) x = torch.ones(100, 2, 2, 10) * (1 + 1j) y = x.as_strided(size=(100, 2, 10), stride=(2 * 2 * 10, 2 * 10, 1)) self.assertEqual(str(y), y.__repr__()) expected_str = '''\ tensor([[[1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j], [1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j]], [[1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j], [1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j]], [[1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j], [1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j]], ..., [[1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j], [1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j]], [[1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j], [1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j]], [[1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j], [1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j]]])\ ''' self.assertExpectedInline(str(y), expected_str) # test print 0-dim tensor: there's no 0-dim in Numpy, we match arrayprint style x = torch.tensor(0.00002) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor(2.0000e-05)''') # test print boolean tensor x = torch.tensor([True]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([True])''') x = torch.tensor(True) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor(True)''') # [Numpy] test print float in sci_mode when min < 0.0001. x = torch.tensor([0.00002]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([2.0000e-05])''') # [Numpy] test print complex in sci_mode when real_min < 0.0001 and (or) imag_min < 0.0001. x = torch.tensor([0.00002]) * (1 + 1j) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([2.0000e-05+2.0000e-05j])''') # [Numpy] test print float in sci_mode when max > 1e8. # TODO: Pytorch uses fixed precision to print, while Numpy uses dragon4_scientific # to do automatic trimming and padding. x = torch.tensor([123456789.]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1.2346e+08])''') # [Numpy] test print float in sci_mode when max / min > 1000. x = torch.tensor([0.01, 11]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1.0000e-02, 1.1000e+01])''') # [Numpy] test print int max / min > 1000, no sci_mode x = torch.tensor([1, 1010]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([ 1, 1010])''') # [Numpy] test print int > 1e8, no sci_mode x = torch.tensor([1000000000]) # 1e9 self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1000000000])''') # [Numpy] test printing float in int_mode x = torch.tensor([1., 1000.]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([ 1., 1000.])''') # [Numpy] test printing float in int_mode in sci format when max / min > 1000. x = torch.tensor([1., 1010.]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1.0000e+00, 1.0100e+03])''') def test_sizeof(self) -> None: sizeof_empty = torch.randn(0).storage().__sizeof__() sizeof_10 = torch.randn(10).storage().__sizeof__() sizeof_100 = torch.randn(100).storage().__sizeof__() self.assertEqual((sizeof_100 - sizeof_empty) // (sizeof_10 - sizeof_empty), 10) self.assertEqual((sizeof_100 - sizeof_empty) % (sizeof_10 - sizeof_empty), 0) sizeof_empty = torch.randn(0).to(torch.uint8).storage().__sizeof__() sizeof_10 = torch.randn(10).to(torch.uint8).storage().__sizeof__() sizeof_100 = torch.randn(100).to(torch.uint8).storage().__sizeof__() self.assertEqual((sizeof_100 - sizeof_empty) // (sizeof_10 - sizeof_empty), 10) self.assertEqual((sizeof_100 - sizeof_empty) % (sizeof_10 - sizeof_empty), 0) def test_iter(self) -> None: x = torch.randn(5, 5) for i, sub in enumerate(x): self.assertEqual(sub, x[i]) x = torch.tensor([]) self.assertEqual(list(x), []) def test_new(self) -> None: x = torch.autograd.Variable(torch.tensor([])) y = torch.autograd.Variable(torch.randn(4, 4)) z = torch.autograd.Variable(torch.IntTensor([1, 2, 3])) self.assertEqual(x.new().shape, [0]) self.assertEqual(x.new(), x) self.assertEqual(x.new(1, 2).shape, [1, 2]) self.assertEqual(x.new(torch.Size([3, 4])).shape, [3, 4]) self.assertEqual(x.new([3, 4]).shape, [2]) self.assertEqual(x.new([3, 4]).tolist(), [3, 4]) self.assertEqual(x.new((3, 4)).tolist(), [3, 4]) self.assertEqual(x.new([np.int32(3), np.float64(4)]).tolist(), [3, 4]) self.assertEqual(x.new(np.array((3, 4))).tolist(), [3, 4]) self.assertEqual(x.new([z[2], z[0] + 3]).tolist(), [3, 4]) self.assertEqual(x.new(size=(3, 4)).shape, [3, 4]) self.assertEqual(x.new(()).shape, [0]) self.assertEqual(x.new(y.storage()).data_ptr(), y.data_ptr()) self.assertEqual(x.new(y).data_ptr(), y.data_ptr()) self.assertIsNot(x.new(y), y) self.assertRaises(TypeError, lambda: x.new(z)) # TypeError would be better self.assertRaises(RuntimeError, lambda: x.new(z.storage())) @unittest.skipIf(PYTORCH_CUDA_MEMCHECK, "is_pinned uses failure to detect pointer property") def test_pin_memory(self): x = torch.randn(3, 5) self.assertFalse(x.is_pinned()) if not torch.cuda.is_available(): self.assertRaises(RuntimeError, lambda: x.pin_memory()) else: pinned = x.pin_memory() self.assertTrue(pinned.is_pinned()) self.assertEqual(pinned, x) self.assertNotEqual(pinned.data_ptr(), x.data_ptr()) # test that pin_memory on already pinned tensor has no effect self.assertIs(pinned, pinned.pin_memory()) self.assertEqual(pinned.data_ptr(), pinned.pin_memory().data_ptr()) def test_error_msg_type_translation(self): with self.assertRaisesRegex( RuntimeError, # message includes both Double and Long '(?=.*Double)(?=.*Long)'): # Calls model with a LongTensor input but DoubleTensor weights input = torch.zeros(1, 1, 1, 6, dtype=torch.long) weight = torch.nn.Parameter(torch.zeros(1, 1, 1, 3, dtype=torch.double)) model = torch.nn.Conv2d(1, 1, (1, 3), stride=1, padding=0, bias=False) model.weight = weight out = model(input) def test_apply(self): x = torch.arange(1, 6) res = x.clone().apply_(lambda k: k + k) self.assertEqual(res, x * 2) self.assertRaises(TypeError, lambda: x.apply_(lambda k: "str")) def test_map(self): x = torch.autograd.Variable(torch.randn(3, 3)) y = torch.autograd.Variable(torch.randn(3)) res = x.clone() res.map_(y, lambda a, b: a + b) self.assertEqual(res, x + y) self.assertRaisesRegex(TypeError, "not callable", lambda: res.map_(y, "str")) def test_map2(self): x = torch.autograd.Variable(torch.randn(3, 3)) y = torch.autograd.Variable(torch.randn(3)) z = torch.autograd.Variable(torch.randn(1, 3)) res = x.clone() res.map2_(y, z, lambda a, b, c: a + b * c) self.assertEqual(res, x + y * z) z.requires_grad = True self.assertRaisesRegex( RuntimeError, "requires grad", lambda: res.map2_(y, z, lambda a, b, c: a + b * c)) def test_Size(self): x = torch.Size([1, 2, 3]) self.assertIsInstance(x, tuple) self.assertEqual(x[0], 1) self.assertEqual(x[1], 2) self.assertEqual(x[2], 3) self.assertEqual(len(x), 3) self.assertRaises(TypeError, lambda: torch.Size(torch.ones(3))) self.assertIsInstance(x * 2, torch.Size) self.assertIsInstance(x[:-1], torch.Size) self.assertIsInstance(x + x, torch.Size) def test_Size_scalar(self): three = torch.tensor(3) two = torch.tensor(2) x = torch.Size([0, 1, two, three, 4]) for i in range(1, 5): self.assertEqual(x[i], i) def test_Size_iter(self): for sizes in [iter([1, 2, 3, 4, 5]), range(1, 6)]: x = torch.Size(sizes) for i in range(0, 5): self.assertEqual(x[i], i + 1) def test_t_not_2d_error(self): self.assertRaises(RuntimeError, lambda: torch.randn(2, 3, 4).t()) self.assertRaises(RuntimeError, lambda: torch.randn(2, 3, 4).t_()) # skip this test for now as it affects all tests @unittest.skipIf(True, "flush_denormal not supported") def test_set_flush_denormal(self): tiny_float = 1e-42 tiny_double = 1e-320 float_tensor = torch.FloatTensor([1.0, tiny_float]) double_tensor = torch.DoubleTensor([1.0, tiny_float, tiny_double]) self.assertEqual(float_tensor[0], 1.0, atol=0.0, rtol=0) self.assertEqual(float_tensor[1], tiny_float, atol=tiny_float / 16, rtol=0) self.assertEqual(double_tensor[0], 1.0, atol=0.0, rtol=0) self.assertEqual(double_tensor[1], tiny_float, atol=0.0, rtol=0) self.assertEqual(double_tensor[2], tiny_double, atol=0.0, rtol=0) torch.set_flush_denormal(True) self.assertEqual(float_tensor[0], 1.0, atol=0.0, rtol=0) self.assertEqual(float_tensor[1], 0.0, atol=0.0, rtol=0) # tiny_float to zero self.assertEqual(double_tensor[0], 1.0, atol=0.0, rtol=0) # tiny_float is not converted to zero in double type self.assertEqual(double_tensor[1], tiny_float, atol=0.0, rtol=0) self.assertEqual(double_tensor[2], 0.0, atol=0.0, rtol=0) # tiny_double to zero torch.set_flush_denormal(False) def test_show_config(self): # We can't usefully test the output; just make sure this doesn't crash torch.__config__.show() @unittest.skipIf(IS_FBCODE, "CXX_FLAGS is only for OSS build.") def test_cxx_flags(self): torch.__config__._cxx_flags() def test_parallel_info(self): torch.__config__.parallel_info() @slowTest def test_slow_test(self): # Just a smoketest to make sure our slowTest decorator works. pass def test_is_nonzero(self): with self.assertRaisesRegex(RuntimeError, "Boolean value of Tensor with no values is ambiguous"): torch.tensor([]).is_nonzero() with self.assertRaisesRegex(RuntimeError, "Boolean value of Tensor with more than one value is ambiguous"): torch.tensor([0, 0]).is_nonzero() self.assertFalse(torch.tensor(0).is_nonzero()) self.assertTrue(torch.tensor(1).is_nonzero()) self.assertFalse(torch.tensor([0]).is_nonzero()) self.assertTrue(torch.tensor([1]).is_nonzero()) self.assertFalse(torch.tensor([[0]]).is_nonzero()) self.assertTrue(torch.tensor([[1]]).is_nonzero()) self.assertTrue(torch.tensor(0.1).is_nonzero()) self.assertTrue(torch.tensor(-0.1).is_nonzero()) self.assertFalse(torch.tensor(0.0).is_nonzero()) self.assertTrue(torch.tensor(True).is_nonzero()) self.assertFalse(torch.tensor(False).is_nonzero()) self.assertFalse(torch.tensor(0 + 0j).is_nonzero()) self.assertTrue(torch.tensor(0 + 0.1j).is_nonzero()) def test_assert_async(self): with self.assertRaisesRegex(RuntimeError, "Boolean value of Tensor with no values is ambiguous"): torch._assert_async(torch.tensor([])) with self.assertRaisesRegex(RuntimeError, "Boolean value of Tensor with more than one value is ambiguous"): torch._assert_async(torch.tensor([0, 0])) with self.assertRaisesRegex(RuntimeError, "Expected Tensor with single nonzero value, but got zero"): torch._assert_async(torch.tensor(0)) torch._assert_async(torch.tensor(1)) torch._assert_async(torch.tensor(0.1)) torch._assert_async(torch.tensor(-0.1)) with self.assertRaisesRegex(RuntimeError, "Expected Tensor with single nonzero value, but got zero"): torch._assert_async(torch.tensor(0.0)) torch._assert_async(torch.tensor(True)) with self.assertRaisesRegex(RuntimeError, "Expected Tensor with single nonzero value, but got zero"): torch._assert_async(torch.tensor(False)) torch._assert_async(torch.tensor(0 + 0.1j)) with self.assertRaisesRegex(RuntimeError, "Expected Tensor with single nonzero value, but got zero"): torch._assert_async(torch.tensor(0 + 0j)) # NB: we must not be built with CUDA; if we are built with CUDA but no CUDA # is available, we get a different error. @unittest.skipIf(torch.backends.cuda.is_built() or IS_SANDCASTLE, "CUDA is built, can't test CUDA not built error") def test_cuda_not_built(self): msg = "Torch not compiled with CUDA enabled" self.assertRaisesRegex(AssertionError, msg, lambda: torch.cuda.current_device()) self.assertRaisesRegex(AssertionError, msg, lambda: torch.tensor([1], device="cuda")) self.assertRaisesRegex(AssertionError, msg, lambda: torch.tensor([1]).cuda()) self.assertRaisesRegex(TypeError, msg, lambda: torch.cuda.FloatTensor()) self.assertRaisesRegex(TypeError, msg, lambda: torch.set_default_tensor_type(torch.cuda.FloatTensor)) self.assertRaisesRegex(AssertionError, msg, lambda: torch.tensor([1]).to(device="cuda")) def test_has_internal_overlap(self): OVERLAP_NO = 0 OVERLAP_YES = 1 OVERLAP_TOO_HARD = 2 # Check for contiguous tensors a = torch.randn(3, 3) self.assertEqual(torch._debug_has_internal_overlap(a), OVERLAP_NO) # Checks for zero strides b = torch.randn(1, 3) b_expanded = b.expand(4, 3) self.assertEqual(torch._debug_has_internal_overlap(b_expanded), OVERLAP_YES) # Check for zero strided, size 1 axis, in non-contiguous storage (gh-33812) c = torch.randn(10).as_strided([2, 1, 5], [1, 0, 2]) self.assertEqual(torch._debug_has_internal_overlap(c), OVERLAP_NO) c = torch.randn(2, 1, 10)[::2].as_strided((2, 1, 5), (10, 0, 2)) self.assertEqual(torch._debug_has_internal_overlap(c), OVERLAP_TOO_HARD) def test_allow_tensor_metadata_change(self): def do_test(t): with self.assertRaisesRegex( RuntimeError, "set_sizes_contiguous is not allowed on a Tensor created from .data or .detach()"): t.resize_((2, 1)) with self.assertRaisesRegex( RuntimeError, "set_storage is not allowed on a Tensor created from .data or .detach()"): t.set_() with self.assertRaisesRegex( RuntimeError, "set_storage_offset is not allowed on a Tensor created from .data or .detach()"): t.set_(t.storage(), 0, t.size(), list(t.stride())) do_test(torch.tensor([[1, 2]]).data) do_test(torch.tensor([[1, 2]]).detach()) @skipIfNotRegistered("LayerNorm", "Skipping as LayerNorm is not registered") def test_c10_layer_norm(self): # test that we can call c10 ops and they return a reasonable result X = torch.rand(5, 5, dtype=torch.float) weight = torch.rand(*X.size()[1:], dtype=torch.float) bias = torch.rand(*X.size()[1:], dtype=torch.float) epsilon = 1e-4 expected_norm = torch.nn.functional.layer_norm( X, X.size()[1:], weight=weight, bias=bias, eps=epsilon) actual_norm, actual_mean, actual_stdev = \ torch.ops._caffe2.LayerNorm(torch.tensor(X), torch.tensor( weight), torch.tensor(bias), 1, epsilon, True) torch.testing.assert_close(expected_norm, actual_norm) def test_memory_format(self): def test_helper(x, memory_format): y = x.contiguous(memory_format=memory_format) self.assertFalse(y.is_contiguous()) self.assertTrue(y.is_contiguous(memory_format=memory_format)) self.assertEqual(y, x) test_helper(torch.randn(4, 3, 8, 8), torch.channels_last) test_helper(torch.randn(4, 3, 8, 8, 8), torch.channels_last_3d) def test_memory_format_contiguous_returns_same_tensor_if_already_satisfies(self): def test_helper(x, memory_format): alias = x.contiguous(memory_format=memory_format) alias.fill_(7) self.assertEqual(x, alias) test_helper(torch.randn(4, 8, 8, 3).permute(0, 3, 1, 2), torch.channels_last) test_helper(torch.randn(4, 8, 8, 8, 3).permute(0, 4, 1, 2, 3), torch.channels_last_3d) def test_memory_format_empty(self): def test_helper(dim1, dim2, memory_format): with self.assertRaises(RuntimeError): x = torch.empty(dim1, memory_format=memory_format) x = torch.empty(dim2, memory_format=memory_format) self.assertTrue(x.is_contiguous(memory_format=memory_format)) test_helper((3, 3), (3, 3, 3, 3), torch.channels_last) test_helper((3, 3, 3), (3, 3, 3, 3, 3), torch.channels_last_3d) def test_subclass_tensors(self): # raise an error when trying to subclass FloatTensor with self.assertRaisesRegex(TypeError, "type 'torch.FloatTensor' is not an acceptable base type"): class Foo1(torch.FloatTensor): pass # but allow subclassing Tensor: class Foo2(torch.Tensor): def foo(self): return 5 f = Foo2() self.assertEqual(f.foo(), 5) def test_ndim(self): a = torch.randn(1, 2, 3) self.assertEqual(3, a.ndim) b = torch.randn(()) self.assertEqual(0, b.ndim) c = torch.randn(1, 0) self.assertEqual(2, c.ndim) def test_fill_diagonal(self): a1 = torch.randn(7, 3) a2 = a1.clone() v = 1 for i in range(3): a2[i][i] = v a1.fill_diagonal_(v) self.assertEqual(a1, a2) b1 = torch.randn(7, 3) b2 = b1.clone() for i in range(3): b2[i][i] = v b2[i + 4][i] = v b1.fill_diagonal_(v, wrap=True) self.assertEqual(b1, b2) c1 = torch.rand(3, 3, 3) c2 = c1.clone() for i in range(3): c2[i][i][i] = v c1.fill_diagonal_(v) self.assertEqual(c1, c2) # non-contiguous tensor d1 = torch.rand(3, 3, 3)[:, 1, ...] d2 = d1.clone() for i in range(3): d2[i][i] = v d1.fill_diagonal_(v) self.assertEqual(d1, d2) e1 = torch.rand(7, 3, 3)[:, 1, ...] e2 = e1.clone() for i in range(3): e2[i][i] = v e2[i + 4][i] = v e1.fill_diagonal_(v, wrap=True) self.assertEqual(e1, e2) def test_setting_real_imag_to_a_number(self): x = torch.randn(4, dtype=torch.cfloat) x.real = 0 x.imag = 0 zeros = torch.zeros(4) self.assertEqual(x.real, zeros) self.assertEqual(x.imag, zeros) def test_batch_norm_cpu_inference(self): # input nchw in (2,1,1,1), (2,2,2,2) inputs = [ torch.tensor([[[[-0.5000]]], [[[0.5000]]]]), torch.tensor([ [ [[-0.5000, 0.5000], [-1.0000, 1.0000]], [[-0.2500, -0.5000], [0.2500, 0.5000]] ], [ [[0.1000, 1.0000], [1.0000, 0.1000]], [[1.0000, 0.5000], [1.5000, -1.5000]] ]])] # output nchw in (2,1,1,1), (2,2,2,2) outputs = [ torch.tensor([ [[[-0.499997496604919433593750000]]], [[[0.499997496604919433593750000]]]]), torch.tensor([ [[[-0.499997496604919433593750000, 0.499997496604919433593750000], [-0.999994993209838867187500000, 0.999994993209838867187500000]], [[-0.249998748302459716796875000, -0.499997496604919433593750000], [0.249998748302459716796875000, 0.499997496604919433593750000]]], [[[0.099999502301216125488281250, 0.999994993209838867187500000], [0.999994993209838867187500000, 0.099999502301216125488281250]], [[0.999994993209838867187500000, 0.499997496604919433593750000], [1.499992489814758300781250000, -1.499992489814758300781250000]]]])] for i in range(len(inputs)): for affine in [False, True]: m = torch.nn.BatchNorm2d(inputs[i].size()[1], 1e-05, 0.1, affine=affine) m.eval() # contiguous case input1 = inputs[i].contiguous() output1 = m(input1) # non-contiguous case input2 = input1.permute(0, 1, 3, 2) output2 = m(input2).permute(0, 1, 3, 2) # channels last case input3 = input1.contiguous(memory_format=torch.channels_last) output3 = m(input3) self.assertEqual(output3, outputs[i]) self.assertEqual(output3, output1) self.assertEqual(output3, output2) # FIXME: move these meta tests to their own test suite/class or # distribute them among the appropriate test suites for their ops def test_empty_meta(self): x = torch.empty(2 ** 20, 2 ** 20, device='meta') y = torch.empty(2 ** 20, device='meta') z = x + y self.assertEqual(z.size(), (2 ** 20, 2 ** 20)) self.assertRaises(RuntimeError, lambda: z[0][0].item()) def test_format_scalar_meta(self): x = torch.empty((), device='meta') self.assertEqual(format(x), repr(x)) def test_upsample_nearest1d_meta(self): # TODO: this test should be triggered by test_nn.py but right # now meta is not enabled (and even if it was, we are probably # missing too many meta functions to get through the test unmolested) # NB: Can't make the exponent too big, or it will overflow # signed 64-bit integer x = torch.empty(2 * 10 ** 8, 3, 2 * 10 ** 8, device='meta') z = torch.nn.functional.interpolate(x, scale_factor=2) self.assertEqual(z.size(), (2 * 10 ** 8, 3, 4 * 10 ** 8)) self.assertRaises(RuntimeError, lambda: z[0][0][0].item()) # TODO: the out tests cannot be triggered by test_nn.py because # we don't actually do out= arguments for nn functions, so there # is no public API by which to get the out version # interpolate doesn't seem to support out= # (not sure why passing None here doesn't work? How strange...) z = torch.empty(0, device='meta') torch._C._nn.upsample_nearest1d(x, (4 * 10 ** 8,), 2, out=z) self.assertEqual(z.size(), (2 * 10 ** 8, 3, 4 * 10 ** 8)) self.assertRaises(RuntimeError, lambda: z[0][0][0].item()) def test_upsample_nearest2d_meta(self): # TODO: the out tests cannot be triggered by test_nn.py because # we don't actually do out= arguments for nn functions, so there # is no public API by which to get the out version # Make sure we don't clobber strides of out tensor. NB: this # test must be done on 2d/3d, because 1d doesn't have any meaningful # layout support x = torch.empty(4, 3, 8, 8, device='meta') out = torch.empty(4, 3, 16, 16, device='meta', memory_format=torch.channels_last) torch._C._nn.upsample_nearest2d(x, (16, 16), out=out) self.assertTrue(out.is_contiguous(memory_format=torch.channels_last)) x = torch.empty(4, 3, 8, 8, device='meta', memory_format=torch.channels_last) out = torch.empty(4, 3, 16, 16, device='meta') torch._C._nn.upsample_nearest2d(x, (16, 16), out=out) self.assertTrue(out.is_contiguous()) # But if resize occurs, do clobber x = torch.empty(4, 3, 8, 8, device='meta', memory_format=torch.channels_last) out = torch.empty(0, device='meta') torch._C._nn.upsample_nearest2d(x, (16, 16), out=out) self.assertTrue(out.is_contiguous(memory_format=torch.channels_last)) # Complain if out dtype mismatch x = torch.empty(4, 3, 8, 8, device='meta', dtype=torch.float) out = torch.empty(4, 3, 16, 16, device='meta', dtype=torch.double) self.assertExpectedRaisesInline( RuntimeError, lambda: torch._C._nn.upsample_nearest2d(x, (16, 16), out=out), """Expected out tensor to have dtype float, but got double instead""" ) # Complain if out device mismatch x = torch.empty(0, 3, 8, 8, device='meta') out = torch.empty(0, 3, 16, 16, device='cpu') self.assertExpectedRaisesInline( RuntimeError, lambda: torch._C._nn.upsample_nearest2d(x, (16, 16), out=out), """Expected out tensor to have device meta, but got cpu instead""" ) def test_add_meta_scalar(self): # From https://github.com/pytorch/pytorch/issues/53815 x = torch.empty(2, device='meta') y = x + 2 self.assertEqual(y.size(), x.size()) def test_normal_shape(self): warned = False for device in get_all_device_types(): tensor1 = torch.rand(1, device=device) tensor4 = torch.rand(4, device=device) tensor120 = torch.rand(120, device=device) tensor2145 = torch.rand(2, 1, 4, 5, device=device) tensor2345 = torch.rand(2, 3, 4, 5, device=device) tensor2345_non_contiguous = torch.rand(2, 4, 3, 5, device=device).permute(0, 2, 1, 3) tensor2345_channels_last = tensor2345.contiguous(memory_format=torch.channels_last) output2345 = torch.zeros(2, 3, 4, 5, device=device) output345 = torch.zeros(3, 4, 5, device=device) # inputs have same size self.assertEqual(torch.normal(tensor2345, tensor2345).size(), (2, 3, 4, 5)) self.assertEqual(torch.normal(tensor2345_non_contiguous, tensor2345).size(), (2, 3, 4, 5)) self.assertEqual(torch.normal(tensor2345, tensor2345_channels_last).size(), (2, 3, 4, 5)) self.assertEqual(torch.normal(tensor2345_non_contiguous, tensor2345_channels_last).size(), (2, 3, 4, 5)) # scalar case self.assertEqual(torch.normal(tensor2345, 2).size(), (2, 3, 4, 5)) self.assertEqual(torch.normal(2, tensor2345).size(), (2, 3, 4, 5)) # inputs are expandable tensors self.assertEqual(torch.normal(tensor2345, tensor1).size(), (2, 3, 4, 5)) self.assertEqual(torch.normal(tensor2145, tensor2345).size(), (2, 3, 4, 5)) # inputs are non-expandable tensors, but they have same number of elements with self.assertRaisesRegex( RuntimeError, r"The size of tensor a \(120\) must match the size of " r"tensor b \(5\) at non-singleton dimension 3"): self.assertEqual(torch.normal(tensor120, tensor2345).size(), (120,)) with self.assertRaisesRegex( RuntimeError, r"The size of tensor a \(5\) must match the size of " r"tensor b \(120\) at non-singleton dimension 3"): self.assertEqual(torch.normal(tensor2345, tensor120).size(), (2, 3, 4, 5)) # inputs are non-expandable tensors and they don't have same number of elements with self.assertRaisesRegex( RuntimeError, r"The size of tensor a \(5\) must match the size of " r"tensor b \(4\) at non-singleton dimension 3"): torch.normal(tensor2345, tensor4) # output and inputs are size compatible self.assertEqual(torch.normal(tensor2345, tensor2345, out=output2345).size(), (2, 3, 4, 5)) # output and inputs are not size compatible with self.assertWarnsRegex( UserWarning, "This behavior is deprecated, and in a future PyTorch " "release outputs will not be resized unless they have " "zero elements"): self.assertEqual(torch.normal(tensor2345, tensor2145, out=output345).size(), (2, 3, 4, 5)) with self.assertRaisesRegex( RuntimeError, r"The size of tensor a \(5\) must match the size of " r"tensor b \(120\) at non-singleton dimension 3"): # inputs are not expandable, output size is not the same as mean torch.normal(tensor2345, tensor120, out=output345) def test_tensoriterator_output_setup(self): # Test whether the output's memory layout is correct def test_memory_layout(x, y, scale, zero_point, out): self.assertEqual(x.dim(), 4) self.assertEqual(x.size(), y.size()) self.assertEqual(y.size(), out.size()) shape = x.size() for n in range(shape[0]): for c in range(shape[1]): for h in range(shape[2]): for w in range(shape[3]): if scale is not None and zero_point is not None: self.assertEqual( out[n][c][h][w], torch.ops.quantized.add(x[n][c][h][w], y[n][c][h][w], scale, zero_point)) else: self.assertEqual(out[n][c][h][w], x[n][c][h][w] + y[n][c][h][w]) xraw = torch.rand(2, 3, 4, 4) yraw = torch.rand(2, 3, 4, 4) qxraw = torch.quantize_per_tensor(xraw, 0.1, 5, torch.quint8) qyraw = torch.quantize_per_tensor(yraw, 0.1, 5, torch.quint8) # contiguous case fast setup test_memory_layout(xraw, yraw, None, None, xraw + yraw) test_memory_layout(qxraw, qyraw, 0.1, 5, torch.ops.quantized.add(qxraw, qyraw, 0.1, 5)) # channels last case fast setup x = xraw.contiguous(memory_format=torch.channels_last) y = yraw.contiguous(memory_format=torch.channels_last) test_memory_layout(x, y, None, None, x + y) qx = qxraw.contiguous(memory_format=torch.channels_last) qy = qyraw.contiguous(memory_format=torch.channels_last) test_memory_layout(qx, qy, 0.1, 5, torch.ops.quantized.add(qx, qy, 0.1, 5)) # non contiguous case fast setup (dense, non-overlapping, same shape and strides) x = xraw.permute(0, 2, 3, 1) y = yraw.permute(0, 2, 3, 1) test_memory_layout(x, y, None, None, x + y) qx = qxraw.permute(0, 2, 3, 1) qy = qyraw.permute(0, 2, 3, 1) test_memory_layout(qx, qy, 0.1, 5, torch.ops.quantized.add(qx, qy, 0.1, 5)) # non contiguous case fast setup (dense, non-overlapping) # input tensors have same shape and strides # output tensor have same shape as input tensors but different stride # output tensor should preserve its strides in this case x = xraw.permute(0, 2, 3, 1) y = yraw.permute(0, 2, 3, 1) out = torch.empty_like(xraw) out = out.permute(0, 3, 2, 1) expected_stride = out.stride() test_memory_layout(x, y, None, None, torch.add(x, y, out=out)) self.assertEqual(expected_stride, out.stride()) # non contiguous case non fast setup x = xraw.permute(0, 2, 3, 1) y = yraw.permute(0, 3, 2, 1) test_memory_layout(x, y, None, None, x + y) qx = qxraw.permute(0, 2, 3, 1) qy = qyraw.permute(0, 3, 2, 1) test_memory_layout(qx, qy, 0.1, 5, torch.ops.quantized.add(qx, qy, 0.1, 5)) # Tests to make sure we still handle .data properly until it is removed def test_dot_data_use(self): # .data allows to change the Tensors types inplace, check that we still # raise a nice error. with self.assertRaisesRegex( RuntimeError, # message includes both Double and Long '(?=.*Double)(?=.*Long)'): # Calls model with a LongTensor input but DoubleTensor weights input = torch.randn(1, 1, 1, 6, dtype=torch.double) weight = torch.zeros(1, 1, 1, 3, dtype=torch.long) model = torch.nn.Conv2d(1, 1, (1, 3), stride=1, padding=0, bias=False) model.weight.data = weight out = model(input) def test_empty_storage_view(self): # we should be able to "modify" slices of a 0-element # array without an error being raised due to # trying to resize its storage t = torch.from_numpy(np.empty((0, 4))) t[:, 1::2] *= 1 def test_has_storage(self): self.assertIsNotNone(torch.tensor([]).storage()) self.assertIsNotNone(torch.empty(0).storage()) self.assertIsNotNone(torch.tensor([]).clone().storage()) self.assertIsNotNone(torch.tensor([0, 0, 0]).nonzero().storage()) self.assertIsNotNone(torch.tensor([]).new().storage()) # FIXME: Extend this test and put in a TensorProperties test class def test_numel(self): b = torch.ByteTensor(3, 100, 100) self.assertEqual(b.nelement(), 3 * 100 * 100) self.assertEqual(b.numel(), 3 * 100 * 100) # Verifies that (deep)copies of dtypes are the same objects def test_copy_dtypes(self): for dtype in all_types_and_complex_and(torch.half, torch.bfloat16, torch.bool): copied_dtype = copy.deepcopy(dtype) self.assertIs(dtype, copied_dtype) def test_dtype_is_signed(self): for dtype in all_types_and_complex_and(torch.half, torch.bfloat16, torch.half): self.assertEqual(dtype.is_signed, torch.is_signed(torch.tensor(0, dtype=dtype))) self.assertRaisesRegex(RuntimeError, 'not supported for quantized', lambda: torch.quint8.is_signed) self.assertRaisesRegex(RuntimeError, 'not supported for quantized', lambda: torch.qint8.is_signed) self.assertRaisesRegex(RuntimeError, 'not supported for quantized', lambda: torch.qint32.is_signed) # FIXME: Put the following random tests into their own test class or test suite def test_RNGState(self): state = torch.get_rng_state() stateCloned = state.clone() before = torch.rand(1000) self.assertEqual(state.ne(stateCloned).long().sum(), 0, atol=0, rtol=0) torch.set_rng_state(state) after = torch.rand(1000) self.assertEqual(before, after, atol=0, rtol=0) def test_RNGStateAliasing(self): # Fork the random number stream at this point gen = torch.Generator() gen.set_state(torch.get_rng_state()) self.assertEqual(gen.get_state(), torch.get_rng_state()) target_value = torch.rand(1000) # Dramatically alter the internal state of the main generator _ = torch.rand(100000) forked_value = torch.rand(1000, generator=gen) self.assertEqual(target_value, forked_value, atol=0, rtol=0, msg="RNG has not forked correctly.") def test_RNG_after_pickle(self): torch.random.manual_seed(100) before = torch.rand(10) torch.random.manual_seed(100) buf = io.BytesIO() tensor = torch.tensor([1, 2, 3]) ForkingPickler(buf, pickle.HIGHEST_PROTOCOL).dump(tensor) after = torch.rand(10) self.assertEqual(before, after, atol=0, rtol=0) def test_boxMullerState(self): torch.manual_seed(123) odd_number = 101 seeded = torch.randn(odd_number) state = torch.get_rng_state() midstream = torch.randn(odd_number) torch.set_rng_state(state) repeat_midstream = torch.randn(odd_number) torch.manual_seed(123) reseeded = torch.randn(odd_number) self.assertEqual(midstream, repeat_midstream, atol=0, rtol=0, msg='get_rng_state/set_rng_state not generating same sequence of normally distributed numbers') self.assertEqual(seeded, reseeded, atol=0, rtol=0, msg='repeated calls to manual_seed not generating same sequence of normally distributed numbers') def test_manual_seed(self): rng_state = torch.get_rng_state() torch.manual_seed(2) x = torch.randn(100) self.assertEqual(torch.initial_seed(), 2) torch.manual_seed(2) y = torch.randn(100) self.assertEqual(x, y) max_int64 = 0x7fff_ffff_ffff_ffff min_int64 = -max_int64 - 1 max_uint64 = 0xffff_ffff_ffff_ffff # Check all boundary cases of valid seed value inputs test_cases = [ # (seed, expected_initial_seed) # Positive seeds should be unchanged (max_int64, max_int64), (max_int64 + 1, max_int64 + 1), (max_uint64, max_uint64), (0, 0), # Negative seeds wrap around starting from the largest seed value (-1, max_uint64), (min_int64, max_int64 + 1) ] for seed, expected_initial_seed in test_cases: torch.manual_seed(seed) actual_initial_seed = torch.initial_seed() msg = "expected initial_seed() = %x after calling manual_seed(%x), but got %x instead" % ( expected_initial_seed, seed, actual_initial_seed) self.assertEqual(expected_initial_seed, actual_initial_seed, msg=msg) for invalid_seed in [min_int64 - 1, max_uint64 + 1]: with self.assertRaisesRegex(RuntimeError, r'Overflow when unpacking long'): torch.manual_seed(invalid_seed) torch.set_rng_state(rng_state) # FIXME: Describe this test and port to the generic device framework in a more # appropriate test suite for the copy operation def test_copy_transpose(self): x = torch.arange(100 * 100, dtype=torch.float).reshape(100, 100).t() y = torch.empty(100, 100, dtype=torch.float) y.copy_(x) self.assertEqual(y[:, 0], range(100)) self.assertEqual(y[:, 40], range(4000, 4100)) y = torch.empty(100, 100, dtype=torch.double) y.copy_(x) self.assertEqual(y[:, 0], range(100)) self.assertEqual(y[:, 40], range(4000, 4100)) # Validates regression reported in https://github.com/pytorch/pytorch/issues/45269 x = torch.arange(100 * 100).reshape(100, 100).to(dtype=torch.cfloat).t() y = torch.empty(100, 100, dtype=torch.cfloat) y.copy_(x) self.assertEqual(y[:, 0], range(100)) self.assertEqual(y[:, 40], range(4000, 4100)) x = torch.arange(100 * 100).reshape(100, 100).to(dtype=torch.complex32).t() y = torch.empty(100, 100, dtype=torch.complex32) y.copy_(x) self.assertEqual(y[:, 0], range(100)) self.assertEqual(y[:, 40], range(4000, 4100)) # FIXME: Port to a more appropriate test suite def test_copy_broadcast(self): torch.zeros(5, 6).copy_(torch.zeros(6)) self.assertRaises(RuntimeError, lambda: torch.zeros(5, 6).copy_(torch.zeros(30))) # FIXME: Port to a more appropriate test suite def test_copy_many_to_one(self): # Testing in-place copy where it attempt to write from many memory # storage to a single storage would cause RuntimeError to be thrown self.assertRaises(RuntimeError, lambda: torch.zeros(1, 6).expand(5, 6).copy_(torch.zeros(5, 6))) # FIXME: Port to a more appropriate test suite def _test_to_with_layout(self, layout): def test_copy_behavior(t, non_blocking=False): self.assertIs(t, t.to(t, non_blocking=non_blocking)) self.assertIs(t, t.to(t.dtype, non_blocking=non_blocking)) self.assertIs(t, t.to(torch.empty_like(t), non_blocking=non_blocking)) self.assertIsNot(t, t.to(t, non_blocking=non_blocking, copy=True)) self.assertIsNot(t, t.to(t.dtype, non_blocking=non_blocking, copy=True)) self.assertIsNot(t, t.to(torch.empty_like(t), non_blocking=non_blocking, copy=True)) devices = [t.device] if t.device.type == 'cuda': if t.device.index == -1: devices.append('cuda:{}'.format(torch.cuda.current_device())) elif t.device.index == torch.cuda.current_device(): devices.append('cuda') for device in devices: self.assertIs(t, t.to(device, non_blocking=non_blocking)) self.assertIs(t, t.to(device, t.dtype, non_blocking=non_blocking)) self.assertIsNot(t, t.to(device, non_blocking=non_blocking, copy=True)) self.assertIsNot(t, t.to(device, t.dtype, non_blocking=non_blocking, copy=True)) a = torch.tensor(5) if layout == torch.sparse_csr: a = torch.tensor([[0, 1, 2], [2, 0, 3]]).to_sparse_csr() test_copy_behavior(a) self.assertEqual(a.device, a.to('cpu').device) self.assertEqual(a.device, a.to('cpu', dtype=torch.float32).device) self.assertIs(torch.float32, a.to('cpu', dtype=torch.float32).dtype) self.assertEqual(a.device, a.to(torch.float32).device) self.assertIs(torch.float32, a.to(dtype=torch.float32).dtype) def test_data_ptr(getter): self.assertEqual(getter(a), getter(a.to('cpu'))) self.assertEqual(getter(a), getter(a.to(dtype=a.dtype, device=a.device, copy=False))) self.assertEqual(getter(a), getter(a.to('cpu', copy=False))) self.assertNotEqual(getter(a), getter(a.to('cpu', copy=True))) if layout == torch.sparse_csr: # TODO: compressed sparse tensors currently don't support data_ptr. # Exercising failure will allow us to widen coverage of this test once it does. with self.assertRaisesRegex(RuntimeError, "Cannot access data pointer of Tensor that doesn't have storage"): a.data_ptr() # While compressed sparse tensors don't have a concept of data_ptr # the underlying tensors do. The implementation of to appropriately forwards # the call to the components, which is what we're test here. test_data_ptr(lambda a: a.values().data_ptr()) test_data_ptr(lambda a: a.crow_indices().data_ptr()) test_data_ptr(lambda a: a.col_indices().data_ptr()) else: test_data_ptr(lambda a: a.data_ptr()) if torch.cuda.is_available(): for non_blocking in [True, False]: for cuda in ['cuda', 'cuda:0' if torch.cuda.device_count() == 1 else 'cuda:1']: b = torch.tensor(5., device=cuda) test_copy_behavior(b, non_blocking) self.assertEqual(b.device, b.to(cuda, non_blocking=non_blocking).device) self.assertEqual(a.device, b.to('cpu', non_blocking=non_blocking).device) self.assertEqual(b.device, a.to(cuda, non_blocking=non_blocking).device) self.assertIs(torch.int32, b.to('cpu', dtype=torch.int32, non_blocking=non_blocking).dtype) self.assertEqual(a.device, b.to('cpu', dtype=torch.int32, non_blocking=non_blocking).device) self.assertIs(torch.int32, b.to(dtype=torch.int32).dtype) self.assertEqual(b.device, b.to(dtype=torch.int32).device) def test_to(self): self._test_to_with_layout(torch.strided) is_cuda10_2_or_higher = ( (torch.version.cuda is not None) and ([int(x) for x in torch.version.cuda.split(".")] >= [10, 2])) if is_cuda10_2_or_higher: # in cuda10_1 sparse_csr is beta self._test_to_with_layout(torch.sparse_csr) # FIXME: describe this test def test_as_subclass(self): class SubTensor(torch.Tensor): member_var = object() t0 = torch.tensor(0) t1 = torch.tensor([1, 2]) t2 = torch.tensor([[3, 4], [5, 6]]) s0 = t0.as_subclass(SubTensor) s1 = t1.as_subclass(SubTensor) s2 = t2.as_subclass(SubTensor) # Check that the correct type is returned. self.assertTrue(type(s0) is SubTensor) self.assertTrue(type(s1) is SubTensor) self.assertTrue(type(s2) is SubTensor) # Check that the data is equal. self.assertEqual(t0, s0) self.assertEqual(t1, s1) self.assertEqual(t2, s2) t0[()] = 1 t1[1] = 3 t2[1, 1] = 7 # Check that the data is equal even after modification. self.assertEqual(t0, s0) self.assertEqual(t1, s1) self.assertEqual(t2, s2) # Check that member variables are passed through. self.assertTrue(s0.member_var is SubTensor.member_var) self.assertTrue(s1.member_var is SubTensor.member_var) self.assertTrue(s2.member_var is SubTensor.member_var) # Test that autograd is propagated. t = torch.tensor(5, dtype=torch.float32, requires_grad=True) # Run a calculation on the tensor. exp_t = torch.exp(t) # Cast exp_t to a subclass. exp_s = exp_t.as_subclass(SubTensor) # Make sure that t.grad was initially None self.assertTrue(t.grad is None) # Run the autograd calculation. exp_s.backward() # Make sure autograd was propagated to the original tensor # declared with requires_grad. self.assertTrue(t.grad is not None) # Make sure invalid subclasses raise nice errors class BadSubTensor(): member_var = object() err_msg = "Creating a Tensor subclass from a class that does not inherit from Tensor" with self.assertRaisesRegex(RuntimeError, err_msg): s0 = t0.as_subclass(BadSubTensor) # FIXME: Port to a test suite that better fits slicing def test_slice(self): empty = torch.empty(0, 4) x = torch.arange(0., 16).view(4, 4) self.assertEqual(x[:], x) self.assertEqual(x[:4], x) # start and stop are clamped to the size of dim self.assertEqual(x[:5], x) # if start >= stop then the result is empty self.assertEqual(x[2:1], empty) self.assertEqual(x[2:2], empty) # out of bounds is also empty self.assertEqual(x[10:12], empty) # additional correctness checks self.assertEqual(x[:1].tolist(), [[0, 1, 2, 3]]) self.assertEqual(x[:-3].tolist(), [[0, 1, 2, 3]]) self.assertEqual(x[:, -2:3].tolist(), [[2], [6], [10], [14]]) self.assertEqual(x[0:-1:2].tolist(), [[0, 1, 2, 3], [8, 9, 10, 11]]) def test_type(self): x = torch.randn(3, 3).double() self.assertEqual(x.type('torch.FloatTensor').dtype, torch.float32) self.assertEqual(x.type(torch.FloatTensor).dtype, torch.float32) self.assertEqual(x.int().type(torch.Tensor).dtype, torch.get_default_dtype()) self.assertEqual(x.type(torch.int32).dtype, torch.int32) # FIXME: port to a quantization test suite def test_qengine(self): qengines = torch.backends.quantized.supported_engines original_qe = torch.backends.quantized.engine for qe in qengines: torch.backends.quantized.engine = qe assert torch.backends.quantized.engine == qe, 'qengine not set successfully' torch.backends.quantized.engine = original_qe # FIXME: port to a distributed test suite -- also... how could this be OOMing on Windows CUDA? @slowTest @unittest.skipIf(NO_MULTIPROCESSING_SPAWN, "Disabled for environments that \ don't support multiprocessing with spawn start method") @unittest.skipIf(IS_WINDOWS, 'FIXME: CUDA OOM error on Windows') def test_multinomial_invalid_probs(self): def _spawn_method(self, method, arg): try: mp.set_start_method('spawn') except RuntimeError: pass with mp.Pool(1) as pool: out: list = pool.map(method, [arg]) self.assertTrue(out[0]) def _test_multinomial_invalid_probs(probs): try: # n_sample = 1 is a special case, test n_sample=2 which is more general torch.multinomial(probs.to('cpu'), 2) return False # Should not be reached except RuntimeError as e: return 'probability tensor contains either `inf`, `nan` or element < 0' in str(e) _spawn_method(_test_multinomial_invalid_probs, torch.tensor([1., -1., 1.])) _spawn_method(_test_multinomial_invalid_probs, torch.tensor([1., inf, 1.])) _spawn_method(_test_multinomial_invalid_probs, torch.tensor([1., -inf, 1.])) _spawn_method(_test_multinomial_invalid_probs, torch.tensor([1., 1., nan])) # FIXME: port to more appropriate test suite def test_to_with_tensor(self): a = torch.tensor(5) self.assertEqual(a.device, a.to(a).device) if torch.cuda.is_available(): for non_blocking in [True, False]: for cuda in ['cuda', 'cuda:0' if torch.cuda.device_count() == 1 else 'cuda:1']: b = torch.tensor(5., device=cuda) self.assertEqual(b.device, b.to(b, non_blocking=non_blocking).device) self.assertEqual(a.device, b.to(a, non_blocking=non_blocking).device) self.assertEqual(b.device, a.to(b, non_blocking=non_blocking).device) def test_device(self): cpu = torch.device('cpu') self.assertEqual('cpu', str(cpu)) self.assertEqual('cpu', cpu.type) self.assertEqual(None, cpu.index) cpu0 = torch.device('cpu:0') self.assertEqual('cpu:0', str(cpu0)) self.assertEqual('cpu', cpu0.type) self.assertEqual(0, cpu0.index) cpu0 = torch.device('cpu', 0) self.assertEqual('cpu:0', str(cpu0)) self.assertEqual('cpu', cpu0.type) self.assertEqual(0, cpu0.index) cuda = torch.device('cuda') self.assertEqual('cuda', str(cuda)) self.assertEqual('cuda', cuda.type) self.assertEqual(None, cuda.index) cuda1 = torch.device('cuda:1') self.assertEqual('cuda:1', str(cuda1)) self.assertEqual('cuda', cuda1.type) self.assertEqual(1, cuda1.index) cuda1 = torch.device('cuda', 1) self.assertEqual('cuda:1', str(cuda1)) self.assertEqual('cuda', cuda1.type) self.assertEqual(1, cuda1.index) cuda90 = torch.device('cuda', 90) self.assertEqual('cuda:90', str(cuda90)) self.assertEqual('cuda', cuda90.type) self.assertEqual(90, cuda90.index) self.assertRaises(RuntimeError, lambda: torch.device('cpu:-1')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:-1')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2 ')) self.assertRaises(RuntimeError, lambda: torch.device('cuda: 2')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2 2')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2.')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2?')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:?2')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2.232')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2 cuda:3')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2+cuda:3')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2cuda:3')) self.assertRaises(RuntimeError, lambda: torch.device(-1)) self.assertRaises(RuntimeError, lambda: torch.device('other')) self.assertRaises(RuntimeError, lambda: torch.device('other:0')) device_set = {'cpu', 'cpu:0', 'cuda', 'cuda:0', 'cuda:1', 'cuda:10', 'cuda:100'} device_hash_set = set() for device in list(device_set): device_hash_set.add(hash(torch.device(device))) self.assertEqual(len(device_set), len(device_hash_set)) def get_expected_device_repr(device): if device.index is not None: return "device(type='{type}', index={index})".format( type=device.type, index=device.index) return "device(type='{type}')".format(type=device.type) for device in device_set: dev = torch.device(device) self.assertEqual(repr(dev), get_expected_device_repr(dev)) # Tests that the use_deterministic_flag can be set as expected @wrapDeterministicFlagAPITest def test_deterministic_flag(self): for deterministic, warn_only in product([True, False], [True, False]): torch.use_deterministic_algorithms(deterministic, warn_only=warn_only) self.assertEqual(deterministic, torch.are_deterministic_algorithms_enabled()) self.assertEqual(warn_only, torch.is_deterministic_algorithms_warn_only_enabled()) if deterministic: if warn_only: debug_mode = 1 else: debug_mode = 2 else: debug_mode = 0 self.assertEqual(debug_mode, torch.get_deterministic_debug_mode()) for debug_mode in [0, 1, 2]: torch.set_deterministic_debug_mode(debug_mode) self.assertEqual(debug_mode, torch.get_deterministic_debug_mode()) deterministic = debug_mode in [1, 2] warn_only = debug_mode == 1 self.assertEqual(deterministic, torch.are_deterministic_algorithms_enabled()) self.assertEqual(warn_only, torch.is_deterministic_algorithms_warn_only_enabled()) for debug_mode, debug_mode_str in [(0, 'default'), (1, 'warn'), (2, 'error')]: torch.set_deterministic_debug_mode(debug_mode_str) self.assertEqual(debug_mode, torch.get_deterministic_debug_mode()) with self.assertRaisesRegex( TypeError, r"_set_deterministic_algorithms\(\): argument 'mode' \(position 1\) must be bool, not int"): torch.use_deterministic_algorithms(1) with self.assertRaisesRegex( TypeError, r"_set_deterministic_algorithms\(\): argument 'warn_only' must be bool, not int"): torch.use_deterministic_algorithms(False, warn_only=1) def test_type_conversion_via_dtype_name(self): x = torch.tensor([1]) self.assertEqual(x.byte().dtype, torch.uint8) self.assertEqual(x.bool().dtype, torch.bool) self.assertEqual(x.char().dtype, torch.int8) self.assertEqual(x.double().dtype, torch.float64) self.assertEqual(x.float().dtype, torch.float32) self.assertEqual(x.half().dtype, torch.float16) self.assertEqual(x.int().dtype, torch.int32) self.assertEqual(x.bfloat16().dtype, torch.bfloat16) cfloat = x.cfloat() self.assertEqual(cfloat.dtype, torch.complex64) self.assertEqual(cfloat.real, x.float()) self.assertEqual(cfloat.imag, torch.zeros_like(cfloat.imag)) cdouble = x.cdouble() self.assertEqual(cdouble.dtype, torch.complex128) self.assertEqual(cdouble.real, x.double()) self.assertEqual(cdouble.imag, torch.zeros_like(cdouble.imag)) chalf = x.chalf() self.assertEqual(chalf.dtype, torch.complex32) self.assertEqual(chalf.real, x.half()) self.assertEqual(chalf.imag, torch.zeros_like(chalf.imag)) def test_type_alias(self): type_alias_map = {torch.float64: torch.double, torch.float32: torch.float, torch.int32: torch.int, torch.int64: torch.long, torch.int16: torch.short, torch.float16: torch.half, torch.complex32: torch.chalf, torch.complex64: torch.cfloat} for dtype, alias in type_alias_map.items(): self.assertIs(alias, dtype) # FIXME: Describe this test def test_doc_template(self) -> None: from torch._torch_docs import __file__ as doc_file from torch._torch_docs import multi_dim_common, single_dim_common, factory_common_args, factory_like_common_args with open(doc_file, "r", encoding="utf-8") as f: doc_strs = f.read() for doc_str in re.findall(r'add_docstr\((.*?),.*?("""|\'\'\')(.*?)("""|\'\'\')\)', doc_strs, re.MULTILINE | re.DOTALL): for common_args in [multi_dim_common, single_dim_common, factory_common_args, factory_like_common_args]: for k, v in common_args.items(): self.assertNotIn(v, doc_str[2], 'The argument description "{}" in {} can be ' 'replaced by {{{}}}'.format(v, doc_str[0], k)) def test_doc(self): checked_types = (types.MethodType, types.FunctionType, types.BuiltinFunctionType, types.BuiltinMethodType) def _test_namespace(ns, *skips): if isinstance(ns, object): ns_name = ns.__class__.__name__ else: ns_name = ns.__name__ skip_regexes = [] for r in skips: if isinstance(r, string_classes): skip_regexes.append(re.compile('^{}$'.format(re.escape(r)))) else: skip_regexes.append(r) for name in dir(ns): if name.startswith('_'): continue if name in ['real', 'imag']: y = torch.randn(1, dtype=torch.cfloat) var = getattr(y, name) elif name in ["H", "mT", "mH"]: y = torch.randn(1, 1) var = getattr(y, name) else: var = getattr(ns, name) if not isinstance(var, checked_types): continue doc = var.__doc__ has_doc = doc is not None and len(doc.strip()) > 0 full_name = ns_name + '.' + name if any(r.match(name) for r in skip_regexes): self.assertFalse(has_doc, 'New docs have been added for {}, please remove ' 'it from the skipped list in TestTorch.test_doc'.format(full_name)) else: self.assertTrue(has_doc, '{} is missing documentation'.format(full_name)) # FIXME: All of the following should be marked as expected failures # so that it is easier to tell when missing has been added. # FIXME: fix all the skipped ones below! test_namespace(torch.randn(1), 'as_strided_', re.compile('^clamp_(min|max)_?$'), 'is_distributed', 'is_nonzero', 'is_same_size', 'log_softmax', 'map2_', 'new', 'reinforce', 'relu', 'relu_', 'prelu', 'resize', 'resize_as', 'softmax', 'split_with_sizes', 'unsafe_split_with_sizes', '_autocast_to_fp16', '_autocast_to_fp32', ) test_namespace(torch.nn) test_namespace(torch.nn.functional, 'assert_int_or_pair') # TODO: add torch.* tests when we have proper namespacing on ATen functions # test_namespace(torch) # FIXME: deprecate torch.Tensor constructor def test_tensor_ctor_scalar(self): x = torch.Tensor(torch.tensor(1.0)) self.assertEqual(x, torch.tensor(1.0)) def test_deepcopy_gradient(self): from copy import deepcopy a = torch.zeros(10) a.grad = torch.ones(10) self.assertEqual(a.grad, deepcopy(a).grad) s = torch.zeros(10).to_sparse() s.grad = torch.ones(10).to_sparse() self.assertEqual(s.grad, deepcopy(s).grad) # ensure sharing is not broken c = deepcopy([a, a.grad]) self.assertTrue(c[0].grad is c[1]) def test_tensor_base_init(self): # Direct construction not OK self.assertRaises(RuntimeError, lambda: torch._C._TensorBase()) # But construction of subclass is OK class T(torch._C._TensorBase): pass T() def test_tensor_base_new(self): # OK to call super().__new__, see # https://github.com/pytorch/pytorch/issues/57421 class TestTensor(torch._C._TensorBase): @staticmethod def __new__(cls, x, *args, **kwargs): return super().__new__(cls, x, *args, **kwargs) x = torch.ones(5) test_tensor = TestTensor(x) def test_pyobj_preserved(self): x = torch.empty(2) x.foo = 2 # put something on __dict__ y = torch.empty(2) y.grad = x del x # x is dead in Python self.assertEqual(y.grad.foo, 2) z = y.grad # it's live del z # it's dead again self.assertEqual(y.grad.foo, 2) def test_subclass_preserved(self): class MyTensor(torch.Tensor): pass x = MyTensor(torch.empty(2)) y = torch.empty(2) y.grad = x del x # x is dead in Python self.assertEqual(type(y.grad), MyTensor) z = y.grad # it's live del z # it's dead again self.assertEqual(type(y.grad), MyTensor) def test_tensor_slot_dealloc(self): class SlotTensor1(torch._C._TensorBase): __slots__ = ['slot1'] class SlotTensor2(SlotTensor1): __slots__ = ['slot2'] m1, t1 = Tracker.make() m2, t2 = Tracker.make() slot_tensor = SlotTensor2(torch.empty(2)) slot_tensor.slot1 = t1 slot_tensor.slot2 = t2 del t1 del t2 self.assertFalse(m1[0]) self.assertFalse(m2[0]) del slot_tensor self.assertTrue(m1[0]) self.assertTrue(m2[0]) def test_tensor_dict_dealloc(self): m, t = Tracker.make() x = torch.empty(2) x.arf = t del t self.assertFalse(m[0]) del x self.assertTrue(m[0]) def test_tensor_finalizer_dealloc(self): m = [False] class FinalizerTensor(torch._C._TensorBase): def __del__(self): m[0] = True fin_tensor = FinalizerTensor(torch.empty(2)) self.assertFalse(m[0]) del fin_tensor self.assertTrue(m[0]) def test_tensor_weakref_dealloc(self): x = torch.empty(2) m = [False] def cb(r): m[0] = True wref = weakref.ref(x, cb) del x self.assertTrue(m[0]) self.assertEqual(wref(), None) def test_tensor_cycle_via_dict(self): m1, t1 = Tracker.make() x = torch.empty(2) x._tracker = t1 del t1 m2, t2 = Tracker.make() y = torch.empty(2) y._tracker = t2 del t2 x._loop = y y._loop = x # C++ reference should keep the cycle live! # This exercise THPVariable_subtype_traverse # NB: Because z.grad is a reference done entirely in C++, cycles # involving it directly are NOT broken by Python GC; you've # set up a good old C++ reference cycle which we cannot safely # break (because C++ references are allowed to be accessed # multithreaded-ly) (TODO: except maybe if you can prove that # only Python has access to the C++ object, in which case you can # also prove that no multithreaded access occurs) z = torch.empty(2) z.grad = x del x del y gc.collect() self.assertFalse(m1[0]) self.assertFalse(m2[0]) with disable_gc(): del z self.assertFalse(m1[0]) self.assertFalse(m2[0]) gc.collect() self.assertTrue(m1[0]) self.assertTrue(m2[0]) def test_tensor_cycle_via_slots(self): m1 = [False] m2 = [False] class SlotTensor1(torch._C._TensorBase): __slots__ = ['slot1'] def __del__(self): m1[0] = True class SlotTensor2(SlotTensor1): __slots__ = ['slot2'] def __del__(self): m2[0] = True x = SlotTensor1(torch.empty(2)) y = SlotTensor2(torch.empty(2)) x.slot1 = y y.slot2 = x del x with disable_gc(): del y self.assertFalse(m1[0]) self.assertFalse(m2[0]) gc.collect() self.assertTrue(m1[0]) self.assertTrue(m2[0]) # FIXME: move to test_autograd? def test_backward_hooks_traverse(self): m1, t1 = Tracker.make() m2, t2 = Tracker.make() x = torch.empty(2, requires_grad=True) x._tracker = t1 y = torch.empty(2, requires_grad=True) y._tracker = t2 del t1 del t2 # this hits a special setter, it's not just a __dict__ entry x._backward_hooks = y y._backward_hooks = x del x with disable_gc(): del y self.assertFalse(m1[0]) self.assertFalse(m2[0]) gc.collect() self.assertTrue(m1[0]) self.assertTrue(m2[0]) def test_dead_weak_ref(self): x = torch.empty(2) w_x = weakref.ref(x) y = torch.empty(2) y.grad = x del x x = w_x() # Ideally, x would keep the tensor live. But CPython doesn't # provide enough hooks to do this. So it will go dead and x # will transmute into an undefined tensor. Not great, but the # best we can do. del y self.assertRaises(RuntimeError, lambda: x.sigmoid()) def test_resurrected_weak_ref(self): x = torch.empty(2) w_x = weakref.ref(x) y = torch.empty(2) y.grad = x del x x = w_x() # Use this to manually fix weak references after dereferencing them x._fix_weakref() del y x.sigmoid() # FIXME: move to test_linalg @torch.inference_mode() def test_bmm_multithreaded(self): device = 'cpu' num_threads = torch.get_num_threads() torch.set_num_threads(4) batch_sizes = [1, 10] M, N, O = 23, 8, 12 dtype = torch.float32 numpy_dtype = dtype def invert_perm(p): d = {x: i for i, x in enumerate(p)} return (d[0], d[1], d[2]) def generate_inputs(num_batches): # transposed tensors for perm1, perm2 in itertools.product(itertools.permutations((0, 1, 2)), repeat=2): b1 = make_tensor((num_batches, M, N), dtype=dtype, device=device, low=-1, high=1) b2 = make_tensor((num_batches, N, O), dtype=dtype, device=device, low=-1, high=1) b1 = b1.permute(perm1).contiguous().permute(invert_perm(perm1)) b2 = b2.permute(perm2).contiguous().permute(invert_perm(perm2)) yield b1, b2 # broadcasting tensors for b1, b2, b3, b4, b5, b6 in itertools.product((True, False), repeat=6): shape1 = (num_batches if b1 else 1, M if b2 else 1, N if b3 else 1) shape2 = (num_batches if b4 else 1, N if b5 else 1, O if b6 else 1) b1 = make_tensor(shape1, dtype=dtype, device=device, low=-1, high=1).expand(num_batches, M, N) b2 = make_tensor(shape2, dtype=dtype, device=device, low=-1, high=1).expand(num_batches, N, O) yield b1, b2 # zero-sized tensors for z1, z2, z3, z4 in itertools.product((True, False), repeat=4): shape1 = (num_batches if z1 else 0, M if z2 else 0, N if z3 else 0) shape2 = (num_batches if z1 else 0, N if z3 else 0, O if z4 else 0) b1 = torch.randn(shape1, dtype=dtype, device=device) b2 = torch.randn(shape2, dtype=dtype, device=device) yield b1, b2 try: for num_batches in batch_sizes: for (b1, b2), perm3 in itertools.product(generate_inputs(num_batches), itertools.permutations((0, 1, 2))): res1 = torch.bmm(b1, b2) res2 = torch.full((num_batches, M, O), math.nan, dtype=dtype, device=device) \ .permute(perm3).contiguous().permute(invert_perm(perm3)) torch.bmm(b1, b2, out=res2) expect = torch.from_numpy( b1.to(numpy_dtype).cpu().numpy() @ b2.to(numpy_dtype).cpu().numpy()).to(device=device, dtype=dtype) self.assertEqual(expect, res1) self.assertEqual(expect, res2) finally: torch.set_num_threads(num_threads) def test_conj_neg_tolist(self): x = torch.randn(2, dtype=torch.cfloat) y1 = x.conj() y1_expect = x.conj_physical() y2 = y1.imag self.assertEqual(y1, y1_expect.tolist()) self.assertEqual(y2, y1_expect.imag.tolist()) # The following block extends TestTorch with negative dim wrapping tests # FIXME: replace these with OpInfo sample inputs or systemic OpInfo tests # Functions to test negative dimension wrapping METHOD = 1 INPLACE_METHOD = 2 FUNCTIONAL = 4 DIM_ARG = None def make_neg_dim_test(name, tensor_arg, arg_constr, types, extra_dim=0): def neg_dim_test(self): if isinstance(tensor_arg, list): assert METHOD not in types and INPLACE_METHOD not in types x = [torch.randn(arg) for arg in tensor_arg] ndim = len(tensor_arg[-1]) else: x = torch.randn(*tensor_arg) ndim = len(tensor_arg) ndim += extra_dim n_dim_to_test = sum(e is DIM_ARG for e in arg_constr()) for dims_val in combinations(range(ndim), n_dim_to_test): arg = arg_constr() arg_neg = copy.deepcopy(arg) idx = 0 for i, v in enumerate(arg): if v is DIM_ARG: arg[i] = dims_val[idx] arg_neg[i] = dims_val[idx] - ndim idx += 1 if METHOD in types: a = getattr(x, name)(*arg) b = getattr(x, name)(*arg_neg) self.assertEqual(a, b) if INPLACE_METHOD in types: a = x.clone() getattr(a, name + '_')(*arg) b = x.clone() getattr(b, name + '_')(*arg_neg) self.assertEqual(a, b) if FUNCTIONAL in types: a = getattr(torch, name)(x, *arg) b = getattr(torch, name)(x, *arg_neg) self.assertEqual(a, b) return neg_dim_test def idx_tensor(size, max_val): return torch.LongTensor(*size).random_(0, max_val - 1) def add_neg_dim_tests(): neg_dim_tests = [ ('narrow', (10, 20, 30), lambda: [DIM_ARG, 0, 5], [METHOD]), ('transpose', (10, 20, 30), lambda: [DIM_ARG, DIM_ARG], [METHOD, INPLACE_METHOD, FUNCTIONAL]), ('size', (10, 20, 30), lambda: [DIM_ARG], [METHOD]), ('cat', [(2, 3, 4), (2, 3, 4)], lambda: [DIM_ARG], [FUNCTIONAL]), ('chunk', (10, 20, 30), lambda: [5, DIM_ARG], [METHOD, FUNCTIONAL]), ('gather', (10, 20), lambda: [DIM_ARG, idx_tensor((10, 20), 10)], [METHOD, FUNCTIONAL]), ('index_select', (10, 10), lambda: [DIM_ARG, idx_tensor((10,), 10)], [METHOD, FUNCTIONAL]), ('split', (10, 20), lambda: [5, DIM_ARG], [METHOD, FUNCTIONAL]), ('squeeze', (10, 1, 20, 1), lambda: [DIM_ARG], [METHOD, INPLACE_METHOD, FUNCTIONAL]), ('unbind', (2, 3, 4), lambda: [DIM_ARG], [FUNCTIONAL]), ('unsqueeze', (10, 20), lambda: [DIM_ARG], [METHOD, INPLACE_METHOD, FUNCTIONAL], 1), ('logcumsumexp', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('cumprod', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('cumsum', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('cummax', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('cummin', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('mean', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('median', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('nanmedian', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('mode', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('norm', (10, 20), lambda: [2, DIM_ARG], [METHOD, FUNCTIONAL]), ('prod', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('std', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('sum', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('var', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('kthvalue', (10, 20), lambda: [3, DIM_ARG], [METHOD, FUNCTIONAL]), ('max', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('min', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('sort', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('topk', (10, 20), lambda: [5, DIM_ARG], [METHOD, FUNCTIONAL]), ('renorm', (10, 20), lambda: [2, DIM_ARG, 1], [METHOD, INPLACE_METHOD, FUNCTIONAL]), ('index_add', (10, 10), lambda: [DIM_ARG, idx_tensor((10,), 10), torch.randn(10, 10)], [INPLACE_METHOD]), ('index_copy', (10, 10), lambda: [DIM_ARG, idx_tensor((10,), 10), torch.randn(10, 10)], [INPLACE_METHOD]), ('index_fill', (10, 10), lambda: [DIM_ARG, idx_tensor((10,), 10), 12], [INPLACE_METHOD]), ('scatter', (10, 10), lambda: [DIM_ARG, idx_tensor((10, 10), 10), torch.randn(10, 10)], [INPLACE_METHOD]), ('select', (10, 20), lambda: [DIM_ARG, 3], [METHOD]), ('unfold', (10, 20), lambda: [DIM_ARG, 5, 2], [METHOD]), ] for decl in neg_dim_tests: if len(decl) == 4: name, tensor_arg, arg_constr, types = decl extra_dim = 0 elif len(decl) == 5: name, tensor_arg, arg_constr, types, extra_dim = decl test_name = 'test_' + name + '_neg_dim' assert not hasattr(TestTorch, test_name), "Duplicated test name: " + test_name setattr(TestTorch, test_name, make_neg_dim_test(name, tensor_arg, arg_constr, types, extra_dim)) # TODO: these empy classes are temporarily instantiated for XLA compatibility # once XLA updates their test suite it should be removed class TestViewOps(TestCase): pass class TestTensorDeviceOps(TestCase): pass # Generates tests # Note: test generation must be done at file scope, not within main, or # pytest will fail. add_neg_dim_tests() instantiate_device_type_tests(TestViewOps, globals()) instantiate_device_type_tests(TestVitalSignsCuda, globals()) instantiate_device_type_tests(TestTensorDeviceOps, globals()) instantiate_device_type_tests(TestTorchDeviceType, globals()) instantiate_device_type_tests(TestDevicePrecision, globals(), except_for='cpu') if __name__ == '__main__': run_tests()
# -*- coding: utf-8 -*- # Owner(s): ["module: tests"] import torch import torch.utils.data import numpy as np import contextlib import gc import io import inspect import itertools import math import random import re import copy import os import tempfile import unittest import warnings import types import pickle import textwrap import subprocess import weakref import sys from torch.utils.dlpack import from_dlpack, to_dlpack from torch._six import inf, nan, string_classes from itertools import product, combinations, permutations from functools import partial from torch import multiprocessing as mp from torch.testing import make_tensor from torch.testing._internal.common_utils import ( TestCase, TEST_WITH_ROCM, run_tests, IS_WINDOWS, IS_FILESYSTEM_UTF8_ENCODING, NO_MULTIPROCESSING_SPAWN, IS_SANDCASTLE, IS_FBCODE, IS_REMOTE_GPU, load_tests, slowTest, TEST_WITH_CROSSREF, skipCUDAMemoryLeakCheckIf, BytesIOContext, skipIfRocm, skipIfNoSciPy, TemporaryFileName, TemporaryDirectoryName, wrapDeterministicFlagAPITest, DeterministicGuard, CudaSyncGuard, skipIfNotRegistered, bytes_to_scalar, parametrize, skipIfMps) from multiprocessing.reduction import ForkingPickler from torch.testing._internal.common_device_type import ( expectedFailureMeta, expectedFailureXLA, instantiate_device_type_tests, onlyCUDA, onlyCPU, dtypes, dtypesIfCUDA, dtypesIfCPU, deviceCountAtLeast, skipMeta, PYTORCH_CUDA_MEMCHECK, largeTensorTest, onlyNativeDeviceTypes, expectedAlertNondeterministic, get_all_device_types, skipXLA) from typing import Tuple import torch.backends.quantized import torch.testing._internal.data from torch.testing._internal.common_cuda import ( tf32_on_and_off, tf32_is_not_fp32, TEST_CUDNN) from torch.testing._internal.common_dtype import ( floating_types_and, get_all_math_dtypes, all_types_and_complex_and, complex_types, all_types_and, floating_types, floating_and_complex_types, integral_types, ) # Protects against includes accidentally setting the default dtype assert torch.get_default_dtype() is torch.float32 # load_tests from torch.testing._internal.common_utils is used to automatically filter tests for # sharding on sandcastle. This line silences flake warnings load_tests = load_tests AMPERE_OR_ROCM = TEST_WITH_ROCM or tf32_is_not_fp32() @contextlib.contextmanager def torch_vital_set(value): stash = None if 'TORCH_VITAL' in os.environ: stash = os.environ['TORCH_VITAL'] os.environ['TORCH_VITAL'] = value try: yield finally: if stash: os.environ['TORCH_VITAL'] = stash else: del os.environ['TORCH_VITAL'] # Tests Vital Signs for Torch # FIXME: document or deprecate whatever this is class TestBasicVitalSigns(TestCase): def test_basic_vitals(self): with torch_vital_set(''): self.assertFalse(torch.vitals_enabled()) with torch_vital_set('ON'): self.assertTrue(torch.vitals_enabled()) def test_basic_vitals_read_write(self): with torch_vital_set('ON'): self.assertTrue(torch.vitals_enabled()) # This tests the code path of setting a vital self.assertTrue(torch.set_vital('Dataloader', 'basic_unit_test', 'TEST_VALUE_STRING')) self.assertIn('TEST_VALUE_STRING', torch.read_vitals()) self.assertIn('CUDA.used', torch.read_vitals()) def test_dataloader_vitals(self): with torch_vital_set('ON'): inps = torch.arange(10 * 5, dtype=torch.float32).view(10, 5) tgts = torch.arange(10 * 5, dtype=torch.float32).view(10, 5) dataset = torch.utils.data.TensorDataset(inps, tgts) loader = torch.utils.data.DataLoader(dataset, batch_size=2) self.assertIn('Dataloader.enabled\t\t True', torch.read_vitals()) # FIXME: document or deprecate whatever this is class TestVitalSignsCuda(TestCase): @onlyCUDA def test_cuda_vitals_gpu_only(self, device): with torch_vital_set('ON'): self.assertIn('CUDA.used\t\t true', torch.read_vitals()) class TestTorchDeviceType(TestCase): exact_dtype = True # TODO: move all tensor creation to common ops def _rand_shape(self, dim, min_size, max_size): shape = [] for i in range(dim): shape.append(random.randint(min_size, max_size)) return tuple(shape) # Validates that mathematical constants are defined properly, as required by # the Python Array API (https://data-apis.org/array-api/latest/API_specification/constants.html) @onlyCPU def test_constants(self, device): self.assertIsInstance(torch.e, float) self.assertEqual(torch.e, math.e, atol=0, rtol=0) self.assertIsInstance(torch.pi, float) self.assertEqual(torch.pi, math.pi, atol=0, rtol=0) self.assertIsInstance(torch.nan, float) self.assertEqual(torch.nan, math.nan, equal_nan=True) self.assertIsInstance(torch.inf, float) self.assertEqual(torch.inf, math.inf) @onlyNativeDeviceTypes @dtypes(torch.int8, torch.uint8, torch.int16, torch.int32, torch.int64, torch.bool, torch.float32, torch.complex64, torch.float64, torch.complex128) def test_bytes_to_scalar(self, device, dtype): def rand_byte(): if dtype == torch.bool: return torch.randint(0, 2, ()).item() else: return torch.randint(0, 256, ()).item() element_size = torch._utils._element_size(dtype) for i in range(10): bytes_list = [rand_byte() for _ in range(element_size)] scalar = bytes_to_scalar(bytes_list, dtype, device) self.assertEqual(scalar.storage()._untyped().tolist(), bytes_list) @dtypes(torch.int8, torch.uint8, torch.int16, torch.int32, torch.int64, torch.bool, torch.float32, torch.complex64, torch.float64, torch.complex128) def test_storage(self, device, dtype): v = make_tensor((3, 5), dtype=dtype, device=device, low=-9, high=9) self.assertEqual(v.storage()[0], v[0][0]) self.assertEqual(v.storage()[14], v[2][4]) v_s = v.storage() for el_num in range(v.numel()): dim0 = el_num // v.size(1) dim1 = el_num % v.size(1) self.assertEqual( v_s[el_num], v[dim0][dim1]) v_s_byte = v.storage()._untyped() el_size = v.element_size() for el_num in range(v.numel()): start = el_num * el_size end = start + el_size dim0 = el_num // v.size(1) dim1 = el_num % v.size(1) self.assertEqual( bytes_to_scalar(v_s_byte[start:end], dtype, device), v[dim0][dim1]) @onlyNativeDeviceTypes @dtypes(torch.int8, torch.uint8, torch.int16, torch.int32, torch.int64, torch.bool, torch.float32, torch.complex64, torch.float64, torch.complex128, torch.quint8, torch.qint8, torch.qint32, torch.quint4x2) def test_storage_setitem(self, device, dtype): # Skip quantized dtypes for CUDA, since they're not supported if torch.device(device).type == 'cuda': if dtype in [torch.quint8, torch.qint8, torch.qint32, torch.quint4x2]: return storage_type_name = torch.storage._dtype_to_storage_type_map()[dtype] if torch.device(device).type == 'cuda': storage_type = eval('torch.cuda.' + storage_type_name) else: storage_type = eval('torch.' + storage_type_name) N = 10 s = storage_type(N) s[:] = 0 l = [0] * N self.assertEqual(s, storage_type(l)) for i in range(N): s[i] = i l[i] = i self.assertEqual(s, storage_type(l)) l[2:7] = [1] * 5 s[2:7] = 1 self.assertEqual(s, storage_type(l)) @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) def test_tensor_storage_type(self, device, dtype): a = make_tensor((10,), dtype=dtype, device=device, low=-9, high=9) module = torch.cuda if (torch.device(device).type == 'cuda') else torch expected_storage_type = getattr(module, torch.storage._dtype_to_storage_type_map()[dtype]) self.assertEqual(a.storage_type(), expected_storage_type) @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) def test_tensor_from_storage(self, device, dtype): a = make_tensor((4, 5, 3), dtype=dtype, device=device, low=-9, high=9) a_s = a.storage() b = torch.tensor(a_s, device=device, dtype=dtype).reshape(a.size()) self.assertEqual(a, b) c = torch.tensor(a_s._untyped(), device=device, dtype=dtype).reshape(a.size()) self.assertEqual(a, c) for error_dtype in all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16): if error_dtype == dtype: continue with self.assertRaisesRegex(RuntimeError, r'Expected a Storage of type'): error_storage = a.to(error_dtype).storage() torch.tensor(error_storage, device=device, dtype=dtype) @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) def test_set_storage(self, device, dtype): a = make_tensor((4, 5, 3), dtype=dtype, device=device, low=-9, high=9) a_s = a.storage() b = torch.tensor([], device=device, dtype=dtype).set_(a_s).reshape(a.size()) self.assertEqual(a, b) c = torch.tensor([], device=device, dtype=dtype).set_(a_s._untyped()).reshape(a.size()) self.assertEqual(a, c) for error_dtype in all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16): if error_dtype == dtype: continue with self.assertRaisesRegex(RuntimeError, r'Expected a Storage of type'): error_storage = a.to(error_dtype).storage() b = torch.tensor([], device=device, dtype=dtype).set_(error_storage) def _check_storage_meta(self, s, s_check): self.assertTrue( isinstance(s, (torch._UntypedStorage, torch._TypedStorage)) and isinstance(s_check, type(s)), ( 's and s_check must both be one of _UntypedStorage or ' '_TypedStorage, but got' f' {type(s).__name__} and {type(s_check).__name__}')) self.assertEqual(s.device.type, 'meta') self.assertEqual(s.nbytes(), s_check.nbytes()) self.assertEqual(s.size(), s_check.size()) self.assertEqual(s.data_ptr(), 0) with self.assertRaisesRegex(NotImplementedError, r'Not available'): s[0] if isinstance(s, torch._TypedStorage): self.assertEqual(s.dtype, s_check.dtype) self._check_storage_meta(s._untyped(), s_check._untyped()) @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) def test_typed_storage_meta(self, device, dtype): args_list = [ [], [0], [100], [[1, 2, 3, 4, 5, 6]], ] for args in args_list: s_check = torch._TypedStorage(*args, dtype=dtype, device=device) s = torch._TypedStorage(*args, dtype=dtype, device='meta') self._check_storage_meta(s, s_check) @onlyNativeDeviceTypes def test_untyped_storage_meta(self, device): args_list = [ [], [0], [100], [[1, 2, 3, 4, 5, 6]], ] for args in args_list: s_check = torch._UntypedStorage(*args, device=device) s = torch._UntypedStorage(*args, device='meta') self._check_storage_meta(s, s_check) @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) def test_storage_meta_from_tensor(self, device, dtype): t_check = make_tensor((4, 5, 3), dtype=dtype, device=device, low=-9, high=9) t = t_check.to('meta') s_check = t_check.storage() s = t.storage() self._check_storage_meta(s, s_check) @onlyCPU @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) def test_storage_meta_errors(self, device, dtype): s0 = torch._TypedStorage([1, 2, 3, 4], device='meta', dtype=dtype) with self.assertRaisesRegex(NotImplementedError, r'Cannot copy out'): s0.cpu() with self.assertRaisesRegex(RuntimeError, r'only available on CPU'): s0._share_fd_cpu_() with self.assertRaisesRegex(RuntimeError, r'only available on CPU'): s0._share_filename_cpu_() if torch.cuda.is_available(): with self.assertRaisesRegex(NotImplementedError, r'Cannot copy out'): s0.cuda() with self.assertRaisesRegex(RuntimeError, r'only available on CUDA'): s0._share_cuda_() with self.assertRaisesRegex(NotImplementedError, r'Cannot copy out'): s0.pin_memory() with self.assertRaisesRegex(RuntimeError, r'got unexpected device type'): s0.resize_(10) with self.assertRaisesRegex(RuntimeError, r'only available on CPU'): s0.share_memory_() with self.assertRaisesRegex(NotImplementedError, r'Not available'): s0.tolist() with tempfile.NamedTemporaryFile() as f: with self.assertRaisesRegex(RuntimeError, r'Device not recognized'): s0._write_file(f, True, True, s0.element_size()) for device in ['cpu', 'cuda'] if torch.cuda.is_available() else ['cpu']: s1 = torch._TypedStorage([1, 2, 3, 4], device=device, dtype=dtype) with self.assertRaisesRegex(NotImplementedError, r'Cannot copy out'): s1.copy_(s0) @dtypes(torch.float32, torch.complex64) def test_deepcopy(self, device, dtype): from copy import deepcopy a = torch.randn(5, 5, dtype=dtype, device=device) b = torch.randn(5, 5, dtype=dtype, device=device) c = a.view(25) q = [a, [a.storage(), b.storage()], b, c] w = deepcopy(q) self.assertEqual(w[0], q[0], atol=0, rtol=0) self.assertEqual(w[1][0], q[1][0], atol=0, rtol=0) self.assertEqual(w[1][1], q[1][1], atol=0, rtol=0) self.assertEqual(w[1], q[1], atol=0, rtol=0) self.assertEqual(w[2], q[2], atol=0, rtol=0) # Check that deepcopy preserves sharing w[0].add_(1) for i in range(a.numel()): self.assertEqual(w[1][0][i], q[1][0][i] + 1) self.assertEqual(w[3], c + 1) w[2].sub_(1) for i in range(a.numel()): self.assertEqual(w[1][1][i], q[1][1][i] - 1) # Check that deepcopy preserves attributes a.foo = 3 self.assertEqual(deepcopy(a).foo, 3) @dtypes(torch.float32, torch.complex64) def test_deepcopy_scalar(self, device, dtype): from copy import deepcopy a = torch.tensor(5, dtype=dtype, device=device) self.assertEqual(a.size(), deepcopy(a).size()) self.assertEqual(a, deepcopy(a)) def check_internal_mem_overlap(self, inplace_op, num_inputs, dtype, device, expected_failure=False): if isinstance(inplace_op, str): inplace_op = getattr(torch.Tensor, inplace_op) input = torch.randn(1, dtype=dtype, device=device).expand(3, 3) inputs = [input] + [torch.randn_like(input) for i in range(num_inputs - 1)] if not expected_failure: with self.assertRaisesRegex(RuntimeError, 'single memory location'): inplace_op(*inputs) else: with self.assertRaises(AssertionError): with self.assertRaisesRegex(RuntimeError, 'single memory location'): inplace_op(*inputs) def unary_check_input_output_mem_overlap(self, data, sz, op, expected_failure=False): def _test(op, output, input): output_exp = torch.empty_like(output) op(input, out=output_exp) self.assertEqual(op(input, out=output), output_exp, msg=op.__name__) # output is identical to input: _test(op, output=data[0:sz], input=data[0:sz]) # output and input are independent: _test(op, output=data[0:sz], input=data[sz:2 * sz]) # output partially overlaps with input: if not expected_failure: with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): _test(op, data[0:sz], data[1:sz + 1]) else: with self.assertRaises(AssertionError): with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): _test(op, data[0:sz], data[1:sz + 1]) # output is transpose of input: length = int(math.sqrt(sz)) input = data[:length**2].view([length, length]) out = input.t() if not expected_failure: with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): _test(op, out, input) else: with self.assertRaises(AssertionError): with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): _test(op, out, input) def ternary_check_input_output_mem_overlap(self, op, device, expected_failure=False): sz = 9 data = torch.randn(2 * sz, device=device) other1 = torch.randn(sz, device=device) other2 = torch.randn(sz, device=device) self.unary_check_input_output_mem_overlap( data, sz, lambda input, out: op(input, other1.view(input.shape), other2.view(input.shape), out=out), expected_failure=expected_failure) self.unary_check_input_output_mem_overlap( data, sz, lambda input, out: op(other1.view(input.shape), input, other2.view(input.shape), out=out), expected_failure=expected_failure) self.unary_check_input_output_mem_overlap( data, sz, lambda input, out: op(other1.view(input.shape), other2.view(input.shape), input, out=out), expected_failure=expected_failure) def _select_broadcastable_dims(self, dims_full=None): # select full dimensionality if dims_full is None: dims_full = [] ndims = random.randint(1, 4) dims_full = [random.randint(1, 8) for _ in range(ndims)] else: ndims = len(dims_full) # select actual dimensions for ops: # larger: full ndims, individual sizes may be reduced # smaller: possibly reduced ndims, sizes may be reduced smaller_ndims = random.randint(1, ndims) dims_small = [] dims_large = [] for i in range(ndims - 1, -1, -1): j = random.randint(1, 3) if j == 1: # no reduced singleton dimension ds = dims_full[i] dl = dims_full[i] elif j == 2: # larger may have reduced singleton dimension ds = dims_full[i] dl = 1 if len(dims_small) < smaller_ndims else dims_full[i] elif j == 3: # smaller may have reduced singleton dimension ds = 1 dl = dims_full[i] dims_large = [dl] + dims_large if len(dims_small) < smaller_ndims: dims_small = [ds] + dims_small return (dims_small, dims_large, dims_full) # collected tests of ops that used scalar_check in Declarations.cwrap for # correctness def test_scalar_check(self, device): zero_d = torch.randn((), device=device) one_d = torch.randn((1,), device=device) # remainder self.assertEqual((), torch.remainder(zero_d, zero_d).shape) self.assertEqual((), torch.remainder(zero_d, 2).shape) self.assertEqual((1,), torch.remainder(zero_d, one_d).shape) self.assertEqual((1,), torch.remainder(one_d, zero_d).shape) # fmod self.assertEqual((), torch.fmod(zero_d, zero_d).shape) self.assertEqual((), torch.fmod(zero_d, 2).shape) self.assertEqual((1,), torch.fmod(zero_d, one_d).shape) self.assertEqual((1,), torch.fmod(one_d, zero_d).shape) # exp, cos, cosh, tan, atan, tanh, erf, erfc, reciprocal self.assertEqual((), torch.exp(zero_d).shape) self.assertEqual((), torch.cos(zero_d).shape) self.assertEqual((), torch.cosh(zero_d).shape) self.assertEqual((), torch.tan(zero_d).shape) self.assertEqual((), torch.atan(zero_d).shape) self.assertEqual((), torch.acosh(zero_d).shape) self.assertEqual((), torch.asinh(zero_d).shape) self.assertEqual((), torch.atanh(zero_d).shape) self.assertEqual((), torch.tanh(zero_d).shape) self.assertEqual((), torch.erf(zero_d).shape) self.assertEqual((), torch.erfc(zero_d).shape) self.assertEqual((), torch.reciprocal(zero_d).shape) self.assertEqual((1,), torch.exp(one_d).shape) self.assertEqual((1,), torch.cos(one_d).shape) self.assertEqual((1,), torch.cosh(one_d).shape) self.assertEqual((1,), torch.tan(one_d).shape) self.assertEqual((1,), torch.atan(one_d).shape) self.assertEqual((1,), torch.acosh(one_d).shape) self.assertEqual((1,), torch.asinh(one_d).shape) self.assertEqual((1,), torch.atanh(one_d).shape) self.assertEqual((1,), torch.tanh(one_d).shape) self.assertEqual((1,), torch.erf(one_d).shape) self.assertEqual((1,), torch.erfc(one_d).shape) self.assertEqual((1,), torch.reciprocal(one_d).shape) # clamp self.assertEqual((), torch.clamp(zero_d, min=0, max=1).shape) self.assertEqual((), torch.clamp(zero_d, min=0).shape) self.assertEqual((), torch.clamp(zero_d, max=1).shape) self.assertEqual((1,), torch.clamp(one_d, min=0, max=1).shape) self.assertEqual((1,), torch.clamp(one_d, min=0).shape) self.assertEqual((1,), torch.clamp(one_d, max=1).shape) # cumsum, cumprod, cummax, cummin self.assertEqual((), torch.logcumsumexp(zero_d, 0).shape) self.assertEqual((), torch.cumsum(zero_d, 0).shape) self.assertEqual((), torch.cumprod(zero_d, 0).shape) self.assertEqual((), torch.cummax(zero_d, 0)[0].shape) self.assertEqual((), torch.cummin(zero_d, 0)[0].shape) # sort, topk self.assertEqual([(), ()], [x.shape for x in torch.sort(zero_d, 0, False)]) self.assertEqual([(), ()], [x.shape for x in torch.sort(zero_d, 0, True)]) self.assertEqual([(), ()], [x.shape for x in torch.topk(zero_d, 1, 0, False)]) self.assertEqual([(), ()], [x.shape for x in torch.topk(zero_d, 1, 0, True)]) # max, min self.assertEqual((), torch.max(zero_d, zero_d).shape) self.assertEqual((1,), torch.max(one_d, zero_d).shape) self.assertEqual((1,), torch.max(zero_d, one_d).shape) self.assertEqual((), torch.min(zero_d, zero_d).shape) self.assertEqual((1,), torch.min(one_d, zero_d).shape) self.assertEqual((1,), torch.min(zero_d, one_d).shape) zero_d_int = torch.tensor(1, device=device) one_d_int = torch.tensor([1], device=device) # lshift, rshift self.assertEqual((), (zero_d_int >> zero_d_int).shape) self.assertEqual((), (zero_d_int >> 1).shape) self.assertEqual((1,), (one_d_int >> zero_d_int).shape) self.assertEqual((1,), (zero_d_int >> one_d_int).shape) self.assertEqual((1,), (one_d_int >> 1).shape) self.assertEqual((), (zero_d_int << zero_d_int).shape) self.assertEqual((), (zero_d_int << 1).shape) self.assertEqual((1,), (one_d_int << zero_d_int).shape) self.assertEqual((1,), (zero_d_int << one_d_int).shape) self.assertEqual((1,), (one_d_int << 1).shape) # or self.assertEqual((), (zero_d_int | zero_d_int).shape) self.assertEqual((), (zero_d_int | 1).shape) self.assertEqual((1,), (one_d_int | zero_d_int).shape) self.assertEqual((1,), (zero_d_int | one_d_int).shape) self.assertEqual((1,), (one_d_int | 1).shape) # and self.assertEqual((), (zero_d_int & zero_d_int).shape) self.assertEqual((), (zero_d_int & 1).shape) self.assertEqual((1,), (one_d_int & zero_d_int).shape) self.assertEqual((1,), (zero_d_int & one_d_int).shape) self.assertEqual((1,), (one_d_int & 1).shape) # clone self.assertEqual((), zero_d.clone().shape) zero_d_bool = torch.tensor(True, device=device) one_d_bool = torch.tensor([True], device=device) # masked_select self.assertEqual((1,), torch.masked_select(zero_d_bool, zero_d_bool).shape) self.assertEqual((1,), torch.masked_select(zero_d_bool, one_d_bool).shape) self.assertEqual((1,), torch.masked_select(one_d_bool, zero_d_bool).shape) zero_d_uint8 = torch.tensor(1, dtype=torch.uint8, device=device) one_d_uint8 = torch.tensor([1], dtype=torch.uint8, device=device) with warnings.catch_warnings(): warnings.simplefilter("ignore") self.assertEqual((1,), torch.masked_select(zero_d_uint8, zero_d_uint8).shape) self.assertEqual((1,), torch.masked_select(zero_d_uint8, one_d_uint8).shape) self.assertEqual((1,), torch.masked_select(one_d_uint8, zero_d_uint8).shape) # mode self.assertEqual([(), ()], [x.shape for x in torch.mode(zero_d, dim=0, keepdim=True)]) self.assertEqual([(), ()], [x.shape for x in torch.mode(zero_d, dim=0, keepdim=False)]) self.assertEqual([(1,), (1,)], [x.shape for x in torch.mode(one_d, dim=0, keepdim=True)]) self.assertEqual([(), ()], [x.shape for x in torch.mode(one_d, dim=0, keepdim=False)]) # max self.assertEqual([(), ()], [x.shape for x in torch.max(zero_d, dim=0, keepdim=True)]) self.assertEqual([(), ()], [x.shape for x in torch.max(zero_d, dim=0, keepdim=False)]) self.assertEqual([(1,), (1,)], [x.shape for x in torch.max(one_d, dim=0, keepdim=True)]) self.assertEqual([(), ()], [x.shape for x in torch.max(one_d, dim=0, keepdim=False)]) # amax self.assertEqual((), torch.amax(zero_d, dim=0, keepdim=True).shape) self.assertEqual((), torch.amax(zero_d, dim=0, keepdim=False).shape) self.assertEqual((1,), torch.amax(one_d, dim=0, keepdim=True).shape) self.assertEqual((), torch.amax(one_d, dim=0, keepdim=False).shape) # min self.assertEqual([(), ()], [x.shape for x in torch.min(zero_d, dim=0, keepdim=True)]) self.assertEqual([(), ()], [x.shape for x in torch.min(zero_d, dim=0, keepdim=False)]) self.assertEqual([(1,), (1,)], [x.shape for x in torch.min(one_d, dim=0, keepdim=True)]) self.assertEqual([(), ()], [x.shape for x in torch.min(one_d, dim=0, keepdim=False)]) # amin self.assertEqual((), torch.amin(zero_d, dim=0, keepdim=True).shape) self.assertEqual((), torch.amin(zero_d, dim=0, keepdim=False).shape) self.assertEqual((1,), torch.amin(one_d, dim=0, keepdim=True).shape) self.assertEqual((), torch.amin(one_d, dim=0, keepdim=False).shape) # set_ zero_d_clone = zero_d.clone() one_d_clone = one_d.clone() self.assertEqual((), zero_d_clone.set_(one_d.storage(), 0, (), ()).shape) self.assertEqual((1,), zero_d_clone.set_(one_d.storage(), 0, (1,), (1,)).shape) self.assertEqual((), one_d_clone.set_(one_d.storage(), 0, (), ()).shape) self.assertEqual((1,), one_d_clone.set_(one_d.storage(), 0, (1,), (1,)).shape) self.assertEqual((), zero_d.clone().set_(zero_d).shape) self.assertEqual((), one_d.clone().set_(zero_d).shape) self.assertEqual((1,), zero_d.clone().set_(one_d).shape) self.assertEqual((1,), one_d.clone().set_(one_d).shape) # take self.assertEqual((), torch.randn((2, 3), device=device).take(zero_d_int).shape) self.assertEqual((1,), torch.randn((2, 3), device=device).take(one_d_int).shape) # gather self.assertEqual((), torch.gather(zero_d, 0, torch.zeros((), dtype=torch.int64, device=device)).shape) self.assertEqual((1,), torch.gather(zero_d, 0, torch.zeros((1,), dtype=torch.int64, device=device)).shape) self.assertEqual((), torch.gather(one_d, 0, torch.zeros((), dtype=torch.int64, device=device)).shape) self.assertEqual((1,), torch.gather(one_d, 0, torch.zeros((1,), dtype=torch.int64, device=device)).shape) # normal # std must be >= 0 zero_d_ge_0 = torch.rand((), device=device) # documentation says out shape matches shape of mean self.assertEqual((), torch.normal(zero_d, zero_d_ge_0).shape) self.assertEqual((1,), torch.normal(one_d, zero_d_ge_0).shape) self.assertEqual((), torch.normal(1, zero_d_ge_0).shape) self.assertEqual((), torch.normal(zero_d, 1).shape) self.assertEqual((1,), torch.normal(one_d, 1).shape) # TODO: this behavior differs on CPU and GPU, see https://github.com/pytorch/pytorch/issues/30480. # self.assertEqual((), torch.normal(zero_d, one_d).shape) # self.assertEqual((), torch.normal(1, one_d).shape) # convolutions. Yes, we are testing nn.functional here; seems justified # given its similar to the other tests w = torch.randn(2, 1, 3, 3, device=device).div_(2).requires_grad_() self.assertRaises(RuntimeError, lambda: torch.nn.functional.conv2d(zero_d, w, groups=1)) self.assertRaises(RuntimeError, lambda: torch.nn.functional.conv2d(zero_d, w, groups=2)) # nll_loss -- verify input can't be 0-dimensional. self.assertRaises(ValueError, lambda: torch.nn.functional.nll_loss(zero_d, zero_d, reduction='none')) self.assertRaises(ValueError, lambda: torch.nn.functional.nll_loss(zero_d, one_d, reduction='none')) # verify output is 0-dimensional when reduction != 'none' for (input, target) in ((torch.randn(1, 1, device=device), torch.tensor([0], device=device)), (torch.randn(1, 1, 1, 1, device=device), torch.tensor([[[0]]], device=device))): self.assertEqual((), torch.nn.functional.nll_loss(input, target, reduction='mean').shape) self.assertEqual((), torch.nn.functional.nll_loss(input, target, reduction='sum').shape) # multilabel_margin_loss for input in (zero_d, one_d, torch.randn(1, 1, device=device)): for target in (torch.tensor(0, device=device), torch.tensor([0], device=device), torch.tensor([[0]], device=device)): if (input.dim() <= 1 and target.dim() <= 1) or (input.dim() == 2 and target.dim() == 2): output_shape = (target.shape[0],) if target.dim() == 2 else () self.assertEqual(output_shape, torch.nn.functional.multilabel_margin_loss(input, target, reduction='none').shape) self.assertEqual((), torch.nn.functional.multilabel_margin_loss(input, target, reduction='mean').shape) self.assertEqual((), torch.nn.functional.multilabel_margin_loss(input, target, reduction='sum').shape) else: self.assertRaises(RuntimeError, lambda: torch.nn.functional.multilabel_margin_loss(input, target, reduction='none')) self.assertRaises(RuntimeError, lambda: torch.nn.functional.multilabel_margin_loss(input, target, reduction='mean')) self.assertRaises(RuntimeError, lambda: torch.nn.functional.multilabel_margin_loss(input, target, reduction='sum')) # multi_margin_loss for input in (zero_d, one_d, torch.randn(1, 1, device=device)): for target in (torch.tensor(0, device=device), torch.tensor([0], device=device)): self.assertEqual(target.shape, torch.nn.functional.multi_margin_loss(input, target, reduction='none').shape) self.assertEqual((), torch.nn.functional.multi_margin_loss(input, target, reduction='mean').shape) self.assertEqual((), torch.nn.functional.multi_margin_loss(input, target, reduction='sum').shape) # Uses mismatched arange out size to trigger a warning @unittest.skipIf(TEST_WITH_CROSSREF, "crossref perturbs line numbering") def test_cpp_warnings_have_python_context(self, device): # Creates long string in advance to avoid a too-long Python line s = ".+Triggered internally at.+RangeFactories.+" def cpp_warn_fn(): out = torch.empty((5,)) torch.arange(0, 3, out=out) return out # Checks eager-mode cpp warning with warnings.catch_warnings(record=True) as w: cpp_warn_fn() frameinfo = inspect.getframeinfo(inspect.currentframe()) warning = w[0] # Checks for cpp context in the warning message escaped_warning_message = str(warning.message).encode('unicode_escape') self.assertTrue(re.search(s, str(escaped_warning_message), re.IGNORECASE) is not None) # Checks the Python features of the warning # Note: the eager mode warning refers to the line in the function # that throws the warning. self.assertEqual(frameinfo.lineno - 6, warning.lineno) self.assertEqual(len(w), 1) # Checks jitted cpp warning with warnings.catch_warnings(record=True) as w: scripted_cpp_warn_fn = torch.jit.script(cpp_warn_fn) scripted_cpp_warn_fn() warning = w[0] # Checks for cpp context in the warning message escaped_warning_message = str(warning.message).encode('unicode_escape') self.assertTrue(re.search(s, str(escaped_warning_message), re.IGNORECASE) is not None) # Checks the Python features of the warning # Note: the jitted warning's lineno refers to the call to the jitted # function, which in our test suite has a layer of indirection # that makes checking the Python lineno fragile self.assertEqual(len(w), 1) # Checks jitted Python warning def warn_fn(): warnings.warn("Warning!") # The jit mimics an eager-mode Python warning in this case with warnings.catch_warnings(record=True) as w: scripted_warn_fn = torch.jit.script(warn_fn) scripted_warn_fn() frameinfo = inspect.getframeinfo(inspect.currentframe()) warning = w[0] self.assertTrue(re.search('Warning!', str(warning.message)) is not None) # Checks the Python features of the warning self.assertEqual(frameinfo.lineno - 6, warning.lineno) self.assertEqual(len(w), 1) # FIXME: move to test_testing @onlyCPU def test_warn_always_caught(self, device): # Check that we can catch a TORCH_WARN_ONCE warning twice # since assertWarnsOnceRegex uses set_warn_always(True) which changes # TORCH_WARN_ONCE to TORCH_WARN a = np.arange(10) a.flags.writeable = False with self.assertWarnsOnceRegex(UserWarning, '.*non-writable.*'): torch.from_numpy(a) # OK, got it once, now try again with self.assertWarnsOnceRegex(UserWarning, '.*non-writable.*'): torch.from_numpy(a) # Make sure emitting two warnings will pass the assertWarnsOnceRegex # context manager with self.assertWarnsOnceRegex(UserWarning, '.*non-writable.*'): torch.from_numpy(a) torch.from_numpy(a) # TODO: this test should be in test_nn.py def test_conv_transposed_backward_agnostic_to_memory_format(self, device): in_channels = 64 out_channels = 128 scale_factor = 8 batch_size = 8 length = 16 conv = torch.nn.ConvTranspose1d( in_channels, out_channels, kernel_size=scale_factor * 2, stride=scale_factor).to(device) layer_norm = torch.nn.LayerNorm(out_channels).to(device) input_ = torch.randn(batch_size, in_channels, length).to(device).contiguous() input_ = conv(input_).contiguous() input_ = layer_norm(input_.transpose(1, 2).contiguous()).contiguous() input_.sum().backward() # 3d conv = torch.nn.ConvTranspose3d(3, 3, kernel_size=3).to(device) input = torch.randn(batch_size, 3, length, length, length, device=device) out = conv(input) out.backward(torch.ones_like(out).transpose(-2, -1)) # TODO: this test should be in test_nn.py @onlyCUDA @largeTensorTest('12GB') def test_conv_transposed_large(self, device): # ConvTranspose3d works for large input tensors (gh-32866) in_channels = 64 out_channels = 128 kernel_size = 5 conv = torch.nn.ConvTranspose3d( in_channels, out_channels, kernel_size=kernel_size, stride=2, padding=2, output_padding=1).to(device) x = torch.rand([1, 64, 8, 128, 172]).to(device) y = conv(x) def test_is_set_to(self, device): t1 = torch.empty(3, 4, 9, 10, device=device) t2 = torch.empty(3, 4, 9, 10, device=device) t3 = torch.tensor([], device=device).set_(t1) t4 = t3.clone().resize_(12, 90) self.assertFalse(t1.is_set_to(t2)) self.assertTrue(t1.is_set_to(t3)) self.assertTrue(t3.is_set_to(t1), "is_set_to should be symmetric") self.assertFalse(t1.is_set_to(t4)) self.assertFalse(torch.tensor([]).is_set_to(torch.tensor([])), "Tensors with no storages should not appear to be set " "to each other") t1 = torch.tensor([True, True], dtype=torch.bool, device=device) t2 = torch.tensor([0], dtype=torch.bool, device=device).set_(t1) self.assertTrue(t1.is_set_to(t2)) # test that sizes must match t1 = torch.empty([2, 3, 4], device=device) t2 = t1.view(4, 3, 2) self.assertFalse(t1.is_set_to(t2)) self.assertFalse(t2.is_set_to(t1)) # test that legacy empty size behavior used to be respected (i.e. all # empty tensors were logically collapsed to size [0]). t1 = torch.empty([2, 5, 0], device=device) t2 = t1.view([0]) self.assertFalse(t1.is_set_to(t2)) self.assertFalse(t2.is_set_to(t1)) # See https://github.com/pytorch/pytorch/issues/72650 @skipIfMps @skipMeta @parametrize( "fn", [ "dist", "atan2", "pow", "lerp", "add", "sub", "mul", "div", "fmod", "remainder", "eq", "ge", "gt", "le", "lt", "max", "min", "ne", "addcdiv", "addcmul", "masked_scatter", "masked_select", "masked_fill", "map", "map2", "copy", ], ) def test_broadcast(self, fn, device): # functions with three tensor arguments fns_3_args = {"map2"} fns_value_kwarg = {"addcdiv", "addcmul"} (dims_small, dims_large, dims_full) = self._select_broadcastable_dims() full1d = torch.randn(*dims_full, device=device).flatten().float() small = torch.randn(*dims_small, device=device).float() large = torch.randn(*dims_large, device=device).float() small_expanded = small.expand(*dims_full) large_expanded = large.expand(*dims_full) small2 = None small2_expanded = None if fn in fns_3_args or fn in fns_value_kwarg: # create another smaller tensor (dims_small2, _, _) = self._select_broadcastable_dims(dims_full) small2 = torch.randn(*dims_small2, device=device).float() small2_expanded = small2.expand(*dims_full) if small.is_cuda and fn in ['map', 'map2']: # map and map2 are not implementd on CUDA tensors return if hasattr(large_expanded, fn): # run through tensor versions of functions # and verify fully expanded inputs give same results expanded = {large: large_expanded, small: small_expanded, small2: small2_expanded} def tensorfn(myfn, t1, t2): if fn == "lerp": return myfn(t1, 0.5) elif fn == "masked_select": return myfn(t1 < 0) elif fn == "masked_scatter": return myfn(t1 < 0.5, full1d) elif fn == "masked_fill": return myfn(t1 < 0.5, 1.0) elif fn in fns_3_args: return myfn(1, t1, t2) elif fn in fns_value_kwarg: return myfn(t1, t2, value=1) else: return myfn(t1) # test various orders for first, second, third in [(large, small, small2), (small, large, small2), (small2, small, large), (small2, large, small)]: if first is None: break # ignore last iter when small2 is None method_expanded = getattr(expanded[first], fn) method = getattr(first, fn) r1 = tensorfn(method_expanded, expanded[second], expanded[third]) r2 = tensorfn(method, second, third) self.assertEqual(r1, r2) # now for torch. versions of functions if hasattr(torch, fn): fntorch = getattr(torch, fn) expanded = {large: large_expanded, small: small_expanded, small2: small2_expanded} def torchfn(t1, t2, t3): if fn == "lerp": return fntorch(t1, t2, 0.5) elif fn == "masked_select": return fntorch(t1, t2 < 0) elif fn == "masked_scatter": return fntorch(t1, t2 < 0.5, full1d) elif fn == "masked_fill": return fntorch(t1, t2 < 0.5, 1.0) elif fn in fns_3_args: return fntorch(t1, 1.0, t2, t3) elif fn in fns_value_kwarg: return fntorch(t1, t2, t3, value=1.0) else: return fntorch(t1, t2) # test various orders for first, second, third in [(large, small, small2), (small, large, small2), (small2, small, large), (small2, large, small)]: if first is None: break # ignore last iter when small2 is None r1 = torchfn(expanded[first], expanded[second], expanded[third]) r2 = torchfn(first, second, third) self.assertEqual(r1, r2) # now for in place functions # in-place tensor is not broadcastable; test only guaranteed # to work by broadcasting other argument(s) if not hasattr(large_expanded, fn + "_"): return # need to clone largeExpanded so we can reuse, since functions are in-place large_expanded_clone = large_expanded.clone() def tensorfn_inplace(t0, t1, t2=None): t0_fn = getattr(t0, fn + "_") if fn == "lerp": return t0_fn(t1, 0.5) elif fn == "masked_scatter": return t0_fn(t1 < 0.5, full1d) elif fn == "masked_fill": return t0_fn(t1 < 0.5, 1.0) elif fn == "map": return t0_fn(t1, lambda x, y: x + y) elif fn == "map2": return t0_fn(t1, t2, lambda x, y, z: x + y + z) elif fn in fns_3_args: return t0_fn(1.0, t1, t2) elif fn in fns_value_kwarg: return t0_fn(t1, t2, value=1.0) else: return t0_fn(t1) # in-place pointwise operations don't actually work if the in-place # tensor is 0-strided (numpy has the same issue) if (0 not in large_expanded.stride() and 0 not in large_expanded_clone.stride()): r1 = tensorfn_inplace(large_expanded, small_expanded, small2_expanded) r2 = tensorfn_inplace(large_expanded_clone, small, small2) self.assertEqual(r1, r2) def broadcastable(t0, t1, t2=None): try: t1.expand_as(t0) if t2 is not None: t2.expand_as(t0) except RuntimeError: return False return True def _test_in_place_broadcastable(t0, t1, t2=None): if not broadcastable(t0, t1, t2): same_size = t0.numel() == t1.numel() and (t0.numel() == t2.numel() if t2 is not None else True) if not same_size: self.assertRaises(RuntimeError, lambda: tensorfn_inplace(t0, t1, t2)) else: tensorfn_inplace(t0, t1, t2) if fn not in fns_3_args and fn not in fns_value_kwarg: _test_in_place_broadcastable(small, large_expanded) _test_in_place_broadcastable(small, large) else: _test_in_place_broadcastable(small2, small_expanded, large_expanded) _test_in_place_broadcastable(small2, small, large) @unittest.skipIf(IS_FBCODE and IS_REMOTE_GPU, "cublas runtime error") @onlyCUDA @wrapDeterministicFlagAPITest def test_cublas_config_nondeterministic_alert(self, device): test_cases = [ # (function, (tensor sizes)) ('mm', ((2, 2), (2, 2),)), ('mv', ((2, 2), (2,),)), ('bmm', ((1, 2, 2), (1, 2, 2),))] test_configs = [ # (CuBLAS workspace config, is deterministic) ('garbage', False), (None, False), (':4096:8', True), (':16:8', True)] cublas_var_name = 'CUBLAS_WORKSPACE_CONFIG' is_cuda10_2_or_higher = ( (torch.version.cuda is not None) and ([int(x) for x in torch.version.cuda.split(".")] >= [10, 2])) def test_case_info(fn_name, config): return f'function "{fn_name}" with config "{"" if config is None else config}"' # Create processes to test each combination of test cases and config settings processes = [] for fn_name, arg_sizes in test_cases: for config, is_config_deterministic in test_configs: env = os.environ.copy() if config is None: if env.get(cublas_var_name) is not None: del env[cublas_var_name] else: env[cublas_var_name] = config should_throw_error = is_cuda10_2_or_higher and not is_config_deterministic script = f""" import torch torch.use_deterministic_algorithms(True) fn = torch.{fn_name} arg_sizes = {arg_sizes} device = '{device}' should_throw_error = {should_throw_error} args = [] for arg_size in arg_sizes: args.append(torch.randn(*arg_size, device=device)) try: fn(*args) except RuntimeError as e: if not should_throw_error: raise RuntimeError('Did not expect any error to be raised') elif 'Deterministic behavior was enabled with either' not in str(e): raise RuntimeError('Expected a CuBLAS nondeterministic error, but got a different error') else: if should_throw_error: raise RuntimeError('Expected a CuBLAS nondeterministic error, but it was not raised') """ try: subprocess.check_output( [sys.executable, '-c', script], stderr=subprocess.STDOUT, # On Windows, opening the subprocess with the default CWD makes `import torch` # fail, so just set CWD to this script's directory cwd=os.path.dirname(os.path.realpath(__file__)), env=env) except subprocess.CalledProcessError as e: self.fail(msg=( f'Subprocess exception while attempting to run {test_case_info(fn_name, config)}:\n' + e.output.decode("utf-8"))) # FIXME: update OpInfos to support "nondeterministic samples" and port these tests # to that architecture @skipIfMps def test_nondeterministic_alert_AvgPool3d(self, device): module = torch.nn.AvgPool3d(3) input = torch.randn(2, 3, 3, 3, requires_grad=True, device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('avg_pool3d_backward_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) @skipIfMps def test_nondeterministic_alert_AdaptiveAvgPool2d(self, device): module = torch.nn.AdaptiveAvgPool2d(3) input = torch.randn(2, 3, 3, requires_grad=True, device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('adaptive_avg_pool2d_backward_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) @skipIfMps def test_nondeterministic_alert_AdaptiveAvgPool3d(self, device): module = torch.nn.AdaptiveAvgPool3d(3) input = torch.randn(2, 3, 3, 3, requires_grad=True, device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('adaptive_avg_pool3d_backward_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) @skipIfMps def test_nondeterministic_alert_MaxPool3d(self, device): module = torch.nn.MaxPool3d(3) input = torch.randn(2, 3, 3, 3, requires_grad=True, device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('max_pool3d_with_indices_backward_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) @skipIfMps def test_nondeterministic_alert_AdaptiveMaxPool2d(self, device): module = torch.nn.AdaptiveMaxPool2d(3) input = torch.randn(2, 3, 3, requires_grad=True, device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('adaptive_max_pool2d_backward_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) @skipIfMps def test_nondeterministic_alert_FractionalMaxPool2d(self, device): module = torch.nn.FractionalMaxPool2d(2, output_ratio=0.5) input = torch.randn(2, 3, 3, 3, requires_grad=True, device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('fractional_max_pool2d_backward_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) @skipIfMps def test_nondeterministic_alert_FractionalMaxPool3d(self, device): module = torch.nn.FractionalMaxPool3d(2, output_ratio=0.5) input = torch.randn(2, 3, 3, 3, 3, requires_grad=True, device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('fractional_max_pool3d_backward_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) @skipIfMps def test_nondeterministic_alert_interpolate_linear(self, device): input = torch.randn(1, 2, 4, device=device, requires_grad=True) res = torch.nn.functional.interpolate( input, size=12, mode='linear', align_corners=False) grad = torch.ones_like(res) @expectedAlertNondeterministic('upsample_linear1d_backward_out_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_interpolate_bilinear(self, device): input = torch.randn(1, 2, 4, 4, device=device, requires_grad=True) res = torch.nn.functional.interpolate( input, size=12, mode='bilinear', align_corners=False) grad = torch.ones_like(res) @expectedAlertNondeterministic('upsample_bilinear2d_backward_out_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) @skipIfMps def test_nondeterministic_alert_interpolate_bicubic(self, device): input = torch.randn(1, 2, 4, 4, device=device, requires_grad=True) res = torch.nn.functional.interpolate( input, size=12, mode='bicubic', align_corners=False) grad = torch.ones_like(res) @expectedAlertNondeterministic('upsample_bicubic2d_backward_out_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) @skipIfMps def test_nondeterministic_alert_interpolate_trilinear(self, device): input = torch.randn(1, 2, 4, 4, 4, device=device, requires_grad=True) res = torch.nn.functional.interpolate( input, size=12, mode='trilinear', align_corners=False) grad = torch.ones_like(res) @expectedAlertNondeterministic('upsample_trilinear3d_backward_out_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) @skipIfMps def test_nondeterministic_alert_ReflectionPad1d(self, device): module = torch.nn.ReflectionPad1d((1, 2)) input = torch.randn(2, 3, 8, device=device, requires_grad=True) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('reflection_pad1d_backward_out_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_ReflectionPad2d(self, device): module = torch.nn.ReflectionPad2d((1, 2, 3, 4)) input = torch.randn(2, 3, 8, 8, device=device, requires_grad=True) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('reflection_pad2d_backward_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) @skipIfMps def test_nondeterministic_alert_ReflectionPad3d(self, device): module = torch.nn.ReflectionPad3d((1, 2, 3, 4, 5, 6)) input = torch.randn(2, 3, 8, 8, 8, device=device, requires_grad=True) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('reflection_pad3d_backward_out_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) @skipIfMps def test_nondeterministic_alert_ReplicationPad1d(self, device): module = torch.nn.ReplicationPad1d((1, 2)) input = torch.randn(2, 3, 4, device=device, requires_grad=True) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('replication_pad1d_backward_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_ReplicationPad2d(self, device): module = torch.nn.ReplicationPad2d((1, 2, 3, 4)) input = torch.randn(2, 3, 4, 4, device=device, requires_grad=True) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('replication_pad2d_backward_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) @skipIfMps def test_nondeterministic_alert_ReplicationPad3d(self, device): module = torch.nn.ReplicationPad3d((1, 2, 3, 4, 5, 6)) input = torch.randn(2, 3, 4, 4, 4, device=device, requires_grad=True) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('replication_pad3d_backward_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_NLLLoss(self, device): module = torch.nn.NLLLoss() input = torch.randn(2, 3, 5, 5, device=device) target = torch.rand(2, 5, 5, device=device).mul(3).floor().long() @expectedAlertNondeterministic('nll_loss2d_forward_out_cuda_template', ['cuda']) def forward_func(slf, device): module(input, target) forward_func(self, device) def test_nondeterministic_alert_CTCLoss(self, device): module = torch.nn.CTCLoss() input = torch.randn(50, 3, 15, device=device, requires_grad=True) target = torch.randint(0, 14, (3, 30), device=device) input_lengths = [50, 50, 50] target_lengths = [30, 25, 20] res = module(input, target, input_lengths, target_lengths) grad = torch.ones_like(res) @expectedAlertNondeterministic('ctc_loss_backward_gpu', ['cuda']) def backward_func(slf, device): res.backward(grad, retain_graph=True) backward_func(self, device) def test_nondeterministic_alert_EmbeddingBag_max(self, device): module = torch.nn.EmbeddingBag( 4, 3, None, 2., False, 'max', _weight=torch.randn(4, 3, device=device, requires_grad=True)) input = torch.randint(0, 3, (4, 3), device=device) res = module(input) grad = torch.ones_like(res) @expectedAlertNondeterministic('embedding_bag_backward_cuda_max', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_nondeterministic_alert_scatter_add(self, device): def test_func(op_call): input = torch.randn(5, 4, device=device) dim = 0 index = torch.tensor([[3]], device=device) src = torch.tensor([[1.0]], device=device) @expectedAlertNondeterministic('scatter_add_cuda_kernel', ['cuda']) def forward_func(slf, device): op_call(input, dim, index, src) forward_func(self, device) test_func(torch.Tensor.scatter_add_) test_func(torch.Tensor.scatter_add) test_func(torch.scatter_add) @expectedFailureMeta # expected a non-determinitic error, but it was not raised @onlyNativeDeviceTypes def test_nondeterministic_alert_put(self, device): def test_func(op_call): a = torch.randn(10, device=device) indices = torch.tensor([0, 0], device=device) values = torch.tensor([0., 1.], device=device) @expectedAlertNondeterministic('put_') def forward_func(slf, device): op_call(a, indices, values, accumulate=False) forward_func(self, device) test_func(torch.Tensor.put) test_func(torch.Tensor.put_) def test_nondeterministic_alert_put_accumulate(self, device): def test_func(op_call): a = torch.randn(10, device=device) indices = torch.tensor([0, 0], device=device) values = torch.tensor([0., 1.], device=device) @expectedAlertNondeterministic('put_', ['cuda']) def forward_func(slf, device): op_call(a, indices, values, accumulate=True) forward_func(self, device) test_func(torch.Tensor.put) test_func(torch.Tensor.put_) @skipIfMps def test_nondeterministic_alert_histc(self, device): def test_func(op_call): a = torch.tensor([], device=device) @expectedAlertNondeterministic('_histc_cuda', ['cuda']) def forward_func(slf, device): res = op_call(a, min=0, max=3) forward_func(self, device) test_func(torch.histc) test_func(torch.Tensor.histc) @skipIfMps def test_nondeterministic_alert_bincount(self, device): def test_func(op_call): a = torch.tensor([], device=device, dtype=torch.long) @expectedAlertNondeterministic('_bincount_cuda', ['cuda']) def forward_func(slf, device): res = op_call(a) forward_func(self, device) test_func(torch.bincount) test_func(torch.Tensor.bincount) # Ensures that kthvalue throws nondeterministic alerts in the correct cases @dtypes(torch.double) def test_nondeterministic_alert_kthvalue(self, device, dtype): @expectedAlertNondeterministic('kthvalue CUDA', ['cuda']) def test_func(slf, device, call_type): S = 10 k = 5 a = torch.randn(S, device=device) if call_type == 'function': torch.kthvalue(a, k) elif call_type == 'method': a.kthvalue(k) elif call_type == 'out': values = torch.empty_like(a) indices = torch.empty((), device=device, dtype=torch.long) torch.kthvalue(a, k, out=(values, indices)) else: self.fail(f"'{call_type}' is not a valid call type") test_func(self, device, 'function') test_func(self, device, 'method') test_func(self, device, 'out') @onlyNativeDeviceTypes def test_nondeterministic_alert_gather(self, device): def test_func(op_call): a = torch.randn(3, 3, device=device, requires_grad=True) dim = 0 index = torch.tensor([[0]], device=device) res = op_call(a, dim, index) grad = torch.ones_like(res) @expectedAlertNondeterministic('scatter_add_cuda_kernel', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) test_func(torch.gather) test_func(torch.Tensor.gather) @skipIfMps def test_nondeterministic_alert_grid_sample_2d(self, device): input = torch.empty(1, 1, 2, 2, device=device, requires_grad=True) grid = torch.empty(1, 1, 1, 2, device=device) res = torch.nn.functional.grid_sample(input, grid, align_corners=False) grad = torch.ones_like(res) @expectedAlertNondeterministic('grid_sampler_2d_backward_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) @skipIfMps def test_nondeterministic_alert_grid_sample_3d(self, device): input = torch.empty(1, 1, 2, 2, 2, device=device, requires_grad=True) grid = torch.empty(1, 1, 1, 2, 3, device=device) res = torch.nn.functional.grid_sample(input, grid, align_corners=False) grad = torch.ones_like(res) @expectedAlertNondeterministic('grid_sampler_3d_backward_cuda', ['cuda']) def backward_func(slf, device): res.backward(grad) backward_func(self, device) def test_invalid_shapes_grid_sampler(self, device): make_arg = partial( make_tensor, device=device, dtype=torch.float64, requires_grad=True) inputs = ( # input, grid ((5, 5, 5, 5, 5,), (1, 1, 1, 4, 4,)), # 3d ((5, 5, 5, 5,), (1, 1, 4, 4,)), # 2d ) interpolation_mode = 0 padding_mode = 0 align_corners = True err = "expected grid and input to have same batch size" for input, grid in inputs: input = make_arg(input) grid = make_arg(grid, low=-1, high=1) # Wrapper for the 2d, 3d, and cuDNN functions listed below. with self.assertRaisesRegex(RuntimeError, err): torch.grid_sampler( input, grid, interpolation_mode, padding_mode, align_corners) # Expects 2d input. with self.assertRaisesRegex(RuntimeError, err): torch.grid_sampler_2d( input, grid, interpolation_mode, padding_mode, align_corners) # Expects 3d input. with self.assertRaisesRegex(RuntimeError, err): torch.grid_sampler_3d( input, grid, interpolation_mode, padding_mode, align_corners) # Expects 2d input. with self.assertRaisesRegex(RuntimeError, err): torch._grid_sampler_2d_cpu_fallback( input, grid, interpolation_mode, padding_mode, align_corners) # Expects 2d input, on CUDA. # Doesn't work on CPU and ROCm. if device != 'cpu' and TEST_CUDNN and not TEST_WITH_ROCM: with self.assertRaisesRegex(RuntimeError, err): torch.cudnn_grid_sampler(input, grid) def test_dist(self, device): def run_test(x, y): for p in [0, 1, 2, 3, 4, inf, -inf]: dist_xy = torch.dist(x, y, p) dist_xy_norm = torch.norm(x - y, p) self.assertEqual(dist_xy, dist_xy_norm) run_test(torch.randn(5, device=device), torch.randn(5, device=device)) x = torch.zeros(3, device=device) y = torch.zeros(3, device=device) y[1] = 1. run_test(x, y) # Ensures that median throws nondeterministic alerts in the correct cases @dtypes(torch.double) def test_nondeterministic_alert_median(self, device, dtype): def test_func(slf, device, call_type): S = 10 a = torch.randn(S, device=device) if call_type == 'function': torch.median(a) elif call_type == 'function with indices': torch.median(a, 0) elif call_type == 'method': a.median() elif call_type == 'method with indices': a.median(0) elif call_type == 'out with indices': result = torch.empty_like(a) indices = torch.empty((), dtype=torch.long, device=device) torch.median(a, 0, out=(result, indices)) else: self.fail(f"'{call_type}' is not a valid call type") @expectedAlertNondeterministic('median CUDA with indices output', ['cuda']) def test_func_expect_error(slf, device, call_type): test_func(slf, device, call_type) test_func(self, device, 'function') test_func_expect_error(self, device, 'function with indices') test_func(self, device, 'method') test_func_expect_error(self, device, 'method with indices') test_func_expect_error(self, device, 'out with indices') # FIXME: move to test_scatter_gather_ops def _test_gather_backward_one_dim(self, device, deterministic: bool = False) -> None: with DeterministicGuard(deterministic): m = random.randint(2000, 3000) elems = random.randint(10 * m, 20 * m) dim = 0 src = torch.randn(m, device=device, requires_grad=True) idx = torch.randint(m, (elems,), device=device) res = torch.gather(src, dim, idx) weight = torch.rand_like(res, device=device) * 10 ** 6 res.backward(weight) grad = src.grad.detach().clone() if torch.device(device).type == 'cuda': for _ in range(2): src.grad.data.zero_() res = torch.gather(src, dim, idx) res.backward(weight) self.assertEqual(src.grad, grad, atol=0, rtol=0) else: expected = torch.zeros_like(src, device=device) for i in range(elems): expected[idx[i]] += weight[i] self.assertEqual(grad, expected, atol=0, rtol=0) # FIXME: move to test_scatter_gather_ops @onlyNativeDeviceTypes def test_gather_backward_deterministic_path(self, device) -> None: self._test_gather_backward_one_dim(device, True) # FIXME: move to test_scatter_gather_ops @onlyCPU def test_gather_backward_one_dim(self, device) -> None: self._test_gather_backward_one_dim(device, False) # FIXME: move to test_scatter_gather_ops @onlyNativeDeviceTypes def test_scatter_add_one_dim_deterministic(self, device) -> None: with DeterministicGuard(True): m = random.randint(20, 30) elems = random.randint(2000 * m, 3000 * m) dim = 0 src = torch.randn(elems, device=device) idx = torch.randint(m, (elems,), device=device) x = torch.zeros(m, device=device) res = x.scatter_add(dim, idx, src) expected = torch.zeros(m, device=device) for i in range(elems): expected[idx[i]] += src[i] self.assertEqual(res, expected, atol=0, rtol=0) # FIXME: move to test_scatter_gather_ops @onlyNativeDeviceTypes def test_scatter_zero_size_index(self, device) -> None: null_index = torch.zeros((0, 4), dtype=torch.int64) null_arr = torch.zeros((0, 4)) original = torch.arange(4, dtype=torch.float32) result = original.scatter(0, null_index, null_arr) self.assertEqual(result, original, atol=0, rtol=0) @onlyCUDA def test_sync_warning(self, device): def _sync_raises_helper(f, level): with CudaSyncGuard(level): if level == 1: with self.assertWarnsRegex(UserWarning, "called a synchronizing "): f() elif level == 2: with self.assertRaisesRegex(RuntimeError, "called a synchronizing "): f() def _no_sync_helper(f, level): with CudaSyncGuard(level): f() def _ind_put_fn(x, ind, val): x[ind] = val return x def _ind_get_fn(x, ind): return x[ind] def _cond_fn(x): if x: # taking boolean value of a tensor synchronizes return x else: return 2 * x # prepare inputs for subsequent ops size = 4 x = torch.rand(size, device=device) y = torch.rand((), device=device) ind = torch.randint(size, (3,), device=device) ind_cpu = ind.cpu() repeats = torch.full((1,), 2, device=device) mask = torch.randint(2, (size,), device=device, dtype=bool) expect_no_sync = (lambda: _ind_put_fn(x, mask, 1.), lambda: _ind_put_fn(x, ind, y), lambda: _ind_get_fn(x, ind), lambda: torch.nn.functional.one_hot(ind, num_classes=size), lambda: torch.randperm(20000, device=device), lambda: torch.repeat_interleave(x, 2, output_size=2 * size), lambda: torch.repeat_interleave(x, repeats, output_size=2 * size)) expect_sync = (lambda: _ind_put_fn(x, mask, y), lambda: _ind_put_fn(x, ind_cpu, y), lambda: _ind_get_fn(x, mask), lambda: _ind_get_fn(x, ind_cpu), lambda: x.nonzero(), lambda: _cond_fn(y), lambda: torch.nn.functional.one_hot(ind), lambda: torch.repeat_interleave(x, 2), lambda: torch.repeat_interleave(x, repeats)) for f, level in product(expect_no_sync, (1, 2)): _no_sync_helper(f, level) for f, level in product(expect_sync, (1, 2)): _sync_raises_helper(f, level) @dtypes(*floating_types_and(torch.half, torch.bfloat16)) @skipIfMps def test_log_normal(self, device, dtype): a = torch.tensor([10], dtype=dtype, device=device).log_normal_() self.assertEqual(a.dtype, dtype) self.assertEqual(a.size(), torch.Size([1])) @dtypes(*all_types_and(torch.half, torch.bfloat16)) @skipIfMps def test_geometric(self, device, dtype): a = torch.tensor([10], dtype=dtype, device=device).geometric_(0.5) self.assertEqual(a.dtype, dtype) self.assertEqual(a.size(), torch.Size([1])) @skipIfMps def test_repeat_interleave(self, device): y = torch.tensor([[1, 2], [3, 4]], device=device) # exercise single argument function signature temp = y.repeat_interleave(2) self.assertEqual(torch.Size([8]), temp.size()) for dtype in [torch.int, torch.long]: lengths = torch.tensor([1, 2], dtype=dtype, device=device) output_size = torch.sum(lengths) a = torch.repeat_interleave( y, lengths, dim=0, ) self.assertEqual(a.dtype, y.dtype) self.assertEqual(a.size(), torch.Size([3, 2])) a_with_output = torch.repeat_interleave( y, lengths, dim=0, output_size=output_size, ) self.assertEqual(a_with_output.dtype, y.dtype) self.assertEqual(a_with_output.size(), torch.Size([3, 2])) @dtypes(*floating_types()) @dtypesIfCPU(*floating_types_and(torch.bfloat16)) @dtypesIfCUDA(*floating_types_and(torch.half)) def test_bernoulli_p(self, device, dtype): for trivial_p in ([0, 1], [1, 0, 1, 1, 0, 1]): x = torch.tensor(trivial_p, dtype=dtype, device=device) self.assertEqual(x.bernoulli().tolist(), trivial_p) def isBinary(t): return torch.ne(t, 0).mul_(torch.ne(t, 1)).sum().item() == 0 p = torch.rand(5, 5, dtype=dtype, device=device) self.assertTrue(isBinary(p.bernoulli())) p = torch.rand(5, dtype=dtype, device=device).expand(5, 5) self.assertTrue(isBinary(p.bernoulli())) p = torch.rand(5, 5, dtype=dtype, device=device) torch.bernoulli(torch.rand_like(p), out=p) self.assertTrue(isBinary(p)) # RngUniform not implemented for Integral type in XLA test @dtypes(*floating_types()) @dtypesIfCPU(*all_types_and(torch.bool)) @dtypesIfCUDA(*all_types_and(torch.bool, torch.half)) def test_bernoulli_self(self, device, dtype): def isBinary(t): return torch.ne(t, 0).mul_(torch.ne(t, 1)).sum().item() == 0 t = torch.empty(10, 10, dtype=dtype, device=device) t.fill_(2) t.bernoulli_(0.5) self.assertTrue(isBinary(t)) for p_dtype in floating_types_and(*[torch.half] if device.startswith('cuda') else []): p = torch.rand(10, dtype=p_dtype, device=device).expand(10, 10) t.fill_(2) t.bernoulli_(p) self.assertTrue(isBinary(t)) t.fill_(2) torch.bernoulli(torch.rand_like(t, dtype=p_dtype), out=t) self.assertTrue(isBinary(t)) t.fill_(2) t.bernoulli_(torch.rand_like(t, dtype=p_dtype)) self.assertTrue(isBinary(t)) @slowTest @dtypes(*floating_types()) @dtypesIfCUDA(*floating_types_and(torch.half)) def test_bernoulli_edge_cases(self, device, dtype): # Need to draw a lot of samples to cover every random floating point number. a = torch.zeros(10000, 10000, dtype=dtype, device=device) # probability of drawing "1" is 0 num_ones = (torch.bernoulli(a) == 1).sum() self.assertEqual(num_ones, 0) b = torch.ones(10000, 10000, dtype=dtype, device=device) # probability of drawing "1" is 1 num_zeros = (torch.bernoulli(b) == 0).sum() self.assertEqual(num_zeros, 0) @dtypes(*floating_types_and(torch.half, torch.bfloat16)) @skipIfMps def test_exponential(self, device, dtype): a = torch.tensor([10], dtype=dtype, device=device).exponential_(0.5) self.assertEqual(a.dtype, dtype) self.assertEqual(a.size(), torch.Size([1])) # Tests extremal behavior tests = ((-0, float('inf')), (0, float('inf')), (float('inf'), 0)) for test in tests: t = torch.empty((1,), device=device, dtype=dtype).exponential_(test[0]) self.assertTrue(t.item() == test[1]) # Tests that negative lambda fails with self.assertRaises(RuntimeError): torch.empty((1,), device=device, dtype=dtype).exponential_(-0.5) @onlyCUDA @dtypes(torch.half, torch.float) def test_exponential_no_zero(self, device, dtype): # naively, 0 in exponential can be generated with probability 2^-24 # so we need more samples to check if it's not generated # instead of doing one # don't test CPU, that would be a long test x = torch.empty(50000000, device=device, dtype=dtype).exponential_() self.assertTrue(x.min() > 0) def _generate_correlation_tensors(self, device, dtype): yield make_tensor((0, 0), dtype=dtype, device=device) yield make_tensor((1, 0), dtype=dtype, device=device) yield make_tensor((0, 1), dtype=dtype, device=device) yield make_tensor((2,), dtype=dtype, device=device) yield make_tensor((2, 1), dtype=dtype, device=device) yield make_tensor((2, 2), dtype=dtype, device=device) yield make_tensor((2, 3), dtype=dtype, device=device) yield make_tensor((5, 10), dtype=dtype, device=device) yield make_tensor((5, 10), dtype=dtype, device=device, noncontiguous=True) if dtype != torch.int: yield torch.tensor([0, -2, nan, 10.2, inf], dtype=dtype, device=device) @onlyNativeDeviceTypes @dtypes(torch.int, torch.float, torch.cfloat) def test_corrcoef(self, device, dtype): for x in self._generate_correlation_tensors(device, dtype): res = torch.corrcoef(x) ref = np.corrcoef(x.cpu().numpy()) self.assertEqual(res, ref, exact_dtype=False) @dtypes(torch.int, torch.float, torch.cfloat) def test_cov(self, device, dtype): def check(t, correction=1, fweights=None, aweights=None): res = torch.cov(t, correction=correction, fweights=fweights, aweights=aweights) t = t.cpu().numpy() fweights = fweights.cpu().numpy() if fweights is not None else None aweights = aweights.cpu().numpy() if aweights is not None else None ref = np.cov(t, ddof=correction, fweights=fweights, aweights=aweights) self.assertEqual(res, ref, atol=1e-05, rtol=1e-05, exact_dtype=False) for x in self._generate_correlation_tensors(device, dtype): check(x) num_observations = x.numel() if x.ndim < 2 else x.size(1) if num_observations > 0: fweights = torch.randint(1, 10, (num_observations,), device=device) aweights = make_tensor((num_observations,), dtype=torch.float, device=device, low=1) for correction, fw, aw in product([0, 1, 2], [None, fweights], [None, aweights]): check(x, correction, fweights, aweights) @skipIfNoSciPy @dtypes(*floating_types_and(torch.half, torch.bfloat16)) def test_uniform_kstest(self, device, dtype): from scipy import stats size = 1000 for from_ in [-42, 0, 4.2]: for to_ in [-4.2, 0, 42]: if to_ > from_: t = torch.empty(size, dtype=dtype, device=device).uniform_(from_, to_) res = stats.kstest(t.cpu().to(torch.double), 'uniform', args=(from_, (to_ - from_))) self.assertTrue(res.statistic < 0.1) @skipIfNoSciPy @dtypes(*floating_types_and(torch.half)) @dtypesIfCUDA(*floating_types_and(torch.half, torch.bfloat16)) def test_normal_kstest(self, device, dtype): from scipy import stats size = 1000 for mean in [-10, 0, 50]: for std in [1, 5, 10]: t = torch.empty(size, dtype=dtype, device=device).normal_(mean=mean, std=std) res = stats.kstest(t.cpu().to(torch.double), 'norm', args=(mean, std)) self.assertTrue(res.statistic < 0.1) @skipIfMps @skipIfNoSciPy @dtypes(*floating_types_and(torch.half, torch.bfloat16)) def test_lognormal_kstest(self, device, dtype): from scipy import stats size = 1000 for mean in [-3, 0, 7]: for std in [1, 5, 7]: t = torch.empty(size, dtype=dtype, device=device).log_normal_(mean=mean, std=std) res = stats.kstest(t.cpu().to(torch.double), 'lognorm', args=(std, 0, math.exp(mean))) if dtype == torch.half: self.assertTrue(res.statistic < 0.3) else: self.assertTrue(res.statistic < 0.1) @skipIfMps @skipIfNoSciPy @dtypes(*floating_types_and(torch.half, torch.bfloat16)) def test_exponential_kstest(self, device, dtype): from scipy import stats size = 1000 for lambd in [0.5, 1.0, 5.0]: t = torch.empty(size, dtype=dtype, device=device).exponential_(lambd=lambd) res = stats.kstest(t.cpu().to(torch.double), 'expon', args=(0, 1 / lambd,)) self.assertTrue(res.statistic < 0.1) @skipIfMps @skipIfNoSciPy @dtypes(*floating_types_and(torch.half, torch.bfloat16)) def test_cauchy_kstest(self, device, dtype): from scipy import stats size = 1000 for median in [-10, 0, 50]: for sigma in [0.5, 1.0, 10.0]: t = torch.empty(size, dtype=dtype, device=device).cauchy_(median=median, sigma=sigma) res = stats.kstest(t.cpu().to(torch.double), 'cauchy', args=(median, sigma)) self.assertTrue(res.statistic < 0.1) @slowTest @onlyCUDA @dtypes(torch.bfloat16, torch.float32) def test_cauchy_no_inf(self, device, dtype): # torch.float16 will have `inf` because of its smaller range. for _ in range((2**16) * 2): x = torch.empty((2**16), dtype=dtype, device=device) x.cauchy_() self.assertFalse(x.isinf().sum()) @skipIfMps @skipIfNoSciPy @dtypes(*all_types_and(torch.half, torch.bfloat16)) def test_geometric_kstest(self, device, dtype): from scipy import stats size = 1000 for p in [0.2, 0.5, 0.8]: t = torch.empty(size, dtype=dtype, device=device).geometric_(p=p) actual = np.histogram(t.cpu().to(torch.double), np.arange(1, 100))[0] expected = stats.geom(p).pmf(np.arange(1, 99)) * size res = stats.chisquare(actual, expected) self.assertEqual(res.pvalue, 1.0, atol=0.1, rtol=0) # FIXME: find test suite for pdist and cdist def test_pairwise_distance_empty(self, device): shape = (2, 0) x = torch.randn(shape, device=device) y = torch.randn(shape, device=device) self.assertEqual(torch.zeros(2, device=device), torch.pairwise_distance(x, y)) self.assertEqual(torch.zeros((2, 1), device=device), torch.pairwise_distance(x, y, keepdim=True)) shape = (0, 2) x = torch.randn(shape, device=device) y = torch.randn(shape, device=device) self.assertEqual(torch.zeros(0, device=device), torch.pairwise_distance(x, y)) self.assertEqual(torch.zeros((0, 1), device=device), torch.pairwise_distance(x, y, keepdim=True)) def test_pdist_empty(self, device): shape = (0, 2) x = torch.randn(shape, device=device) self.assertEqual(torch.empty(0, device=device), torch.pdist(x)) shape = (1, 2) x = torch.randn(shape, device=device) self.assertEqual(torch.empty(0, device=device), torch.pdist(x)) shape = (3, 0) x = torch.randn(shape, device=device) self.assertEqual(torch.zeros(3, device=device), torch.pdist(x)) def test_cdist_empty(self, device): x = torch.randn((0, 5), device=device) y = torch.randn((4, 5), device=device) self.assertEqual(torch.empty(0, 4, device=device), torch.cdist(x, y)) x = torch.randn((2, 5), device=device) y = torch.randn((0, 5), device=device) self.assertEqual(torch.empty(2, 0, device=device), torch.cdist(x, y)) x = torch.randn((2, 0), device=device) y = torch.randn((3, 0), device=device) self.assertEqual(torch.zeros(2, 3, device=device), torch.cdist(x, y)) x = torch.randn((2, 0), device=device) y = torch.randn((0, 0), device=device) self.assertEqual(torch.empty(2, 0, device=device), torch.cdist(x, y)) def _brute_cdist(self, x, y, p=2): r1 = x.shape[-2] r2 = y.shape[-2] if r1 == 0 or r2 == 0: return torch.empty(r1, r2, device=x.device) return torch.norm(x[..., None, :] - y[..., None, :, :], p=p, dim=-1) @skipIfMps def test_cdist_norm(self, device): for r1 in [3, 4, 5, 6]: for m in [2, 3, 4, 10]: for r2 in [4, 6, 7, 8]: for p in [0, 1, 2, 3, 1.5, 2.5, float('inf')]: x = torch.randn(r1, m, device=device) y = torch.randn(r2, m, device=device) if p == 2: for cm in ['use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']: actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertEqual(expected, actual, rtol=0, atol=0.02) else: actual = torch.cdist(x, y, p=p) expected = self._brute_cdist(x, y, p=p) self.assertEqual(expected, actual) @skipIfMps def test_cdist_norm_batch(self, device): for r1 in [3, 4, 5, 6]: for m in [2, 3, 4, 10]: for r2 in [4, 6, 7, 8]: for p in [0, 1, 2, 3, 1.5, 2.5, float('inf')]: x = torch.randn(2, 3, 6, r1, m, device=device) y = torch.randn(2, 3, 6, r2, m, device=device) if p == 2: for cm in ['use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']: actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertEqual(expected, actual, rtol=0, atol=0.02) else: actual = torch.cdist(x, y, p=p) expected = self._brute_cdist(x, y, p=p) self.assertEqual(expected, actual) @onlyCUDA def test_cdist_cuda_backward(self, device): for l1 in [1, 511, 513]: for l2 in [1, 511, 513]: for p in [0, 1, 2, 3, 1.5, 2.5, float('inf')]: x1 = torch.randn(4, l1, 32, device=device, requires_grad=True) x2 = x1.clone().detach_().requires_grad_() y1 = torch.randn(4, l2, 32, device=device, requires_grad=True) y2 = y1.clone().detach_().requires_grad_() if p == 2: for cm in ['use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']: z1 = torch.cdist(x1, y1, p=2, compute_mode=cm).mean() z2 = self._brute_cdist(x2, y2, p=2).mean() z1.backward() z2.backward() self.assertEqual(x1.grad, x2.grad, rtol=0, atol=0.001) self.assertEqual(y1.grad, y2.grad, rtol=0, atol=0.001) else: z1 = torch.cdist(x1, y1, p=p).mean() z2 = self._brute_cdist(x2, y2, p=p).mean() self.assertEqual(x1.grad, x2.grad, rtol=0, atol=0.001) self.assertEqual(y1.grad, y2.grad, rtol=0, atol=0.001) @tf32_on_and_off(0.005) def test_cdist_large(self, device): for cm in ['use_mm_for_euclid_dist_if_necessary', 'use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']: x = torch.randn(1000, 10, device=device) y = torch.randn(1000, 10, device=device) actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertEqual(expected, actual) @slowTest @tf32_on_and_off(0.01) def test_cdist_large_batch(self, device): for cm in ['use_mm_for_euclid_dist_if_necessary', 'use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']: x = torch.randn(4, 3, 1000, 10, device=device) y = torch.randn(4, 3, 1000, 10, device=device) actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertEqual(expected, actual) @tf32_on_and_off(0.005) def test_cdist_non_contiguous(self, device): for cm in ['use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']: x = torch.randn(5, 7, device=device).mT y = torch.randn(5, 3, device=device).mT actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertFalse(x.is_contiguous()) self.assertFalse(y.is_contiguous()) self.assertEqual(expected, actual) x = torch.randn(7, 5, device=device) y = torch.randn(5, 3, device=device).t() actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertTrue(x.is_contiguous()) self.assertFalse(y.is_contiguous()) self.assertEqual(expected, actual) x = torch.randn(5, 7, device=device).t() y = torch.randn(3, 5, device=device) actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertFalse(x.is_contiguous()) self.assertTrue(y.is_contiguous()) self.assertEqual(expected, actual) @tf32_on_and_off() def test_cdist_non_contiguous_batch(self, device): for cm in ['use_mm_for_euclid_dist', 'donot_use_mm_for_euclid_dist']: x = torch.randn(4, 3, 2, 5, 7, device=device).mT y = torch.randn(4, 3, 2, 5, 3, device=device).mT actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertFalse(x.is_contiguous()) self.assertFalse(y.is_contiguous()) self.assertEqual(expected, actual) x = torch.randn(7, 2, 7, 5, device=device) y = torch.randn(7, 2, 5, 3, device=device).mT actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertTrue(x.is_contiguous()) self.assertFalse(y.is_contiguous()) self.assertEqual(expected, actual) x = torch.randn(4, 5, 7, device=device).mT y = torch.randn(4, 3, 5, device=device) actual = torch.cdist(x, y, p=2, compute_mode=cm) expected = self._brute_cdist(x, y, p=2) self.assertFalse(x.is_contiguous()) self.assertTrue(y.is_contiguous()) self.assertEqual(expected, actual) # Maybe merge into OpInfo? def test_cdist_euclidean_large(self, device): def _test_euclidean_large_cdist(sizex, sizey=None): if sizey is None: sizey = sizex x = torch.randn(sizex, device=device, dtype=torch.float) y = torch.randn(sizey, device=device, dtype=torch.float) eps = 1e-6 # to avoid extremum x = x - (((x - y) < eps).float() * 2 * eps) x.requires_grad = True y.requires_grad = True dist = torch.cdist(x, y, p=2) # Do a backward pass to check that it is valid for large # matrices loss = dist.sum() loss.backward() _test_euclidean_large_cdist((2000, 5)) # Ensure that cdist backward with p<1 does not produce NaNs @skipIfMps def test_cdist_grad_p_lt_1_no_nan(self, device): for p in [0.99, 0.7, 0.5, 0.1, 0.01]: x = torch.randn(1, 2, device=device) y = x.clone().detach() + torch.tensor([[1., 0.]], device=device) x.requires_grad = True y.requires_grad = True result = torch.cdist(x, y, p=p) result.backward(torch.ones_like(result)) self.assertFalse(torch.isnan(x.grad).any()) self.assertFalse(torch.isnan(y.grad).any()) def test_cdist_same_inputs(self, device): # Test to detect issues in cdist gradient calculation # When the distances are 0 sizex = (1, 27, 32) for p in [0, 1, 2, 3, 1.5, 2.5, float('inf')]: x = torch.randn(sizex, device=device, dtype=torch.float) dist_grad = torch.randn((1, 27, 27), device=device, dtype=torch.float) y = x.clone() eps = 1e-6 x.requires_grad = True d = torch.cdist(x, y) d.backward(dist_grad) # Check that the backward passs does not contain invalid # values such as nan or inf assert torch.isfinite(x.grad).all() @skipIfMps def test_cumsum(self, device): x = torch.rand(100, 100, device=device) res1 = torch.cumsum(x, 1) res2 = torch.tensor([]).to(device) torch.cumsum(x, 1, out=res2) self.assertEqual(res1, res2) x.cumsum_(1) self.assertEqual(res1, x) a = torch.tensor([[True, False, True], [False, False, False], [True, True, True]], device=device) b = a.byte() aRes = torch.cumsum(a, 0) bRes = torch.cumsum(b, 0) self.assertEqual(aRes, bRes) self.assertEqual(aRes, torch.tensor([[1, 0, 1], [1, 0, 1], [2, 1, 2]])) aRes = torch.cumsum(a, 1) bRes = torch.cumsum(b, 1) self.assertEqual(aRes, bRes) self.assertEqual(aRes, torch.tensor([[1, 1, 2], [0, 0, 0], [1, 2, 3]])) # Check that cummulative sum over a zero length dimension doesn't crash on backprop. # Also check that cumsum over other dimensions in a tensor with a zero-length # dimensiuon also works # Also include a basic suite of similar tests for other bases cases. shapes = [[2, 0], [2, 1, 4], [0, 2, 3], [1], [5]] for shape in shapes: for dim in range(len(shape)): raw_tensor = torch.zeros(*shape, requires_grad=True) integrated = raw_tensor.cumsum(dim=dim) # Check that backward does not crash integrated.sum().backward() # Check that output maintained correct shape self.assertEqual(raw_tensor.shape, raw_tensor.grad.shape) # Check a scalar example raw_tensor = torch.tensor(3., requires_grad=True) integrated = raw_tensor.cumsum(dim=-1) self.assertEqual(raw_tensor, integrated) # Check that backward does not crash integrated.sum().backward() # Check that output maintained correct shape self.assertEqual(raw_tensor.shape, raw_tensor.grad.shape) @skipIfMps def test_cumprod(self, device): x = torch.rand(100, 100, device=device) res1 = torch.cumprod(x, 1) res2 = torch.tensor([]).to(device) torch.cumprod(x, 1, out=res2) self.assertEqual(res1, res2) x.cumprod_(1) self.assertEqual(res1, x) a = torch.tensor([[True, False, True], [False, False, False], [True, True, True]], dtype=torch.bool, device=device) b = a.byte() aRes = torch.cumprod(a, 0) bRes = torch.cumprod(b, 0) self.assertEqual(aRes, bRes) self.assertEqual(aRes, torch.tensor([[1, 0, 1], [0, 0, 0], [0, 0, 0]])) aRes = torch.cumprod(a, 1) bRes = torch.cumprod(b, 1) self.assertEqual(aRes, bRes) self.assertEqual(aRes, torch.tensor([[1, 0, 0], [0, 0, 0], [1, 1, 1]])) # Check that cummulative prod over a zero length dimension doesn't crash on backprop. # Also check that cumprod over other dimensions in a tensor with a zero-length # dimensiuon also works # Also include a basic suite of similar tests for other bases cases. shapes = [[2, 0], [2, 1, 4], [0, 2, 3], [1], [5]] for shape in shapes: for dim in range(len(shape)): raw_tensor = torch.zeros(*shape, requires_grad=True) integrated = raw_tensor.cumprod(dim=dim) # Check that backward does not crash integrated.sum().backward() # Check that output maintained correct shape self.assertEqual(raw_tensor.shape, raw_tensor.grad.shape) # Check a scalar example raw_tensor = torch.tensor(3., requires_grad=True) integrated = raw_tensor.cumprod(dim=-1) self.assertEqual(raw_tensor, integrated) # Check that backward does not crash integrated.sum().backward() # Check that output maintained correct shape self.assertEqual(raw_tensor.shape, raw_tensor.grad.shape) @skipIfMps def test_cummax_cummin(self, device): def test_ops(op, string_of_function_name, expected_output1, expected_output2): x = torch.rand(100, 100, device=device) out1 = op(x, 1) res2 = torch.empty(0, device=device) indices2 = torch.empty(0, dtype=torch.int64, device=device) op(x, 1, out=(res2, indices2)) self.assertEqual(out1[0], res2) self.assertEqual(out1[1], indices2) a = torch.tensor([[True, False, True], [False, False, False], [True, True, True]], dtype=torch.bool, device=device) b = a.byte() aRes = op(a, 0) bRes = op(b, 0) self.assertEqual(aRes[0], bRes[0].bool()) self.assertEqual(aRes[0], expected_output1.bool()) # test inf and nan input x = torch.tensor([4, inf, 1.5, -inf, 0, nan, 1]) xRes = op(x, 0)[0] self.assertEqual(xRes, expected_output2) # op shouldn't support values, indices with a dtype, device type or layout # different from that of input tensor t = torch.randn(10) values = torch.empty(0, dtype=torch.int16) indices = torch.empty(0, dtype=torch.int64) with self.assertRaisesRegex( RuntimeError, 'expected scalar_type Float but found Short'): op(t, 0, out=(values, indices)) # Check that op over a zero length dimension doesn't crash on backprop. # Also check that op over other dimensions in a tensor with a zero-length # dimension also works # Also include a basic suite of similar tests for other bases cases. shapes = [[2, 0], [2, 1, 4], [0, 2, 3], [1], [5]] for shape in shapes: for dim in range(len(shape)): raw_tensor = torch.zeros(*shape, requires_grad=True) integrated = getattr(raw_tensor, string_of_function_name)(dim=dim) # Check that backward does not crash integrated[0].sum().backward() # Check that output maintained correct shape self.assertEqual(raw_tensor.shape, raw_tensor.grad.shape) # Check a scalar example raw_tensor = torch.tensor(3., requires_grad=True) integrated = getattr(raw_tensor, string_of_function_name)(dim=-1) # Check that backward does not crash integrated[0].sum().backward() # Check that output maintained correct shape self.assertEqual(raw_tensor.shape, raw_tensor.grad.shape) expected_out = torch.tensor([4, inf, inf, inf, inf, nan, nan]) test_ops(torch.cummax, "cummax", torch.tensor([[1, 0, 1], [1, 0, 1], [1, 1, 1]]), expected_out) expected_out = torch.tensor([4, 4, 1.5, -inf, -inf, nan, nan]) test_ops(torch.cummin, "cummin", torch.tensor([[1, 0, 1], [0, 0, 0], [0, 0, 0]]), expected_out) @skipIfMps def test_logcumsumexp(self, device): def logcumsumexp(a, axis): return torch.cumsum(a.exp(), axis=axis).log_() axis = -1 a = torch.randn(100, 100, device=device) actual = a.logcumsumexp(axis) expected = logcumsumexp(a, axis) self.assertEqual(a.dtype, actual.dtype) self.assertEqual(expected.shape, actual.shape) self.assertEqual(expected, actual) # check -inf and nan handling x = torch.tensor([-float('inf'), -float('inf'), 1.0, 1.0, float('inf'), float('inf'), float('nan'), 1.0, 1.0], device=device) x2d = x.unsqueeze(0).expand(2, -1) for inp in (x, x2d): actual = inp.logcumsumexp(axis) expected = logcumsumexp(inp, axis) self.assertEqual(expected, actual) # Check that out is actually inplace b = torch.randn(5, 2, device=device) inplace_out = torch.zeros(5, 2, device=device) expected = logcumsumexp(b, axis) torch.logcumsumexp(b, axis=axis, out=inplace_out) self.assertEqual(inplace_out, expected) # Check input and inplace_output type mismatch b = torch.randn(5, 2, device=device, dtype=torch.float64) inplace_out = torch.zeros(5, 2, device=device, dtype=torch.float32) with self.assertRaisesRegex( RuntimeError, 'expected scalar_type Double but found Float'): torch.logcumsumexp(b, axis, out=inplace_out) def _test_diff_numpy(self, t, dims=None): # Helper for test_diff to compare with NumPy reference implementation def to_np(t): if t.dtype == torch.bfloat16: return t.to(dtype=torch.float, device="cpu").numpy() else: return t.cpu().numpy() for dim in dims if dims else range(t.dim()): prepend = t.narrow(dim, 0, 1) append = t.narrow(dim, 0, 1) np_t = to_np(t) # test when no prepend and append for n in range(t.size(dim)): actual = torch.diff(t, dim=dim, n=n) expected = torch.from_numpy(np.diff(np_t, axis=dim, n=n)) self.assertEqual(actual, expected.to(t.dtype)) # test when prepend and append's size along dim is 1 for n in range(1, t.size(dim) + 4): actual = torch.diff(t, dim=dim, n=n, prepend=prepend, append=append) expected = torch.from_numpy(np.diff(np_t, axis=dim, n=n, prepend=to_np(prepend), append=to_np(append))) self.assertEqual(actual, expected.to(t.dtype)) # test when prepend and append's size along dim != 1 for n in range(1, t.size(dim) * 3): actual = torch.diff(t, dim=dim, n=n, prepend=t, append=t) expected = torch.from_numpy(np.diff(np_t, axis=dim, n=n, prepend=np_t, append=np_t)) self.assertEqual(actual, expected.to(t.dtype)) # All tensors appear contiguous on XLA @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half, torch.bool)) def test_diff_noncontig(self, device, dtype): shapes = ( (1,), (1, 5), (3, 5), (1, 5, 1), (2, 3, 5)) for shape in shapes: contig = make_tensor(shape, dtype=dtype, device=device, low=-9, high=9) non_contig = torch.empty(shape + (2, 2), device=device, dtype=dtype)[..., 0] non_contig = non_contig.select(-1, -1) non_contig.copy_(contig) self.assertTrue(not non_contig.is_contiguous() or shape == (1,)) self._test_diff_numpy(non_contig) # RngNormal not implemented for type f16 for XLA @dtypes(*all_types_and_complex_and(torch.bool)) @dtypesIfCPU(*all_types_and_complex_and(torch.half, torch.bool)) @dtypesIfCUDA(*all_types_and_complex_and(torch.half, torch.bool)) def test_diff(self, device, dtype): shapes = ( (1,), (1, 5), (3, 5), (1, 5, 1), (2, 3, 5)) for shape in shapes: contig = make_tensor(shape, dtype=dtype, device=device, low=-9, high=9) self._test_diff_numpy(contig) t = torch.ones(2, 3) with self.assertRaisesRegex( RuntimeError, 'diff expects prepend or append to be the same dimension as input'): invalid_prepend = torch.tensor([1, 2, 3], device=device, dtype=dtype) t.diff(dim=0, prepend=invalid_prepend) with self.assertRaisesRegex( RuntimeError, 'diff expects the shape of tensor to prepend or append to match that of input'): invalid_prepend = torch.tensor([[0, 1]], device=device, dtype=dtype) t.diff(dim=0, prepend=invalid_prepend) with self.assertRaisesRegex( RuntimeError, 'diff expects input to be at least one-dimensional'): scalar = torch.tensor(2, device=device, dtype=dtype) torch.diff(scalar) # if the given input arg is not a list, it returns a list of single element: [arg] def _wrap_to_list(self, input_array): return input_array if isinstance(input_array, list) else [input_array] # To ensure inf, -inf, and nan values do not cause divergence between Numpy and PyTorch. # There are two types of possible divergence: # 1. When we compute a,b both real numbers and has very small absolute values (i.e. very near to 0.0) # then, result of a/b be inf, -inf and nan, and this cause divergence. # 2. When we are dividing complex numbers by zero. For example, when a = torch.tensor(3+5j) we have # a/0 to be equal to nan + nan*j in PyTorch and inf + inf*j in Numpy. def _inf_nan_preprocess(self, actual, expected): for i in range(len(expected)): expected[i] = np.nan_to_num(expected[i], nan=nan, posinf=nan, neginf=nan) # nan_to_num is not defined for complex tensors in PyTorch. if actual[i].dtype == torch.complex64 : actual[i].real = torch.nan_to_num(actual[i].real, nan=nan, posinf=nan, neginf=nan) actual[i].imag = torch.nan_to_num(actual[i].imag, nan=nan, posinf=nan, neginf=nan) else: actual[i] = torch.nan_to_num(actual[i], nan=nan, posinf=nan, neginf=nan) return actual, expected @onlyNativeDeviceTypes @dtypes(torch.long, torch.float32, torch.complex64) def test_gradient_all(self, device, dtype): def create_scalar(shape): return make_tensor((1,), device='cpu', dtype=dtype, low=1.).item() def create_list(shape): return make_tensor((len(shape),), device='cpu', dtype=dtype, low=1.).tolist() def create_coordinate_tensors(shape): tensor_list = [] for i in range(len(shape)): tensor_list.append(make_tensor((shape[i],), device=device, dtype=dtype)) return tensor_list def filter_shape(shape, dim): filtered_shape = [] for i in range(len(dim)): filtered_shape.append(shape[dim[i]]) return filtered_shape # shape, dims format test_cases = ( ((5,), (0,)), ((4, 4), (0, 1)), ((3, 3, 3), (-1, 0)), ((4, 4, 4), (2,)), ((4, 4, 4), (0, 1)), ((4, 4, 4, 3), (0, 2, 3)), ((4, 5, 3, 4, 3), (1, 2)), ((4, 3, 6, 5, 3), (2, 4)), ((4, 3, 3, 5, 3), (0, 1, 2, 3, 4)), ((1, 3, 3), (1, 2)), ((1, 5), (1,)), ) for case, contig, edge_order, space_fn in product(test_cases, [True, False], [1, 2], (create_scalar, create_list, create_coordinate_tensors)): shape, dims = case # filter shape by dims before passing filtered shape to create_* functions filtered_shape = filter_shape(shape, dims) spacing = space_fn(filtered_shape) t = make_tensor(shape, device=device, dtype=dtype, noncontiguous=not contig) t_np = t.cpu().numpy() actual = torch.gradient(t, spacing=spacing, dim=dims, edge_order=edge_order) if space_fn == create_coordinate_tensors and spacing[0].device != 'cpu': spacing = [space.cpu().detach().numpy() for space in spacing] expected = np.gradient(t_np, *self._wrap_to_list(spacing), axis=dims, edge_order=edge_order) actual, expected = self._inf_nan_preprocess(list(actual), self._wrap_to_list(expected)) self.assertEqual(actual, expected, equal_nan=True, atol=1e-4, rtol=0, exact_dtype=False) @onlyNativeDeviceTypes @dtypes(torch.long, torch.float32, torch.complex64) def test_gradient_extreme_cases(self, device, dtype): # Test behaviour for inf and nan values actual = torch.gradient(torch.tensor([2, -2, inf, inf, -inf, -inf, inf, 3, -inf, 2, nan, nan, 3, inf, nan])) expected = np.gradient(np.array([2, -2, inf, inf, -inf, -inf, inf, 3, -inf, 2, nan, nan, 3, inf, nan])) self.assertEqual(actual, self._wrap_to_list(expected), exact_dtype=False) # Test behaviour in very big tensors large_size = 100000 t = make_tensor((large_size,), dtype=dtype, device=device) t_np = t.cpu().numpy() coordinates_np = list(np.random.randn(large_size)) coordinates = [torch.tensor(coordinates_np, device=device)] actual = torch.gradient(t, spacing=coordinates, dim=0, edge_order=1) expected = [np.gradient(t_np, coordinates_np, axis=0, edge_order=1)] self.assertEqual(actual, expected, exact_dtype=False) actual = torch.gradient(t, spacing=coordinates, dim=0, edge_order=2) expected = [np.gradient(t_np, coordinates_np, axis=0, edge_order=2)] self.assertEqual(actual, expected, exact_dtype=False) @onlyNativeDeviceTypes def test_gradient_type_promotion(self, device): inputs = ( make_tensor((4, 4), device=device, dtype=torch.float32), make_tensor((4, 4), device=device, dtype=torch.complex64), make_tensor((4, 4), device=device, dtype=torch.int64), ) spacing = ( make_tensor((1,), device='cpu', dtype=torch.float32).item(), make_tensor((1,), device='cpu', dtype=torch.int64).item(), make_tensor((1,), device='cpu', dtype=torch.complex64).item(), make_tensor((2,), device='cpu', dtype=torch.float32, low=0.1).tolist(), make_tensor((2,), device='cpu', dtype=torch.int64, low=1).tolist(), make_tensor((2,), device='cpu', dtype=torch.complex64).tolist(), [make_tensor((4,), device=device, dtype=torch.float32), make_tensor((4,), device=device, dtype=torch.float32)], [make_tensor((4,), device=device, dtype=torch.int64), make_tensor((4,), device=device, dtype=torch.int64)], [make_tensor((4,), device=device, dtype=torch.complex64), make_tensor((4,), device=device, dtype=torch.complex64)], ) for input, spacing_or_coord, edge_order in product(inputs, spacing, [1, 2]): input_np = input.cpu().numpy() input_np = input.cpu().numpy() actual = torch.gradient(input, spacing=spacing_or_coord, dim=(0, 1), edge_order=edge_order) spacing_or_coord_wrapped = self._wrap_to_list(spacing_or_coord) spacing_or_coord_np = [] if torch.is_tensor(spacing_or_coord_wrapped[0]) and torch.device(spacing_or_coord_wrapped[0].device).type != 'cpu': for i in range(len(spacing_or_coord_wrapped)): spacing_or_coord_np.append(spacing_or_coord_wrapped[i].detach().clone().cpu().numpy()) else: spacing_or_coord_np = spacing_or_coord_wrapped expected = np.gradient(input_np, *spacing_or_coord_np, axis=(0, 1), edge_order=edge_order) if actual[0].dtype == torch.complex64 and input.dtype != torch.complex64: for i in range(len(actual)): self.assertEqual(actual[i].real, expected[i].real, exact_dtype=False) # Type promotion fails on Numpy when spacing is given as complex number and input is given as real. # Result is given just as real number and all the imaginary parts to be equal to zero. self.assertEqual(expected[i].imag, torch.zeros(actual[i].shape), exact_dtype=False) else: actual, expected = self._inf_nan_preprocess(list(actual), expected) self.assertEqual(actual, expected, equal_nan=True, exact_dtype=False) def _test_large_cum_fn_helper(self, x, fn): x_cpu = x.cpu().float() expected = fn(x_cpu) actual = fn(x).cpu().float() self.assertEqual(expected, actual.cpu().float()) @unittest.skipIf(IS_FBCODE and IS_REMOTE_GPU, "sandcastle OOM with current tpx gpu/re configuration") @onlyCUDA @dtypes(torch.half) # only small dtype not to get oom def test_large_cumsum(self, device, dtype): # initialization to avoid overflow and half caveats x = torch.empty(2**30 + 200, device=device, dtype=dtype) x[::3] = -3 x[1::3] = 2 x[2::3] = 1 self._test_large_cum_fn_helper(x, lambda x: torch.cumsum(x, 0)) @onlyCUDA @dtypes(torch.half) # only small dtype not to get oom def test_large_cumprod(self, device, dtype): # initialization to avoid overflow and half caveats x = torch.empty(2**30 + 200, device=device, dtype=dtype) x[::3] = 8 x[1::3] = .25 x[2::3] = .5 self._test_large_cum_fn_helper(x, lambda x: torch.cumprod(x, 0)) @skipIfMps def test_discontiguous_out_cumsum(self, device): x = torch.randn(4, 8, device=device) y = torch.empty(4, 16, device=device)[:, ::2] out = torch.cumsum(x, 0) torch.cumsum(x, 0, out=y) self.assertFalse(y.is_contiguous()) self.assertEqual(out, y, atol=0., rtol=0.) def _test_cumminmax_helper(self, x, fn, expected_val, expected_ind): val, ind = fn(x, -1) self.assertEqual(val, expected_val, atol=0, rtol=0) self.assertEqual(ind, expected_ind, atol=0, rtol=0) out_val = torch.empty_like(val).t().contiguous().t() out_ind = torch.empty_like(ind).t().contiguous().t() fn(x, -1, out=(out_val, out_ind)) self.assertFalse(out_val.is_contiguous()) self.assertFalse(out_ind.is_contiguous()) self.assertEqual(out_val, expected_val, atol=0, rtol=0) self.assertEqual(out_ind, expected_ind, atol=0, rtol=0) @skipIfMps def test_cummax_discontiguous(self, device): x = torch.tensor([[0, 1, 2, 3, 2, 1], [4, 5, 6, 5, 6, 7]], device=device, dtype=torch.float).t().contiguous().t() expected_val = torch.tensor([[0, 1, 2, 3, 3, 3], [4, 5, 6, 6, 6, 7]], device=device, dtype=torch.float) expected_ind = torch.tensor([[0, 1, 2, 3, 3, 3], [0, 1, 2, 2, 4, 5]], device=device, dtype=torch.long) self._test_cumminmax_helper(x, torch.cummax, expected_val, expected_ind) @skipIfMps def test_cummin_discontiguous(self, device): x = torch.tensor([[3, 2, 1, 0, 1, 2], [7, 6, 5, 4, 5, 2]], device=device, dtype=torch.float).t().contiguous().t() expected_val = torch.tensor([[3, 2, 1, 0, 0, 0], [7, 6, 5, 4, 4, 2]], device=device, dtype=torch.float) expected_ind = torch.tensor([[0, 1, 2, 3, 3, 3], [0, 1, 2, 3, 3, 5]], device=device, dtype=torch.long) self._test_cumminmax_helper(x, torch.cummin, expected_val, expected_ind) def test_bool_tensor_value_change(self, device): x = torch.tensor([True, False], dtype=torch.bool, device=device) x[0] = False x[1] = True self.assertEqual(x, torch.tensor([False, True], dtype=torch.bool, device=device)) # FIXME: move to shape ops test suite def test_unfold_all_devices_and_dtypes(self, device): for dt in all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16): if dt == torch.bool: x = torch.empty((0, 1, 3, 0), dtype=dt, device=device) self.assertEqual((0, 1, 1, 0, 3), x.unfold(2, 3, 2).shape) else: x = torch.empty((0, 1, 3, 0), dtype=dt, device=device) self.assertEqual((0, 1, 1, 0, 3), x.unfold(2, 3, 2).shape) # FIXME: move to shape ops test suite def test_unfold_scalars(self, device): x = torch.tensor(0.5, device=device) # unfold on a 0-dimensional tensor should always return a 1-d dimensional # tensor of shape [size] (i.e., the second parameter to unfold) self.assertEqual(torch.empty(0, device=device), x.unfold(0, 0, 1)) self.assertEqual(torch.empty(0, device=device), x.unfold(0, 0, 2)) self.assertEqual(torch.tensor([0.5], device=device), x.unfold(0, 1, 1)) # FIXME: move to data movement test suite def test_copy_all_dtypes_and_devices(self, device): from copy import copy for dt in all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16): x = torch.tensor([1, 2, 3, 4], dtype=dt, device=device) x_clone = x.clone() y = copy(x) y.fill_(1) # copy is a shallow copy, only copies the tensor view, # not the data self.assertEqual(x, y) # FIXME: move to data movement test suite @onlyNativeDeviceTypes def test_copy_math_view(self, device): for dst_dtype, src_dtype in [ (torch.float32, torch.float32), (torch.float64, torch.float32), (torch.int64, torch.int32), (torch.complex128, torch.complex64), ]: src = make_tensor((100,), dtype=src_dtype, device=device) dst = torch.empty(100, dtype=dst_dtype, device=device) dst.copy_(src) self.assertEqual(dst, src, exact_dtype=False) dst.copy_(src._neg_view()) self.assertEqual(dst, src.neg(), exact_dtype=False) dst._neg_view().copy_(torch._neg_view(src)) self.assertEqual(dst, src, exact_dtype=False) dst._neg_view().copy_(src) self.assertEqual(dst, src.neg(), exact_dtype=False) for dst_dtype, src_dtype in [ (torch.complex64, torch.complex64), (torch.complex128, torch.complex64), ]: src = make_tensor((100,), dtype=src_dtype, device=device) dst = torch.empty(100, dtype=dst_dtype, device=device) dst.conj().copy_(src) self.assertEqual(dst, src.conj_physical(), exact_dtype=False) dst.conj().copy_(src._neg_view()) self.assertEqual(dst, src.neg().conj_physical(), exact_dtype=False) # FIXME: move to data movement test suite @onlyNativeDeviceTypes @dtypes(torch.int64, torch.float32, torch.complex64) def test_copy_transpose_math_view(self, device, dtype): src = make_tensor((100, 100), dtype=dtype, device=device).transpose(0, 1) dst = torch.empty((100, 100), dtype=dtype, device=device) dst._neg_view().copy_(src) self.assertEqual(dst, -src) dst._neg_view().copy_(src._neg_view()) self.assertEqual(dst, src) dst.copy_(src._neg_view()) self.assertEqual(dst, -src) if dtype.is_complex: dst.conj().copy_(src) self.assertEqual(dst, src.conj_physical()) dst.conj().copy_(src.conj()) self.assertEqual(dst, src) dst.copy_(src.conj()) self.assertEqual(dst, src.conj_physical()) def test_clone_all_dtypes_and_devices(self, device): for dt in all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16): x = torch.tensor((1, 1), dtype=dt, device=device) y = x.clone() self.assertEqual(x, y) def test_clone_zero_stride_dim(self, device): # stride zero, size 1 axis, not contiguous x = torch.randn(10) y = x.as_strided([2, 1, 5], [1, 0, 2]) self.assertEqual(y, y.clone()) def test_clone_not_memory_dense(self): # github issue: https://github.com/pytorch/pytorch/issues/64176 x = torch.randn(10, 8).t()[::2, ::2] y = x.clone() # should retain permutation after densification self.assertTrue(y.stride() == (1, 4)) # FIXME: move to elementwise ternary test suite @dtypesIfCUDA(*set(get_all_math_dtypes('cuda'))) @dtypes(*set(get_all_math_dtypes('cpu'))) def test_addcmul(self, device, dtype): # Returns floating or integral scalar corresponding to dtype def _number(floating, integer, dtype): if dtype in [torch.half, torch.float, torch.double, torch.bfloat16]: return floating elif dtype in [torch.cfloat, torch.cdouble]: return floating * (1 + 1j) else: return integer def rand_tensor(size, dtype, device): if dtype.is_floating_point or dtype.is_complex: return torch.rand(size=size, dtype=dtype, device=device) if dtype == torch.uint8: return torch.randint(1, 5, size=size, dtype=dtype, device=device) else: return torch.randint(-5, 5, size=size, dtype=dtype, device=device) a = rand_tensor((2, 2), dtype=dtype, device=device) b = rand_tensor((2, 2), dtype=dtype, device=device) c = rand_tensor((2, 2), dtype=dtype, device=device) alpha = _number(0.5, 3, dtype) actual = torch.addcmul(a, b, c, value=alpha) expected = a + alpha * b * c self.assertEqual(expected, actual) with self.assertWarnsOnceRegex( UserWarning, "This overload of addcmul is deprecated"): self.assertEqual(actual, torch.addcmul(a, alpha, b, c)) if self.device_type == 'cuda' and dtype == torch.half: a = torch.tensor([60000.0], device=device, dtype=dtype) b = torch.tensor([60000.0], device=device, dtype=dtype) c = torch.tensor([2.0], device=device, dtype=dtype) out = torch.addcmul(a, b, c, value=-1) self.assertTrue(not (out.isnan() or out.isinf())) # FIXME: move to shape ops test suite def test_narrow_empty(self, device): x = torch.randn(2, 3, 4, device=device) for d in range(x.dim()): y = x.narrow(d, x.size(d), 0) sz = list(x.size()) sz[d] = 0 self.assertEqual(sz, y.size()) # FIXME: move to indexing test suite @parametrize("reduce", ['prod', 'amin', 'amax', 'mean']) @dtypes(*floating_types_and(torch.half, torch.bfloat16)) def test_index_reduce(self, device, dtype, reduce): size = (3, 4, 5) index_dtypes = [torch.int, torch.long] include_selfs = [True, False] reduction_init = {'prod': 1, 'mean': 0, 'amin': float('inf'), 'amax': -float('inf')} for dest_contig, src_contig, index_contig in product([True, False], repeat=3): for idx_dtype, include_self in product(index_dtypes, include_selfs): for dim in range(len(size)): num_src = np.random.randint(10) num_dest = size[dim] dest = torch.randn(size, dtype=dtype, device=device) if not dest_contig: dest = make_tensor(size, device=device, dtype=dtype, noncontiguous=True) src = torch.randn(*size[:dim], num_src, *size[dim + 1:], dtype=dtype, device=device) if not src_contig: # noncontiguous_like fails with RuntimeError: XLA tensors do not have storage src = torch.testing.make_non_contiguous(src) idx = torch.randint(num_dest, (num_src,), dtype=idx_dtype, device=device) if not index_contig: # noncontiguous_like fails with RuntimeError: XLA tensors do not have storage idx = torch.testing.make_non_contiguous(idx) expected = dest.clone() dest.index_reduce_(dim, idx, src, reduce, include_self=include_self) # fill rows in idx with reduction inits if include_self=False if (not include_self): expected.index_fill_(dim, idx.long(), reduction_init[reduce]) expected = expected.transpose(0, dim) src = src.transpose(0, dim) for i in range(num_src): if reduce == 'prod': expected[idx[i]] *= src[i] elif reduce == 'amin': torch.minimum(expected[idx[i]], src[i], out=expected[idx[i]]) elif reduce == 'amax': torch.maximum(expected[idx[i]], src[i], out=expected[idx[i]]) else: expected[idx[i]] += src[i] if reduce == 'mean': counts = torch.ones_like(expected) if include_self else torch.zeros_like(expected) counts.index_add_(0, idx, torch.ones_like(src)) counts.masked_fill_(counts == 0, 1) expected /= counts expected = expected.transpose(0, dim) self.assertEqual(dest, expected) # FIXME: move to test indexing @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) def test_index_copy(self, device, dtype): # We just test for num_copy <= num_dest, as otherwise there are repeated indices # and the behavior is undefined num_copy, num_dest = 3, 5 def make_arg(batch_sizes, n, dim, contig): size_arg = batch_sizes[:dim] + (n,) + batch_sizes[dim:] return make_tensor(size_arg, dtype=dtype, device=device, low=None, high=None, noncontiguous=not contig) def ref_index_copy(tgt, dim, idx, src): for i in range(idx.size(0)): idx_dest = dim * (slice(None),) + (idx[i],) idx_src = dim * (slice(None),) + (i,) tgt[idx_dest] = src[idx_src] # More thorough testing as in index_add for dest_contig, src_contig, index_contig in product([True, False], repeat=3): for other_sizes in ((), (4, 5)): for dim in range(len(other_sizes)): dest = make_arg(other_sizes, num_dest, dim, dest_contig) src = make_arg(other_sizes, num_copy, dim, src_contig) idx = torch.randperm(num_dest, dtype=torch.int64, device=device)[:num_copy] if not index_contig: idx = torch.repeat_interleave(idx, 2, dim=-1) idx = idx[..., ::2] dest2 = dest.clone() dest.index_copy_(dim, idx, src) ref_index_copy(dest2, dim, idx, src) self.assertEqual(dest, dest2) # FIXME: move to test indexing # onlyNativeDeviceTypes due to an XLA error: # https://github.com/pytorch/pytorch/issues/53256 @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) def test_index_copy_scalars(self, device, dtype): # Create the 8 possible combinations of scalar sizes for target / index / source scalars = ((make_tensor(size_t, dtype=dtype, device=device, low=None, high=None), make_tensor(size_i, dtype=torch.int64, device=device, low=0, high=1), make_tensor(size_s, dtype=dtype, device=device, low=None, high=None)) for size_t, size_i, size_s in product([(), (1,)], repeat=3)) for target, idx, source in scalars: target.index_copy_(0, idx, source) self.assertEqual(target.item(), source.item()) # FIXME: move to test indexing @onlyCPU def test_errors_index_copy(self, device): # We do not test the GPU as the CUDA_ASSERT would break the CUDA context idx_dim = 8 tgt_dim = 5 batch_dim = 3 # Too large of an index a = torch.randn(batch_dim, tgt_dim, device=device) idx = torch.full((idx_dim,), tgt_dim, device=device) c = torch.zeros(batch_dim, idx_dim, device=device) with self.assertRaises(IndexError): a.index_copy_(1, idx, c) # Too small (negative indices) idx = torch.full((idx_dim,), -1, device=device) with self.assertRaises(IndexError): a.index_copy_(1, idx, c) # Too small (very negative indices) - they should be unsupported even # when support for negative indices is implemented for index_copy_ idx = torch.full((idx_dim,), -tgt_dim - 1, device=device) with self.assertRaises(IndexError): a.index_copy_(1, idx, c) def _prepare_data_for_index_copy_and_add_deterministic( self, dim: int, device: torch.device ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: assert (dim >= 0 and dim < 3) a = [5, 4, 3] a[dim] = 2000 x = torch.zeros(a, device=device) b = a.copy() elems = a[dim] * 20 b[dim] = elems src = torch.rand(b, device=device) index = torch.randint(a[dim], (elems,), device=device) return (x, index, src) # FIXME: move to test indexing @onlyNativeDeviceTypes def test_index_copy_deterministic(self, device: torch.device) -> None: for dim in range(3): x, index, src = self._prepare_data_for_index_copy_and_add_deterministic(dim, device) with DeterministicGuard(True): y0 = torch.index_copy(x, dim, index, src) x0 = x.clone().detach() index_list = index.tolist() for i in range(len(index_list)): if dim == 0: x0[index_list[i], :, :] = src[i, :, :] elif dim == 1: x0[:, index_list[i], :] = src[:, i, :] elif dim == 2: x0[:, :, index_list[i]] = src[:, :, i] self.assertEqual(x0, y0, atol=0, rtol=0) # FIXME: move to test indexing @onlyNativeDeviceTypes def test_index_add_deterministic(self, device: torch.device) -> None: for dim in range(3): x, index, src = self._prepare_data_for_index_copy_and_add_deterministic(dim, device) alpha = random.random() + 1 # on CPU it should be deterministic regardless of the deterministic mode with DeterministicGuard(True): y0 = torch.index_add(x, dim, index, src, alpha=alpha) for _ in range(3): y = torch.index_add(x, dim, index, src, alpha=alpha) self.assertEqual(y, y0, atol=0, rtol=0) with DeterministicGuard(False): for _ in range(3): y_nd = torch.index_add(x, dim, index, src, alpha=alpha) self.assertEqual(y_nd, y0, atol=1e-3, rtol=1e-5) # FIXME: find a test suite for the put operator @onlyNativeDeviceTypes def test_index_put_non_accumulate_deterministic(self, device) -> None: with DeterministicGuard(True): for i in range(3): m = random.randint(10, 20) elems = random.randint(20000, 30000) values = torch.rand(elems, device=device) indices = torch.randint(m, (elems,), device=device) input = torch.rand(m, device=device) output = input.index_put((indices,), values, accumulate=False) input_list = input.tolist() indices_list = indices.tolist() values_list = values.tolist() for i, v in zip(indices_list, values_list): input_list[i] = v self.assertEqual(output, input_list) # FIXME: move to test indexing @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) @skipIfMps def test_index_fill(self, device, dtype): x = torch.tensor([[1, 2], [4, 5]], dtype=dtype, device=device) index = torch.tensor([0], device=device) x.index_fill_(1, index, 0) self.assertEqual(x, torch.tensor([[0, 2], [0, 5]], dtype=dtype, device=device)) if not x.is_complex() and not device == "meta": with self.assertRaisesRegex(RuntimeError, r"Scalar"): x.index_fill_(1, index, 1 + 1j) # Make sure that the result stays 0-dim while applied to # a 0-dim input x = torch.tensor(1, dtype=dtype, device=device) self.assertEqual(0, x.index_fill(0, index, -1).dim()) self.assertEqual(0, x.index_fill_(0, index, -1).dim()) # FIXME: move to test indexing # The test fails for zero-dimensional tensors on XLA @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) def test_index_select(self, device, dtype): num_src, num_out = 3, 5 def make_arg(batch_sizes, n, dim, contig): size_arg = batch_sizes[:dim] + (n,) + batch_sizes[dim:] return make_tensor(size_arg, dtype=dtype, device=device, low=None, high=None, noncontiguous=not contig) def ref_index_select(src, dim, idx): # bfloat16 is just used on GPU, so it's not supported on numpy if dtype == torch.bfloat16: src = src.float() out = torch.from_numpy(np.take(src.cpu().numpy(), idx.cpu().numpy(), axis=dim)) if dtype == torch.bfloat16: out = out.to(device=device, dtype=dtype) return out for src_contig, idx_contig in product([True, False], repeat=2): for other_sizes in ((), (4, 5)): for dim in range(len(other_sizes)): src = make_arg(other_sizes, num_src, dim, src_contig) idx = make_tensor( (num_out,), dtype=torch.int64, device=device, low=0, high=num_src, noncontiguous=not idx_contig ) out = torch.index_select(src, dim, idx) out2 = ref_index_select(src, dim, idx) self.assertEqual(out, out2) for idx_type in (torch.int32, torch.int64): other_sizes = (3, 2) dim = 1 src = make_arg(other_sizes, num_src, dim, True) idx = make_tensor((num_out,), dtype=idx_type, device=device, low=0, high=num_src, noncontiguous=False) out = torch.index_select(src, dim, idx) out2 = ref_index_select(src, dim, idx) self.assertEqual(out, out2) # Create the 4 possible combinations of scalar sizes for index / source scalars = ((make_tensor(size_s, dtype=dtype, device=device), torch.zeros(size_i, dtype=torch.int64, device=device)) for size_s, size_i in product([(), (1,)], repeat=2)) for source, idx in scalars: out = source.index_select(0, idx) self.assertEqual(out.item(), source.item()) # FIXME: find a test suite for the take operator @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) def test_take(self, device, dtype): idx_size = (4,) make_arg = partial(make_tensor, device=device, dtype=dtype) make_idx = partial(make_tensor, low=0, device=device, dtype=torch.int64) def ref_take(src, idx): if dtype == torch.bfloat16: src = src.half() src = src.cpu().numpy() idx = idx.cpu().numpy() out = torch.from_numpy(np.take(src, idx)).to(device=device, dtype=dtype) return out for src_contig, idx_contig, idx_reshape in product([True, False], repeat=3): for src_size in ((5,), (4, 5)): src = make_arg(src_size, noncontiguous=not src_contig) idx = make_idx(idx_size, high=src.numel(), noncontiguous=not idx_contig) if idx_reshape: idx = idx.reshape(2, 2) out = torch.take(src, idx) out2 = ref_take(src, idx) self.assertEqual(out, out2) # Create the 4 possible combinations of scalar sizes for source / index for size_s, size_i in product([(), (1,)], repeat=2): source = make_arg(size_s) idx = make_idx(size_i, high=1) out = source.take(idx) self.assertEqual(out.item(), source.item()) # FIXME: find a test suite for the put operator # The bool instance does not work on GPU. See # https://github.com/pytorch/pytorch/issues/54317 @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16)) def test_put(self, device, dtype): src_size = (4,) make_arg = partial(make_tensor, device=device, dtype=dtype) make_idx = partial(make_tensor, low=0, device=device, dtype=torch.int64) def ref_put(dst, idx, src, accumulate): new_dst = dst.clone(memory_format=torch.contiguous_format).view(-1) new_idx = idx.contiguous().view(-1) new_src = src.contiguous().view(-1) method = new_dst.index_add_ if accumulate else new_dst.index_copy_ return method(0, new_idx, new_src).view_as(dst) for dst_contig, src_contig, idx_contig, idx_reshape, accumulate in product([True, False], repeat=5): for dst_size in ((5,), (4, 5)): dst = make_arg(dst_size, noncontiguous=not dst_contig) src = make_arg(src_size, noncontiguous=not src_contig) # If accumulate=True, `put_` should be deterministic regardless of the inputs on CPU # On CUDA it may not be, but the test has enough tolerance to account for this if accumulate: idx = make_idx(src_size, high=dst.numel()) else: idx = torch.randperm(dst.numel(), dtype=torch.int64, device=device)[:src_size[0]] if not idx_contig: idx = torch.repeat_interleave(idx, 2, dim=-1)[..., ::2] if idx_reshape: idx = idx.reshape(2, 2) out = torch.put(dst, idx, src, accumulate) # out-place reference = ref_put(dst, idx, src, accumulate) self.assertEqual(out, reference) # in-place dst.put_(idx, src, accumulate) self.assertEqual(dst, reference) # Create the 8 possible combinations of scalar sizes for target / index / source scalars = ((make_arg(size_t), make_idx(size_i, high=1), make_arg(size_s)) for size_t, size_i, size_s in product([(), (1,)], repeat=3)) for (dest, idx, source), accumulate in product(scalars, [True, False]): dest_init = dest.clone() # out-place out = torch.put(dest, idx, source, accumulate=accumulate) # in-place dest1 = dest.clone() dest1.put_(idx, source, accumulate=accumulate) for d in [out, dest1]: if accumulate: self.assertEqual(d.item(), (dest_init + source).item()) else: self.assertEqual(d.item(), source.item()) # Empty case dest = make_arg((3, 2)) reference = dest.clone() idx = make_idx((0,), high=1) source = make_arg((0,)) for accumulate in [True, False]: out = torch.put(dest, idx, source, accumulate=accumulate) self.assertEqual(out, reference) dest.put_(idx, source, accumulate=accumulate) self.assertEqual(dest, reference) # FIXME: find a test suite for the put operator # The bool instance does not work on GPU. See # https://github.com/pytorch/pytorch/issues/54317 @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16)) def test_put_accumulate(self, device, dtype): # Test for parallel adds with accumulate == True low_precision = dtype == torch.half or dtype == torch.bfloat16 # Less numbers to avoid overflow with low_precision # Grainsize is 3000 for the for_loop to be parallized on CPU sizes = ((100,)) if low_precision else ((200,), (3002,)) # Bfloat16 has a particularly bad performance here # This operation is nondeterministic on GPU, so we are generous with the rtol rtol, atol = (1e-1, 1e-2) if low_precision else (1e-3, 1e-4) make_arg = partial(make_tensor, low=-2, high=3, device=device, dtype=dtype) # Dump everything into the 0-th position make_idx = partial(torch.zeros, device=device, dtype=torch.int64) args = ((make_idx(size), make_arg(size)) for size in sizes) for idx, source in args: orig = make_arg((1,)) out = orig.put(idx, source, accumulate=True) self.assertEqual(out, orig + source.sum(), rtol=rtol, atol=atol) # FIXME: find a test suite for the take operator @skipIfMps def test_take_empty(self, device): for input_shape in [(0,), (0, 1, 2, 0), (1, 2, 3)]: for indices_shape in [(0,), (0, 1, 2, 0)]: input = torch.empty(input_shape, device=device) indices = torch.empty(indices_shape, dtype=torch.int64, device=device) self.assertEqual(indices, torch.take(input, indices), exact_dtype=False) # FIXME: find a test suite for the put operator def test_put_empty(self, device): for dst_shape in [(0,), (0, 1, 2, 0), (1, 2, 3)]: for indices_shape in [(0,), (0, 1, 2, 0)]: for accumulate in [False, True]: dst = torch.randn(dst_shape, device=device) indices = torch.empty(indices_shape, dtype=torch.int64, device=device) src = torch.randn(indices_shape, device=device) self.assertEqual(dst, dst.put_(indices, src, accumulate=accumulate)) # FIXME: port to test_scatter_gather_ops.py def scatter_allow_reduce(self, device, dtype, reduceop): device_type = torch.device(device).type return device_type != 'cuda' or (reduceop == 'multiply' and dtype.is_floating_point) @dtypes(*floating_and_complex_types()) @dtypesIfCPU(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) @dtypesIfCUDA(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) def test_scatter_reduce_operations_to_large_input(self, device, dtype): index = torch.tensor([[1], [2]], device=device, dtype=torch.long) test_data = [ (torch.zeros(4, 4, device=device, dtype=dtype), torch.ones(2, 2, device=device, dtype=dtype), torch.tensor([[0, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0]], device=device, dtype=dtype), "add"), (torch.tensor([2], device=device, dtype=dtype).repeat(4, 4), torch.tensor([6], device=device, dtype=dtype).repeat(2, 2), torch.tensor([[2, 2, 2, 2], [12, 2, 2, 2], [12, 2, 2, 2], [2, 2, 2, 2]], device=device, dtype=dtype), "multiply"), ] for input, src, result, operation in test_data: if not self.scatter_allow_reduce(device, dtype, operation): continue input.scatter_(0, index, src, reduce=operation) self.assertEqual(input, result) @dtypes(*floating_and_complex_types()) @dtypesIfCPU(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) @dtypesIfCUDA(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) def test_scatter_reduce_scalar(self, device, dtype): index = torch.tensor([[1], [2]], device=device, dtype=torch.long) test_data = [ (torch.zeros(4, 4, device=device, dtype=dtype), 1, torch.tensor([[0, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0]], device=device, dtype=dtype), "add"), (torch.tensor([2], device=device, dtype=dtype).repeat(4, 4), 2, torch.tensor([[2, 2, 2, 2], [4, 2, 2, 2], [4, 2, 2, 2], [2, 2, 2, 2]], device=device, dtype=dtype), "multiply"), ] for input, src, result, operation in test_data: if not self.scatter_allow_reduce(device, dtype, operation): continue input.scatter_(0, index, src, reduce=operation) self.assertEqual(input, result) # FIXME: port to test_scatter_gather_ops.py # TODO: remove this after scatter_add_ is deprecated. def test_scatter_add_non_unique_index(self, device): height = 2 width = 65536 input = torch.ones(height, width, device=device) index = torch.zeros(height, width, dtype=torch.long, device=device) src = torch.ones(height, width, device=device) input.scatter_add_(0, index, src) self.assertEqual(input, torch.tensor([[3], [1]], device=device, dtype=torch.float32).repeat(1, width)) @dtypes(*floating_and_complex_types()) @dtypesIfCPU(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) @dtypesIfCUDA(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) def test_scatter_reduce_non_unique_index(self, device, dtype): height = 2 width = 2 index = torch.zeros(height, width, dtype=torch.long, device=device) test_data = [ (torch.ones(height, width, device=device, dtype=dtype), torch.ones(height, width, device=device, dtype=dtype), torch.tensor([[3], [1]], device=device, dtype=dtype).repeat(1, width), "add"), (torch.tensor([2], device=device, dtype=dtype).repeat(height, width), torch.tensor([2], device=device, dtype=dtype).repeat(height, width), torch.tensor([[8], [2]], device=device, dtype=dtype).repeat(1, width), "multiply"), ] for input, src, result, operation in test_data: if not self.scatter_allow_reduce(device, dtype, operation): continue input.scatter_(0, index, src, reduce=operation) self.assertEqual(input, result, msg=f"result: {result} input: {input} method: {str(operation)}") @onlyCUDA @dtypes(*integral_types(), *complex_types()) def test_scatter_reduce_multiply_unsupported_dtypes(self, device, dtype): height = 2 width = 2 index = torch.zeros(height, width, dtype=torch.long, device=device) input = torch.ones(height, width, device=device, dtype=dtype) src = torch.ones(height, width, device=device, dtype=dtype) with self.assertRaises(RuntimeError): input.scatter_(0, index, src, reduce="multiply") # FIXME: port to test_scatter_gather_ops.py def test_scatter_to_large_input(self, device): input = torch.zeros(4, 4, device=device) src = torch.ones(2, 2, device=device) index = torch.tensor([[1], [2]], device=device, dtype=torch.long) input.scatter_(0, index, src) self.assertEqual(input, torch.tensor([[0, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0]], device=device, dtype=torch.float32)) # FIXME: port to test_scatter_gather_ops.py def test_scatter_add_to_large_input(self, device): input = torch.zeros(4, 4, device=device) src = torch.ones(2, 2, device=device) index = torch.tensor([[1], [2]], device=device, dtype=torch.long) input.scatter_add_(0, index, src) self.assertEqual(input, torch.tensor([[0, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0]], device=device, dtype=torch.float32)) # FIXME: port to test_scatter_gather_ops.py def test_scatter_bool(self, device): x = torch.tensor([[True, True, True], [True, True, True]], device=device) res = torch.zeros(3, 3, dtype=torch.bool, device=device) res = res.scatter_(0, torch.tensor([[0, 1, 2], [0, 1, 2]], device=device), x) self.assertEqual(res, torch.tensor([[True, False, False], [False, True, False], [False, False, True]], device=device)) # FIXME: port to test_scatter_gather_ops.py def test_scatter_add_bool(self, device): x = torch.tensor([[True, True, True, True, True], [True, True, True, True, True]], device=device) res = torch.zeros(3, 5, dtype=torch.bool, device=device) res = res.scatter_add_(0, torch.tensor([[0, 1, 2, 0, 0], [2, 0, 0, 1, 2]], device=device), x) self.assertEqual(res, torch.tensor([[True, True, True, True, True], [False, True, False, True, False], [True, False, True, False, True]], device=device)) # FIXME: find a test suite for the masked scatter operator @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) def test_masked_scatter(self, device, dtype): dt = dtype with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") for maskType in [torch.uint8, torch.bool]: num_copy, num_dest = 3, 10 dest = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=dt, device=device) dest2 = dest.clone() dest_ones = dest.clone() dest_ones_expected = dest.clone() src = torch.tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=dt, device=device) src_ones = torch.tensor([1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=dt, device=device) mask = torch.tensor((0, 0, 0, 0, 1, 0, 1, 0, 1, 0), dtype=maskType, device=device) if dt == torch.bool: # torch.bool is a special case and is being tested # in a separate test return dest.masked_scatter_(mask, src) j = 0 for i in range(num_dest): if mask[i]: dest2[i] = src[j] dest_ones_expected[i] = src_ones[j] j += 1 self.assertEqual(dest, dest2, atol=0, rtol=0) dest_ones.masked_scatter_(mask, src_ones) self.assertEqual(dest_ones, dest_ones_expected, atol=0, rtol=0) # Bound checking in CUDA is done inside a kernel # in order to avoid synchronization, but this means # we can not clear the failures. So there is no way # to test it then recover. if self.device_type != 'cuda': # make src smaller. this should fail src = torch.zeros(num_copy - 1, dtype=dt, device=device) with self.assertRaises(RuntimeError): dest.masked_scatter_(mask, src) # empty tensor dest = torch.empty((5, 0, 5), dtype=dt, device=device) mask = torch.ones_like(dest, dtype=maskType, device=device) src = torch.empty((0,), dtype=dt, device=device) dest.masked_scatter_(mask, src) dest = torch.empty((5, 0, 5), dtype=dt, device=device) mask = torch.ones((5, 1, 5), dtype=maskType, device=device) src = torch.empty((0,), dtype=dt, device=device) dest.masked_scatter_(mask, src) if self.device_type != 'cuda': self.assertEqual(len(w), 5) else: self.assertEqual(len(w), 4) warn = 'masked_scatter_ received a mask with dtype torch.uint8,' for wi in w: self.assertEqual(str(wi.message)[0:55], str(warn)) # FIXME: find a test suite for the masked scatter operator @skipIfMps def test_masked_scatter_bool_tensor(self, device): src = torch.tensor([True, True, True], device=device) dst = torch.tensor([False, False, False], device=device) mask = torch.tensor([False, True, False], device=device) dst.masked_scatter_(mask, src) self.assertEqual(dst, torch.tensor([False, True, False], device=device)) mask = torch.tensor([True, False, True], device=device) dst = dst.masked_scatter(mask, src) self.assertEqual(dst, torch.tensor([True, True, True], device=device)) # FIXME: find a test suite for the masked scatter operator # test_scatter_gather_ops or test_masked_ops? @onlyCUDA @largeTensorTest('30GB') def test_masked_scatter_large_tensor(self, device): t_cpu = torch.empty(2**31 + 1, dtype=torch.bool).random_() t = t_cpu.to(device) result_cpu = t_cpu.masked_scatter(t_cpu, t_cpu) result = t.masked_scatter(t, t) self.assertEqual(result, result_cpu) # FIXME: find a test suite for the masked select operator @dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16)) def test_masked_select(self, device, dtype): if device == 'cpu': warn = 'masked_select received a mask with dtype torch.uint8,' else: warn = 'indexing with dtype torch.uint8 is now deprecated, pl' for maskType in [torch.uint8, torch.bool]: num_src = 10 src = torch.tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=dtype, device=device) mask = torch.randint(2, (num_src,), device=device, dtype=maskType) with warnings.catch_warnings(record=True) as w: dst = src.masked_select(mask) if maskType is torch.uint8: self.assertEqual(len(w), 1) self.assertEqual(str(w[0].message)[0:53], str(warn)) dst2 = [] for i in range(num_src): if mask[i]: dst2 += [src[i]] self.assertEqual(dst, torch.tensor(dst2), atol=0, rtol=0) dst3 = torch.empty(0, device=device, dtype=dtype) torch.masked_select(src, mask, out=dst3) self.assertEqual(dst3, torch.tensor(dst2, dtype=dst3.dtype), atol=0, rtol=0) # Since half on CPU is not supported, need to skip the remaining test cases if dtype == torch.half and torch.device(device).type == 'cpu': return # Ensure that masks are expanded to match tensor properly a = torch.rand(100, 100, device=device).mul(100).to(dtype) mask_first_el_each_row = torch.zeros(100, device=device, dtype=torch.bool) mask_first_el_each_row[0] = True a_masked = a.masked_select(mask_first_el_each_row) self.assertEqual(a_masked, a[:, 0]) mask_first_row = torch.zeros(100, 1, device=device, dtype=torch.bool) mask_first_row[0][0] = True a_masked = a.masked_select(mask_first_row) self.assertEqual(a_masked, a[0, :]) # Ensure that tensor is expanded to match mask properly a = torch.rand(100, device=device).mul(100).to(dtype) mask_copy_3_times = torch.tensor([[True], [True], [False], [True]], device=device) a_masked = a.masked_select(mask_copy_3_times) self.assertEqual(a_masked, a.unsqueeze(0).expand(3, 100).flatten()) # FIXME: find a test suite for the masked select operator def test_masked_select_discontiguous(self, device): for size in (10, 200): vals = torch.rand(size, size, device=device) mask = torch.full((size, size), False, dtype=torch.bool, device=device) mask[:, ::2] = True vals_list = (vals, vals.t()) mask_list = (mask, mask.t()) out_dc = torch.empty(size * size, device=device)[::2] for v, m in product(vals_list, mask_list): if m.is_contiguous(): expected = v[:, ::2].clone().reshape((-1, )) else: expected = v[::2].clone().reshape((-1, )) out = torch.masked_select(v, m) self.assertEqual(out, expected, atol=0, rtol=0) torch.masked_select(v, m, out=out_dc) self.assertEqual(out_dc, expected, atol=0, rtol=0) # FIXME: find a test suite for the masked fill operator @dtypes(*product(all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16), (torch.uint8, torch.bool))) def test_masked_fill(self, device, dtypes): dtype = dtypes[0] mask_dtype = dtypes[1] with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") num_dest = 10 dst = torch.zeros(num_dest, dtype=dtype) mask = torch.randint(2, (num_dest,), dtype=mask_dtype) val = random.random() dst2 = dst.clone() dst.masked_fill_(mask, val) for i in range(num_dest): if mask[i]: dst2[i] = val self.assertEqual(dst, dst2, atol=0, rtol=0) # test non-contiguous case dst = ((torch.randn(num_dest, num_dest, num_dest) * 10).to(dtype)).permute((2, 0, 1)) dst2 = dst.contiguous() if dtype.is_complex: mask = dst.abs() > 0 else: mask = dst > 0 self.assertTrue(not dst.is_contiguous()) self.assertTrue(dst2.is_contiguous()) dst.masked_fill_(mask.to(mask_dtype), val) dst2.masked_fill_(mask.to(mask_dtype), val) self.assertEqual(dst, dst2, atol=0, rtol=0) if mask_dtype == torch.uint8: self.assertEqual(len(w), 3) warn = 'masked_fill_ received a mask with dtype torch.uint8,' for wi in w: self.assertEqual(str(wi.message)[0:52], str(warn)) else: self.assertEqual(len(w), 0) # FIXME: find a test suite for the masked fill operator def test_masked_fill_bool_tensor(self, device): dst = torch.tensor([True, False, True], device=device) mask = torch.tensor([False, True, False], device=device) dst.masked_fill_(mask, True) self.assertEqual(dst, torch.tensor([True, True, True], device=device)) dst = dst.masked_fill(mask, False) self.assertEqual(dst, torch.tensor([True, False, True], device=device)) def test_tensor_shape_empty(self, device): x = torch.randn((0, 1, 3, 0), device=device) # flatten self.assertEqual((0,), torch.flatten(x, 0, 3).shape) self.assertEqual((0, 0), torch.flatten(x, 0, 2).shape) self.assertEqual((0, 3, 0), torch.flatten(x, 1, 2).shape) # squeeze, unsqueeze self.assertEqual((0, 1, 1, 3, 0), torch.unsqueeze(x, 1).shape) self.assertEqual((0, 3, 0), torch.squeeze(x, 1).shape) self.assertEqual((0, 3, 0), torch.squeeze(x).shape) # transpose, t self.assertEqual((0, 0, 3, 1), torch.transpose(x, 1, 3).shape) y = torch.randn((5, 0), device=device) self.assertEqual((0, 5), y.t().shape) # select self.assertEqual((0, 1, 0), torch.select(x, 2, 2).shape) # repeat, permute self.assertEqual((9, 0, 5, 6, 0), x.repeat(9, 7, 5, 2, 3).shape) self.assertEqual((3, 0, 0, 1), x.permute(2, 3, 0, 1).shape) # diagonal, diagflat self.assertEqual((0,), torch.diagonal(torch.randn((5, 0), device=device)).shape) self.assertEqual((0,), torch.diagonal(torch.randn((0, 5), device=device)).shape) # off the end offsets are valid self.assertEqual((0,), torch.diagonal(torch.randn((5, 0), device=device), offset=1).shape) self.assertEqual((0,), torch.diagonal(torch.randn((0, 5), device=device), offset=1).shape) # check non-zero sized offsets off the end self.assertEqual((5, 6, 0), torch.diagonal(torch.randn((3, 4, 5, 6), device=device), offset=45252).shape) self.assertEqual((5, 6, 0), torch.diagonal(torch.randn((3, 4, 5, 6), device=device), offset=-45252).shape) self.assertEqual((0, 0), torch.diagflat(torch.tensor([], device=device)).shape) self.assertEqual(torch.zeros(1, 1), torch.diagflat(torch.tensor([], device=device), offset=1)) self.assertEqual((0, 0), torch.diagflat(torch.tensor([[]], device=device)).shape) self.assertEqual(torch.zeros(1, 1), torch.diagflat(torch.tensor([[]], device=device), offset=1)) # stack, split, chunk self.assertEqual((4, 0, 1, 3, 0), torch.stack((x, x, x, x)).shape) self.assertEqual([(0, 1, 3, 0)], [z.shape for z in torch.chunk(x, 1, dim=0)]) self.assertEqual([(0, 1, 3, 0), ] * 3, [z.shape for z in torch.chunk(x, 3, dim=0)]) self.assertEqual([(0, 1, 1, 0), ] * 3, [z.shape for z in torch.chunk(x, 3, dim=2)]) # NOTE: split_with_sizes behaves differently than NumPy in that it # takes sizes rather than offsets self.assertEqual([(0, 1, 0, 0), (0, 1, 1, 0), (0, 1, 2, 0)], [z.shape for z in torch.split(x, (0, 1, 2), dim=2)]) self.assertRaises(RuntimeError, lambda: torch.split(x, 0, dim=1)) # This is strange because the split size is larger than the dim size, but consistent with # how split handles that case generally (when no 0s are involved). self.assertEqual([(0, 1, 3, 0)], [z.shape for z in torch.split(x, 1, dim=0)]) self.assertEqual([(0, 1, 3, 0)], [z.shape for z in torch.split(x, 0, dim=0)]) # functions that operate over a dimension but don't reduce. def test_dim_function_empty(self, device): shape = (0, 1, 2, 0) x = torch.randn(shape, device=device) # size stride self.assertEqual(0, x.size(3)) self.assertEqual(2, x.size(2)) self.assertEqual(2, x.stride(0)) self.assertEqual(1, x.stride(2)) self.assertEqual(x, torch.nn.functional.glu(x, 0)) self.assertEqual((0, 1, 1, 0), torch.nn.functional.glu(x, 2).shape) # softmax, logsoftmax self.assertEqual(x, torch.nn.functional.softmax(x, 0)) self.assertEqual(x, torch.nn.functional.softmax(x, 2)) self.assertEqual(x, torch.nn.functional.softmax(x, 3)) self.assertEqual(x, torch.nn.functional.log_softmax(x, 0)) self.assertEqual(x, torch.nn.functional.log_softmax(x, 2)) self.assertEqual(x, torch.nn.functional.log_softmax(x, 3)) # cumsum, cumprod, cummax, cummin self.assertEqual(shape, torch.cumsum(x, 0).shape) self.assertEqual(shape, torch.cumsum(x, 2).shape) self.assertEqual(shape, torch.cumprod(x, 0).shape) self.assertEqual(shape, torch.cumprod(x, 2).shape) self.assertEqual(shape, torch.cummax(x, 0)[0].shape) self.assertEqual(shape, torch.cummax(x, 2)[0].shape) self.assertEqual(shape, torch.cummin(x, 0)[0].shape) self.assertEqual(shape, torch.cummin(x, 2)[0].shape) self.assertEqual(shape, torch.logcumsumexp(x, 0).shape) self.assertEqual(shape, torch.logcumsumexp(x, 2).shape) # flip self.assertEqual(x, x.flip(0)) self.assertEqual(x, x.flip(2)) # roll self.assertEqual(x, x.roll(0, 1).roll(0, -1)) self.assertEqual(x, x.roll(1, x.size(1))) self.assertEqual(x, x.roll(1)) self.assertEqual(x, x.roll((1, 1), (3, 1))) # unbind self.assertEqual((), x.unbind(0)) self.assertEqual((torch.empty((0, 1, 0), device=device), torch.empty((0, 1, 0), device=device)), x.unbind(2)) # cross y = torch.randn((0, 1, 3, 0), device=device) self.assertEqual(y.shape, torch.cross(y, y).shape) # renorm self.assertEqual(shape, torch.renorm(x, 1, 0, 5).shape) self.assertEqual(shape, torch.renorm(x, 1, 2, 5).shape) # sort self.assertEqual([shape, shape], [z.shape for z in torch.sort(x, dim=0)]) self.assertEqual([shape, shape], [z.shape for z in torch.sort(x, dim=2)]) # topk self.assertEqual([shape, shape], [z.shape for z in torch.topk(x, 0, dim=0)]) self.assertEqual([(0, 1, 1, 0), (0, 1, 1, 0)], [z.shape for z in torch.topk(x, 1, dim=2)]) y = torch.randn((2, 3, 4), device=device) self.assertEqual([(2, 3, 0), (2, 3, 0)], [z.shape for z in torch.topk(y, 0)]) # gather self.assertEqual(shape, torch.gather(x, 0, torch.empty(shape, dtype=torch.int64, device=device)).shape) self.assertEqual(shape, torch.gather(x, 2, torch.empty(shape, dtype=torch.int64, device=device)).shape) larger_shape = torch.empty((0, 1, 3, 0), dtype=torch.int64, device=device) self.assertEqual(larger_shape.shape, torch.gather(x, 2, larger_shape).shape) smaller_shape = torch.empty((0, 1, 0, 0), dtype=torch.int64, device=device) self.assertEqual(smaller_shape.shape, torch.gather(x, 2, smaller_shape).shape) y = torch.randn((2, 3, 4), device=device) self.assertEqual((0, 3, 4), torch.gather(y, 0, torch.empty((0, 3, 4), dtype=torch.int64, device=device)).shape) # scatter, scatter_add for dim in [0, 2]: y = torch.randn(shape, device=device) y_src = torch.randn(shape, device=device) ind = torch.empty(shape, dtype=torch.int64, device=device) self.assertEqual(shape, y.scatter_(dim, ind, y_src).shape) self.assertEqual(shape, y.scatter_add_(dim, ind, y_src).shape) z = torch.randn((2, 3, 4), device=device) z_src = torch.randn((2, 3, 4), device=device) self.assertEqual(z, z.scatter_(2, torch.empty((2, 3, 0), dtype=torch.int64, device=device), z_src)) self.assertEqual(z, z.scatter_add_(2, torch.empty((2, 3, 0), dtype=torch.int64, device=device), z_src)) # index_fill, index_copy, index_add c = x.clone() c_clone = c.clone() ind_empty = torch.tensor([], dtype=torch.int64, device=device) ind_01 = torch.tensor([0, 1], dtype=torch.int64, device=device) self.assertEqual(c_clone, c.index_fill_(0, ind_empty, -1)) self.assertEqual(c_clone, c.index_fill_(2, ind_empty, -1)) self.assertEqual(c_clone, c.index_fill_(2, ind_01, -1)) self.assertEqual(c_clone, c.index_copy_(0, ind_empty, torch.empty((0, 1, 2, 0), device=device))) self.assertEqual(c_clone, c.index_copy_(2, ind_empty, torch.empty((0, 1, 0, 0), device=device))) self.assertEqual(c_clone, c.index_copy_(2, ind_01, torch.empty((0, 1, 2, 0), device=device))) self.assertEqual(c_clone, c.index_add_(0, ind_empty, torch.empty((0, 1, 2, 0), device=device))) self.assertEqual(c_clone, c.index_add_(2, ind_empty, torch.empty((0, 1, 0, 0), device=device))) self.assertEqual(c_clone, c.index_add_(2, ind_01, torch.empty((0, 1, 2, 0), device=device))) c = torch.randn((0, 1, 2), device=device) c_clone = c.clone() self.assertEqual(c_clone, c.index_fill_(0, ind_empty, -1)) self.assertEqual(c_clone, c.index_copy_(0, ind_empty, torch.empty((0, 1, 2), device=device))) self.assertEqual(c_clone, c.index_add_(0, ind_empty, torch.empty((0, 1, 2), device=device))) self.assertEqual(c_clone, c.index_fill_(0, ind_empty, -1)) self.assertEqual(c_clone, c.index_copy_(0, ind_empty, torch.empty((0, 1, 2), device=device))) self.assertEqual(c_clone, c.index_add_(0, ind_empty, torch.empty((0, 1, 2), device=device))) # index fill/copy/add non-empty z = torch.randn((2, 3, 4), device=device) self.assertEqual(z, z.index_fill_(0, ind_empty, -1)) z = torch.randn((2, 3, 4), device=device) self.assertEqual(z, z.index_copy_(0, ind_empty, torch.empty((0, 3, 4), device=device))) z = torch.randn((2, 3, 4), device=device) self.assertEqual(z, z.index_add_(0, ind_empty, torch.empty((0, 3, 4), device=device))) # index_select self.assertEqual(x, x.index_select(0, ind_empty)) self.assertEqual((0, 1, 0, 0), x.index_select(2, ind_empty).shape) self.assertEqual(x, x.index_select(2, ind_01)) z = torch.randn((2, 3, 4), device=device) # non-empty self.assertEqual((0, 3, 4), z.index_select(0, ind_empty).shape) c = torch.randn((0, 1, 2), device=device) self.assertEqual(c, c.index_select(0, ind_empty)) c = torch.randn((0, 1, 2), device=device) self.assertEqual(c, c.index_select(0, ind_empty)) w = torch.randn((0, 3), device=device) self.assertEqual((0, 2), w.index_select(1, ind_01).shape) w = torch.randn((3, 0), device=device) self.assertEqual((2, 0), w.index_select(0, ind_01).shape) ind_01_int32 = torch.tensor([0, 1], dtype=torch.int32, device=device) self.assertEqual((2, 0), w.index_select(0, ind_01_int32).shape) if device == 'cpu': w = torch.randn((0, 3), device=device) with self.assertRaisesRegex(RuntimeError, "self indexing axis dim should be positive"): torch.index_select(w, 0, ind_01) ind_05 = torch.tensor([0, 5], dtype=torch.int64, device=device) with self.assertRaisesRegex(RuntimeError, "INDICES element is out of DATA bounds"): torch.index_select(w, 1, ind_05) # FIXME: find a test suite for the pdist operator def _brute_pdist(self, inp, p=2): """Computes the same as torch.pdist using primitives""" n = inp.shape[-2] k = n * (n - 1) // 2 if k == 0: # torch complains about empty indices return torch.empty(inp.shape[:-2] + (0,), dtype=inp.dtype, device=inp.device) square = torch.norm(inp[..., None, :] - inp[..., None, :, :], p=p, dim=-1) unroll = square.view(square.shape[:-2] + (n * n,)) inds = torch.ones(k, dtype=torch.int) inds[torch.arange(n - 1, 1, -1, dtype=torch.int).cumsum(0)] += torch.arange(2, n, dtype=torch.int) return unroll[..., inds.cumsum(0)] # FIXME: find a test suite for the pdist operator def _pdist_single(self, shape, device, p, dtype, trans, grad_check=False): x = torch.randn(shape, dtype=dtype, device=device) if trans: x.transpose_(-2, -1) if grad_check: x.requires_grad_() y = x.detach().clone().requires_grad_() else: y = x actual = torch.pdist(x, p=p) expected = self._brute_pdist(y, p=p) self.assertEqual(expected.shape, actual.shape) self.assertEqual(expected, actual) if grad_check and expected.size() != torch.Size([0]): g0 = torch.rand_like(actual) actual.backward(g0) expected.backward(g0) self.assertEqual(x.grad, y.grad) # FIXME: find a test suite for the pdist operator @slowTest def test_pdist_norm_forward(self, device): for shape in [(4, 5), (3, 2), (2, 1), (1500, 1)]: for p in [0, 1, 2, 3, 1.5, 2.5, float('inf')]: for trans in [False, True]: for dtype in [torch.float32, torch.float64]: self._pdist_single(shape, device, p, dtype, trans, grad_check=False) # do a simplified comparison with big inputs, see: # https://github.com/pytorch/pytorch/issues/15511 for dtype in [torch.float32, torch.float64]: self._pdist_single((1000, 2), device, 2, dtype, trans=False, grad_check=False) # FIXME: find a test suite for the pdist operator @slowTest def test_pdist_norm_backward(self, device): for shape in [(4, 5), (3, 2), (2, 1), (1500, 1)]: for p in [0, 1, 2, 3, 1.5, 2.5, float('inf')]: for trans in [False, True]: self._pdist_single(shape, device, p, torch.float64, trans, grad_check=True) # FIXME: find a test suite for the pdist operator @unittest.skipIf(IS_FBCODE and IS_REMOTE_GPU, "sandcastle OOM with current tpx gpu/re configuration") @skipIfRocm @onlyCUDA @largeTensorTest('10GB', device='cpu') @largeTensorTest('5GB', device='cuda') def test_pdist_norm_large(self, device): # use dim0>=46342 for forward, see: # https://github.com/pytorch/pytorch/issues/30583 # Compare output using GPU with the CPU implementation, as brute_pdist uses too much memory x = torch.randn(50000, 1, dtype=torch.float32) # 50k * 4 bytes = 200 KB # Will require 1249975000 float32s expected_cpu = torch.pdist(x, p=2) # ~1250M * 4 bytes = 5 GB on CPU actual_gpu = torch.pdist(x.to(device), p=2) # 5 GB on GPU self.assertEqual(expected_cpu, actual_gpu.cpu()) # Another 5 GB on CPU # FIXME: move to elementwise ternary test suite @onlyNativeDeviceTypes @dtypesIfCUDA(*set(get_all_math_dtypes('cuda'))) @dtypes(*set(get_all_math_dtypes('cpu'))) def test_addcdiv(self, device, dtype): # Returns floating or integral scalar corresponding to dtype def _number(floating, integer, dtype): if dtype in [torch.half, torch.float, torch.double, torch.bfloat16]: return floating elif dtype in [torch.cfloat, torch.cdouble]: return floating * (1 + 1j) else: return integer def non_zero_rand(size, dtype, device): if dtype.is_floating_point or dtype.is_complex: a = torch.rand(size=size, dtype=dtype, device=device) elif dtype == torch.uint8: a = torch.randint(1, 5, size=size, dtype=dtype, device=device) else: a = torch.randint(-5, 5, size=size, dtype=dtype, device=device) return a + (a == 0).to(dtype) def _test_addcdiv(): a = non_zero_rand((2, 2), dtype=dtype, device=device) b = non_zero_rand((2, 2), dtype=dtype, device=device) c = non_zero_rand((2, 2), dtype=dtype, device=device) alpha = _number(0.5, 3, dtype) expected = a + (alpha * b) / c actual = torch.addcdiv(a, b, c, value=alpha) self.assertEqual(expected, actual) with self.assertWarnsOnceRegex( UserWarning, "This overload of addcdiv is deprecated"): self.assertEqual(actual, torch.addcdiv(a, alpha, b, c)) if not (dtype.is_floating_point or dtype.is_complex): # Integer division with addcdiv is prohibited with self.assertRaises(RuntimeError): _test_addcdiv() else: _test_addcdiv() if self.device_type == 'cuda' and dtype == torch.half: a = torch.tensor([60000.0], device=device, dtype=dtype) b = torch.tensor([60000.0], device=device, dtype=dtype) c = torch.tensor([1.0], device=device, dtype=dtype) out = torch.addcmul(a, b, c, value=-2) self.assertTrue(not (out.isnan() or out.isinf())) def test_nullary_op_mem_overlap(self, device): ops = ( ("random_", ()), ("uniform_", ()), ("cauchy_", ()), ("log_normal_", ()), ("exponential_", ()), ("geometric_", (0.5,)), ("normal_", ()), ) x = torch.rand((1, 3)).expand((3, 3)) for op, args in ops: with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): getattr(x, op)(*args) # FIXME: move to an elementwise ternary test suite and make this an OpInfo test @dtypes(torch.double) def test_ternary_op_mem_overlap(self, device, dtype): ops = [ ("addcmul", True, True, 'cpu'), ("addcmul", True, True, 'cuda'), ("addcdiv", True, True, 'cpu'), ("addcdiv", True, True, 'cuda'), ("lerp", True, True, 'cpu'), ("lerp", True, True, 'cuda') ] for (fn, has_input_output_mem_overlap_check, has_internal_mem_overlap_check, dev) in ops: if dev != device: continue out_op = getattr(torch, fn) inplace_op = getattr(torch.Tensor, fn + '_') self.check_internal_mem_overlap( inplace_op, 3, dtype, device, expected_failure=not has_internal_mem_overlap_check) self.ternary_check_input_output_mem_overlap(out_op, dev, expected_failure=not has_input_output_mem_overlap_check) @expectedFailureMeta # RuntimeError not raised @dtypes(torch.double) @onlyNativeDeviceTypes def test_copy_mem_overlap(self, device, dtype): self.check_internal_mem_overlap( torch.Tensor.copy_, num_inputs=2, dtype=dtype, device=device) sz = 9 doubles = torch.randn(2 * sz, dtype=dtype, device=device) self.unary_check_input_output_mem_overlap( doubles, sz, lambda input, out: out.copy_(input)) # FIXME: convert to ErrorInputs @onlyNativeDeviceTypes def test_index_add_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) y = torch.rand((6,), device=device) ind = torch.tensor([2, 1, 0], device=device) value = torch.rand((3,), device=device) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.index_add_(0, ind, value) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): y.index_add_(0, ind, y[:3]) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_add_(0, ind, ind.clone()) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_add_(0, ind.clone(), ind) # FIXME: convert to ErrorInputs @onlyNativeDeviceTypes def test_index_copy_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) y = torch.rand((6,), device=device) ind = torch.tensor([2, 1, 0], device=device) value = torch.rand((3,), device=device) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.index_copy_(0, ind, value) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): y.index_copy_(0, ind, y[:3]) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_copy_(0, ind, ind.clone()) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_copy_(0, ind.clone(), ind) # FIXME: convert to ErrorInputs @expectedFailureMeta # Warning not triggered @onlyNativeDeviceTypes def test_index_fill_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) y = torch.rand((6,), device=device) ind = torch.tensor([2, 1, 0], device=device) value = torch.rand((3,), device=device) with self.assertWarnsRegex(UserWarning, "index_fill_ on expanded tensors"): x.index_fill_(0, ind, 1.0) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_fill_(0, ind, 0) # FIXME: convert to ErrorInputs @expectedFailureMeta # RuntimeError not raised @onlyNativeDeviceTypes def test_shift_mem_overlap(self, device): x = torch.rand(3, device=device) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x[:-1] <<= x[1:] with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x[:-1] >>= x[1:] # FIXME: convert to ErrorInputs @expectedFailureMeta # RuntimeError not raised @onlyNativeDeviceTypes def test_bernoulli_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.bernoulli_() with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.bernoulli_(p=0.1) p = torch.rand(6, device=device) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.bernoulli_(p=p) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): torch.bernoulli(torch.rand_like(x), out=x) # FIXME: convert to ErrorInputs @expectedFailureMeta # RuntimeError not raised @onlyNativeDeviceTypes def test_put_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) y = torch.rand((6,), device=device) ind = torch.tensor([2, 1, 0], device=device) value = torch.rand((3,), device=device) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.put_(ind, value) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): y.put_(ind[0], y[0]) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.put_(ind, ind) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): y.put_(ind, y[:3]) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.put_(ind, ind.clone()) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.put_(ind.clone(), ind) # FIXME: convert to ErrorInputs @expectedFailureMeta # UserWarning not triggered @onlyNativeDeviceTypes def test_index_put_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) y = torch.rand((6,), device=device) ind = torch.tensor([2, 1, 0], device=device) value = torch.rand((3,), device=device) with self.assertWarnsRegex(UserWarning, 'expanded tensors'): x.index_put_((ind,), value) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): y.index_put_((ind,), y[0]) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_put_((ind,), ind) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): y.index_put_((ind,), y[:3]) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_put_((ind,), ind.clone()) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.index_put_((ind.clone(),), ind) # FIXME: convert to ErrorInputs @expectedFailureMeta # UserWarning not triggered @onlyNativeDeviceTypes def test_masked_fill_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) mask = torch.tensor([True, False, True, True, False, False], device=device) with self.assertWarnsRegex(UserWarning, 'expanded tensors'): x.masked_fill_(mask, 0.) fill_val = torch.tensor(0., device=device) with self.assertWarnsRegex(UserWarning, 'expanded tensors'): x.masked_fill_(mask, fill_val) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): mask[1:].masked_fill_(mask[:-1], False) # FIXME: convert to ErrorInputs @expectedFailureMeta # RuntimeError not raised @onlyNativeDeviceTypes def test_masked_scatter_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) src = torch.rand((3,), device=device) mask = torch.tensor([True, False, True, True, False, False], device=device) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.masked_scatter_(mask, src) # FIXME: convert to ErrorInputs @onlyNativeDeviceTypes def test_scatter_mem_overlap(self, device): x = torch.rand((1,), device=device).expand((6,)) src = torch.rand((3,), device=device) ind = torch.tensor([2, 1, 0], device=device, dtype=torch.int64) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): x.scatter_(0, ind, src) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): src.scatter_(0, ind, src) with self.assertRaisesRegex(RuntimeError, 'unsupported operation'): ind.scatter_(0, ind, ind.clone()) # FIXME: move to test distributions @onlyCUDA def test_multinomial_device_constrain(self, device): x = torch.empty(0, device="cpu") y = torch.empty(0, device=device) self.assertRaisesRegex( RuntimeError, "Expected all tensors to be on the same device", lambda: torch.multinomial(x, 2, out=y)) # FIXME: move to test distributions @deviceCountAtLeast(2) @onlyCUDA def test_multinomial_gpu_device_constrain(self, devices): x = torch.empty(0, device=devices[0]) y = torch.empty(0, device=devices[1]) self.assertRaisesRegex( RuntimeError, "Expected all tensors to be on the same device", lambda: torch.multinomial(x, 2, out=y)) # FIXME: convert this to an automated OpInfo test @deviceCountAtLeast(2) @onlyCUDA def test_device_guard(self, devices): # verify that all operators with `device_guard: False` behave properly with multiple devices. # TODO: if we had operator introspection we could figure out this set of operators automatically... x = torch.randn((1, 2, 3), device=devices[1]) y = torch.zeros((1, 3, 2), device=devices[1]) scalar = torch.tensor(5, device=devices[1]) # property ops torch.cudnn_is_acceptable(x) x.is_distributed() x.is_floating_point() x.is_complex() x.is_same_size(y) x.is_signed() x.size(0) x.stride(0) x.numel() x.is_set_to(y) x.data_ptr() scalar.is_nonzero() # sparse property ops y[0][1] = 5 y_sparse = y.to_sparse() y_sparse.sparse_dim() y_sparse._dimI() y_sparse.dense_dim() y_sparse._dimV() y_sparse._nnz() y_sparse.is_coalesced() y_sparse._indices() y_sparse._values() y_sparse.indices() y_sparse.values() # in-place ops def inplace(): return torch.randn((1, 2, 3), device=devices[1]) inplace().as_strided_(y.size(), y.stride()) inplace().resize_(y.size()) inplace().squeeze_() inplace().squeeze_(0) inplace().unsqueeze_(2) inplace().transpose_(1, 2) inplace().squeeze_().t_() inplace().set_(x.storage()) inplace().set_(x.storage(), x.storage_offset(), x.size(), x.stride()) inplace().set_(x) inplace().set_() y_sparse._coalesced_(True) # shape modification x.as_strided(y.size(), y.stride()) x.expand((5, 2, 3)) x.expand_as(x) x.sum_to_size((1,)) torch.broadcast_tensors(x , x) x.reshape((1, 3, 2)) x.reshape_as(y) x.squeeze() x.squeeze(0) x.squeeze().t() x.transpose(1, 2) x.unsqueeze(2) x.view((1, 3, 2)) x.view_as(y) # chunk, split, etc. x.chunk(2, dim=1) x.split(1, dim=2) x.split_with_sizes([1, 2], dim=2) x.unfold(dimension=2, size=1, step=1) x.narrow(1, 1, 1) x.select(1, 1) torch.isnan(x) torch.empty((1, 3, 2), out=y) torch.empty_like(x) torch.empty_like(x, dtype=torch.int64) # to x.to(x) x.to(y) x.to(x, copy=True) def test_is_signed(self, device): self.assertEqual(torch.IntTensor(5).to(device).is_signed(), True) self.assertEqual(torch.ByteTensor(5).to(device).is_signed(), False) self.assertEqual(torch.CharTensor(5).to(device).is_signed(), True) self.assertEqual(torch.FloatTensor(5).to(device).is_signed(), True) self.assertEqual(torch.HalfTensor(10).to(device).is_signed(), True) # Note - reports a leak of 512 bytes on CUDA device 1 @deviceCountAtLeast(2) @skipCUDAMemoryLeakCheckIf(True) @onlyCUDA def test_tensor_set_errors_multigpu(self, devices): f_cuda0 = torch.randn((2, 3), dtype=torch.float32, device=devices[0]) f_cuda1 = torch.randn((2, 3), dtype=torch.float32, device=devices[1]) self.assertRaises(RuntimeError, lambda: f_cuda0.set_(f_cuda1.storage())) self.assertRaises(RuntimeError, lambda: f_cuda0.set_(f_cuda1.storage(), 0, f_cuda1.size(), f_cuda1.stride())) self.assertRaises(RuntimeError, lambda: f_cuda0.set_(f_cuda1)) # FIXME: move to test_serialization @onlyCUDA @deviceCountAtLeast(1) # Note: Tests works with one but prefers more devices def test_serialization(self, devices): def _test_serialization(filecontext_lambda): t0 = torch.cuda.FloatTensor(5).fill_(1) with torch.cuda.device(devices[-1]): tn = torch.cuda.FloatTensor(3).fill_(2) torch.cuda.set_device(devices[0]) b = (t0, tn) with filecontext_lambda() as f: torch.save(b, f) f.seek(0) c = torch.load(f) self.assertEqual(b, c, atol=0, rtol=0) u0, un = c self.assertEqual(str(u0.device), devices[0]) self.assertEqual(str(un.device), devices[-1]) _test_serialization(tempfile.NamedTemporaryFile) _test_serialization(BytesIOContext) # FIXME: move memory format tests to their own test class/suite def test_memory_format_preserved_after_permute(self, device): x = torch.randn(4, 3, 8, 8, device=device) nhwc = x.contiguous(memory_format=torch.channels_last) y = nhwc.permute(0, 1, 3, 2).permute(0, 1, 3, 2) self.assertTrue(y.is_contiguous(memory_format=torch.channels_last)) x = torch.randn(4, 3, 8, 8, 8, device=device) ndhwc = x.contiguous(memory_format=torch.channels_last_3d) y = ndhwc.permute(0, 1, 4, 3, 2).permute(0, 1, 4, 3, 2) self.assertTrue(y.is_contiguous(memory_format=torch.channels_last_3d)) def test_memory_format_propagation_rules(self, device): contiguous = torch.rand(10, 3, 5, 5, device=device) cl = torch.rand(10, 3, 5, 5, device=device).contiguous(memory_format=torch.channels_last) ambiguous = torch.rand(10, 3, 1, 1, device=device).contiguous(memory_format=torch.channels_last) self.assertTrue(ambiguous.is_contiguous(memory_format=torch.channels_last)) self.assertTrue(ambiguous.is_contiguous(memory_format=torch.contiguous_format)) bias = torch.rand(1, 1, 1, 1, device=device).contiguous(memory_format=torch.channels_last) def _test_propagation_rules(self, contiguous, cl, ambiguous, bias): options = ((ambiguous, contiguous, torch.contiguous_format), (ambiguous, cl, torch.channels_last), (contiguous, ambiguous, torch.contiguous_format), (contiguous, cl, torch.contiguous_format), (cl, ambiguous, torch.channels_last), (cl, contiguous, torch.channels_last), (bias, cl, torch.channels_last), (cl, bias, torch.channels_last),) for a, b, mf in options: result = a + b self.assertTrue(result.is_contiguous(memory_format=mf)) _test_propagation_rules(self, contiguous, cl, ambiguous, bias) cl = cl.to(memory_format=torch.channels_last) ambiguous = ambiguous.to(memory_format=torch.channels_last) bias = bias.to(memory_format=torch.channels_last) _test_propagation_rules(self, contiguous, cl, ambiguous, bias) # test cases when strides matter in ambiguous tensors for mf in (torch.channels_last, torch.contiguous_format): ambiguous = torch.rand(10, 3, 1, 1, device=device).to(memory_format=mf) bias = torch.rand(3, 1, 1, device=device) result = ambiguous + bias self.assertEqual(ambiguous.stride(), result.stride()) result = bias + ambiguous self.assertEqual(ambiguous.stride(), result.stride()) result = ambiguous * 5 self.assertEqual(ambiguous.stride(), result.stride()) @skipIfMps def test_memory_format_empty_like(self, device): def test_helper(x, memory_format): xc = x.contiguous(memory_format=memory_format) like = torch.empty_like(xc, memory_format=torch.preserve_format) self.assertFalse(like.is_contiguous()) self.assertTrue(like.is_contiguous(memory_format=memory_format)) like_x = torch.empty_like(x, memory_format=torch.preserve_format) self.assertTrue(like_x.is_contiguous()) self.assertFalse(like_x.is_contiguous(memory_format=memory_format)) like = torch.empty_like(x, memory_format=memory_format) self.assertFalse(like.is_contiguous()) self.assertTrue(like.is_contiguous(memory_format=memory_format)) like = torch.empty_like(xc, memory_format=torch.contiguous_format) self.assertTrue(like.is_contiguous()) self.assertFalse(like.is_contiguous(memory_format=memory_format)) like = torch.empty_like(xc) self.assertFalse(like.is_contiguous()) self.assertTrue(like.is_contiguous(memory_format=memory_format)) sparse = x.to_sparse() with self.assertRaises(RuntimeError): z = torch.empty_like(sparse, memory_format=torch.preserve_format) test_helper(torch.randn(4, 3, 8, 8, device=device), torch.channels_last) test_helper(torch.randn(4, 3, 8, 8, 8, device=device), torch.channels_last_3d) def test_memory_format_consistency(self, device): x = torch.randn(10, 3, 1, 1, device=device) x_rep = x.as_strided(x.size(), x.stride()) self.assertEqual(x.size(), x_rep.size()) self.assertEqual(x.stride(), x_rep.stride()) self.assertEqual(x.is_contiguous(), x_rep.is_contiguous()) self.assertEqual(x.is_contiguous(memory_format=torch.channels_last), x_rep.is_contiguous(memory_format=torch.channels_last)) self.assertEqual( x.is_contiguous(memory_format=torch.channels_last_3d), x_rep.is_contiguous(memory_format=torch.channels_last_3d)) # FIXME: make this a elementwise unary and elementwise binary OpInfo test def test_memory_format_operators(self, device): def _chunk_op(x, y): x1, x2 = x.chunk(2, dim=1) return x1 + x2 def _unsqueeze_op_add(x, y): return x[0].unsqueeze(0) + 3 def _unsqueeze_op_clone(x, y): return x[0].unsqueeze(0).clone() def _test_helper(x, y, bias, memory_format): return_contig_fns = [ lambda x, y: y + x, lambda x, y: y * x, lambda x, y: y.addcdiv(x, y, value=2), lambda x, y: y.addcmul(x, y, value=2), ] bias_fns = [ lambda x, b: x + b, lambda x, b: b + x, ] fns = [ lambda x, y: x.clone(), lambda x, y: x + 3, lambda x, y: 3 * x, lambda x, y: x + y, lambda x, y: x * y, lambda x, y: abs(x), lambda x, y: x.abs(), lambda x, y: x.abs_(), lambda x, y: x.acos(), lambda x, y: x.acos_(), lambda x, y: x.add(y, alpha=3), lambda x, y: x.add_(y, alpha=3), lambda x, y: x.addcdiv(y, y, value=2), lambda x, y: x.addcdiv_(y, y, value=2), lambda x, y: x.addcmul(y, y, value=2), lambda x, y: x.addcmul_(y, y, value=2), lambda x, y: x.acosh(), lambda x, y: x.acosh_(), lambda x, y: x.asinh(), lambda x, y: x.asinh_(), lambda x, y: x.atanh(), lambda x, y: x.atanh_(), lambda x, y: x.asin(), lambda x, y: x.asin_(), lambda x, y: x.atan(), lambda x, y: x.atan2(y), lambda x, y: x.atan2_(y), lambda x, y: x.ceil(), lambda x, y: x.ceil_(), lambda x, y: x.clamp(-1, 1), lambda x, y: x.cos(), lambda x, y: x.cosh(), lambda x, y: x.div(0.5), lambda x, y: x.div_(0.5), lambda x, y: x.div(y), lambda x, y: x.div_(y), lambda x, y: x.digamma(), lambda x, y: x.digamma_(), lambda x, y: x.erf(), lambda x, y: x.erfc(), lambda x, y: x.erfinv(), lambda x, y: x.erfinv_(), lambda x, y: x.exp(), lambda x, y: x.expm1(), lambda x, y: x.expm1_(), lambda x, y: x.floor(), lambda x, y: x.floor_(), lambda x, y: x.fmod(2), lambda x, y: x.frac(), lambda x, y: x.hypot(y), lambda x, y: x.hypot_(y), lambda x, y: x.i0(), lambda x, y: x.i0_(), lambda x, y: x.lerp(y, 0.5), lambda x, y: x.log(), lambda x, y: x.log_(), lambda x, y: x.log10(), lambda x, y: x.log10_(), lambda x, y: x.log1p(), lambda x, y: x.log1p_(), lambda x, y: x.log2(), lambda x, y: x.log2_(), lambda x, y: x.mul(3), lambda x, y: x.mul_(3), lambda x, y: x.neg(), lambda x, y: x.neg_(), lambda x, y: x.pow(3), lambda x, y: x.pow_(3), lambda x, y: x.pow(0.0), lambda x, y: x.pow(1.0), lambda x, y: x.reciprocal(), lambda x, y: x.remainder(2), lambda x, y: x.round(), lambda x, y: x.round_(), lambda x, y: x.rsqrt(), lambda x, y: x.rsqrt_(), lambda x, y: x.sigmoid(), lambda x, y: x.sigmoid_(), lambda x, y: x.logit(), lambda x, y: x.logit_(), lambda x, y: x.logit(1e-6), lambda x, y: x.logit_(1e-6), lambda x, y: x.sign(), lambda x, y: x.sign_(), lambda x, y: x.sgn(), lambda x, y: x.sgn_(), lambda x, y: x.sin(), lambda x, y: x.sin_(), lambda x, y: x.sinh(), lambda x, y: x.sinh_(), lambda x, y: x.sqrt(), lambda x, y: x.sqrt_(), lambda x, y: x.tan(), lambda x, y: x.tanh(), lambda x, y: x.trunc(), lambda x, y: x.trunc_(), _chunk_op, _unsqueeze_op_add, _unsqueeze_op_clone, ] for fn in fns: x_c = x.contiguous() y_c = y.contiguous() result_c = fn(x_c, y_c) result = fn(x, y) self.assertEqual(result, result_c) self.assertTrue( result.is_contiguous(memory_format=memory_format), "result of the '{}' is not in '{}' format".format(inspect.getsource(fn).strip(), memory_format)) for fn in bias_fns: x_c = x.contiguous() b_c = bias.contiguous() result_c = fn(x_c, b_c) result = fn(x, bias) self.assertEqual(result, result_c) self.assertTrue( result.is_contiguous(memory_format=memory_format), "result of the '{}' is not in '{}' format".format(inspect.getsource(fn).strip(), memory_format)) for fn in return_contig_fns: x_c = x.contiguous() y_c = y.contiguous() result_c = fn(x_c, y_c) result = fn(x, y) self.assertEqual(result, result_c) self.assertTrue( result.is_contiguous(memory_format=torch.contiguous_format), "result of the '{}' is not in '{}' format".format(inspect.getsource(fn).strip(), torch.contiguous_format)) _test_helper( torch.randn((4, 3, 8, 8), device=device).contiguous(memory_format=torch.channels_last), abs(torch.randn((4, 3, 8, 8), device=device)) + 1, torch.randn((1, 3, 1, 1), device=device).contiguous(memory_format=torch.channels_last), torch.channels_last) _test_helper( torch.randn((4, 3, 8, 8, 8), device=device).contiguous(memory_format=torch.channels_last_3d), abs(torch.randn((4, 3, 8, 8, 8), device=device)) + 1, torch.randn((1, 3, 1, 1, 1), device=device).contiguous(memory_format=torch.channels_last_3d), torch.channels_last_3d) # FIXME: make this a elementwise unary and elementwise binary OpInfo test def test_strides_propagation(self, device): def _test_helper(x, op, unary=False): def compare_strides(s1, s2, div): sdiv = [s // div for s in s1] self.assertEqual(sdiv, s2) dim = x.dim() # we produce memory dense outputs, so when input is strided on the last dimension # we need to divide by that dimension stride to compare input and result strides div = x.stride(-1) for p in permutations(range(dim)): xp = x.permute(p) if not unary: y = torch.randn(xp.size(-1), device=x.device, dtype=x.dtype) for inputs in ((xp, xp), (xp, y), (y, xp)): res = op(*inputs) compare_strides(xp.stride(), res.stride(), div) self.assertEqual(xp.size(), res.size()) out = torch.empty(0, device=xp.device, dtype=res.dtype) res = op(*inputs, out=out) compare_strides(xp.stride(), res.stride(), div) self.assertEqual(xp.size(), res.size()) else: res = op(xp) compare_strides(xp.stride(), res.stride(), div) self.assertEqual(xp.size(), res.size()) out = torch.empty(0, device=xp.device, dtype=res.dtype) res = op(xp, out=out) compare_strides(xp.stride(), res.stride(), div) self.assertEqual(xp.size(), res.size()) # torch.eq by default calls TensorIterator with defined output, torch.add with undefined binary_ops = (torch.eq, torch.add) unary_ops = (torch.exp,) # memory dense, sliced and ambiguous sliced (ambiguous dense loses permutation information) xs = (torch.randn(2, 3, 4, device=device), torch.randn(2, 3, 8, device=device)[:, :, ::2], torch.randn(1, 1, 4, 12, device=device)[:, :, :, ::2]) for op in binary_ops: for x in xs: _test_helper(x, op) for op in unary_ops: for x in xs: _test_helper(x, op, unary=True) # FIXME: move dlpack tests to their own test class/suite @skipMeta @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16)) def test_dlpack_capsule_conversion(self, device, dtype): # DLpack does not explicitly support bool (xref dmlc/dlpack#75) x = make_tensor((5,), dtype=dtype, device=device) z = from_dlpack(to_dlpack(x)) self.assertEqual(z, x) @skipMeta @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16)) def test_dlpack_protocol_conversion(self, device, dtype): x = make_tensor((5,), dtype=dtype, device=device) z = from_dlpack(x) self.assertEqual(z, x) @skipMeta @onlyNativeDeviceTypes def test_dlpack_shared_storage(self, device): x = make_tensor((5,), dtype=torch.float64, device=device) z = from_dlpack(to_dlpack(x)) z[0] = z[0] + 20.0 self.assertEqual(z, x) @skipMeta @onlyCUDA @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16)) def test_dlpack_conversion_with_streams(self, device, dtype): # Create a stream where the tensor will reside stream = torch.cuda.Stream() with torch.cuda.stream(stream): # Do an operation in the actual stream x = make_tensor((5,), dtype=dtype, device=device) + 1 # DLPack protocol helps establish a correct stream order # (hence data dependency) at the exchange boundary. # DLPack manages this synchronization for us, so we don't need to # explicitly wait until x is populated stream = torch.cuda.Stream() with torch.cuda.stream(stream): z = from_dlpack(x) stream.synchronize() self.assertEqual(z, x) @skipMeta @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16)) def test_from_dlpack(self, device, dtype): x = make_tensor((5,), dtype=dtype, device=device) y = torch.from_dlpack(x) self.assertEqual(x, y) @skipMeta @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16)) def test_from_dlpack_noncontinguous(self, device, dtype): x = make_tensor((25,), dtype=dtype, device=device).reshape(5, 5) y1 = x[0] y1_dl = torch.from_dlpack(y1) self.assertEqual(y1, y1_dl) y2 = x[:, 0] y2_dl = torch.from_dlpack(y2) self.assertEqual(y2, y2_dl) y3 = x[1, :] y3_dl = torch.from_dlpack(y3) self.assertEqual(y3, y3_dl) y4 = x[1] y4_dl = torch.from_dlpack(y4) self.assertEqual(y4, y4_dl) y5 = x.t() y5_dl = torch.from_dlpack(y5) self.assertEqual(y5, y5_dl) @skipMeta @onlyCUDA @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16)) def test_dlpack_conversion_with_diff_streams(self, device, dtype): stream_a = torch.cuda.Stream() stream_b = torch.cuda.Stream() # DLPack protocol helps establish a correct stream order # (hence data dependency) at the exchange boundary. # the `tensor.__dlpack__` method will insert a synchronization event # in the current stream to make sure that it was correctly populated. with torch.cuda.stream(stream_a): x = make_tensor((5,), dtype=dtype, device=device) + 1 z = torch.from_dlpack(x.__dlpack__(stream_b.cuda_stream)) stream_a.synchronize() stream_b.synchronize() self.assertEqual(z, x) @skipMeta @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16)) def test_from_dlpack_dtype(self, device, dtype): x = make_tensor((5,), dtype=dtype, device=device) y = torch.from_dlpack(x) assert x.dtype == y.dtype @skipMeta @onlyCUDA def test_dlpack_default_stream(self, device): class DLPackTensor: def __init__(self, tensor): self.tensor = tensor def __dlpack_device__(self): return self.tensor.__dlpack_device__() def __dlpack__(self, stream=None): if torch.version.hip is None: assert stream == 1 else: assert stream == 0 capsule = self.tensor.__dlpack__(stream) converted = True return capsule # CUDA-based tests runs on non-default streams with torch.cuda.stream(torch.cuda.default_stream()): x = DLPackTensor(make_tensor((5,), dtype=torch.float32, device=device)) from_dlpack(x) @skipMeta @onlyNativeDeviceTypes @dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16)) def test_dlpack_tensor_invalid_stream(self, device, dtype): with self.assertRaises(TypeError): x = make_tensor((5,), dtype=dtype, device=device) x.__dlpack__(stream=object()) @skipMeta def test_dlpack_error_on_bool_tensor(self): x = torch.tensor([True], dtype=torch.bool) with self.assertRaises(RuntimeError): to_dlpack(x) # TODO: increase tests once NumPy supports the `__dlpack__` protocol @skipMeta def test_dlpack_export_requires_grad(self): x = torch.zeros(10, dtype=torch.float32, requires_grad=True) with self.assertRaisesRegex(RuntimeError, r"require gradient"): x.__dlpack__() @skipMeta def test_dlpack_export_is_conj(self): x = torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]) y = torch.conj(x) with self.assertRaisesRegex(RuntimeError, r"conjugate bit"): y.__dlpack__() @skipMeta def test_dlpack_export_non_strided(self): x = torch.sparse_coo_tensor([[0]], [1], size=(1,)) y = torch.conj(x) with self.assertRaisesRegex(RuntimeError, r"strided"): y.__dlpack__() @onlyCUDA @unittest.skipIf(PYTORCH_CUDA_MEMCHECK, "is_pinned uses failure to detect pointer property") def test_pin_memory_from_constructor(self, device): def _get_like(t, **kwargs): return [ torch.rand_like(t, **kwargs), torch.randn_like(t, **kwargs), torch.empty_like(t, **kwargs), torch.full_like(t, 4, **kwargs), torch.zeros_like(t, **kwargs), torch.ones_like(t, **kwargs), ] def _get_tensors(**kwargs): return [ torch.tensor([10, 11], **kwargs), torch.randn(3, 5, **kwargs), torch.rand(3, **kwargs), # torch.randint(3, 5, **kwargs), // unsupported torch.zeros(3, **kwargs), torch.randperm(3, **kwargs), torch.empty(6, **kwargs), torch.ones(6, **kwargs), torch.eye(6, **kwargs), torch.arange(3, 5, **kwargs)] pinned_tensors = _get_tensors(pin_memory=True) + _get_like(torch.empty(5, dtype=torch.float64), pin_memory=True) for x in pinned_tensors: self.assertTrue(x.is_pinned()) tensors = _get_tensors() + _get_like(torch.empty(5, dtype=torch.float64, pin_memory=True)) for x in tensors: self.assertFalse(x.is_pinned()) @deviceCountAtLeast(1) @onlyCUDA def test_storage_all_devices(self, devices): for device in devices: t = torch.tensor((), device=device) self.assertEqual(t.dtype, t.storage().dtype) # FIXME: move to test distributions @skipIfMps @dtypesIfCUDA(torch.float, torch.double, torch.half) @dtypes(torch.float, torch.double) def test_multinomial(self, device, dtype): def make_prob_dist(shape, is_contiguous): if is_contiguous: if dtype == torch.half: return torch.zeros(shape, device=device).uniform_().to(dtype=torch.half) return torch.zeros(shape, device=device, dtype=dtype).uniform_() elif len(shape) == 1: if dtype == torch.half: return torch.zeros((shape + [5]), device=device).uniform_().to(dtype=torch.half)[:, 2] return torch.zeros((shape + [5]), device=device, dtype=dtype).uniform_()[:, 2] else: # num dim = 2 new_shape = [2, shape[1], 7, 1, shape[0], 1, 10] if dtype == torch.half: prob_dist = torch.zeros(new_shape, device=device).uniform_().to(dtype=torch.half) else: prob_dist = torch.zeros(new_shape, device=device, dtype=dtype).uniform_() prob_dist = prob_dist.transpose(1, 4) prob_dist = prob_dist[1, :, 5, 0, :, 0, 4] assert not prob_dist.is_contiguous() # sanity check return prob_dist for is_contiguous in (True, False): # with replacement n_row = 3 for n_col in range(4, 5 + 1): prob_dist = make_prob_dist([n_row, n_col], is_contiguous) # indices that shouldn't be sampled (<0 means none) zero_prob_indices = torch.LongTensor(n_row).random_(-2, n_col).tolist() for i, j in enumerate(zero_prob_indices): if j >= 0: prob_dist[i, j] = 0 n_sample = n_col * 3 sample_indices = torch.multinomial(prob_dist, n_sample, True) self.assertEqual(prob_dist.dim(), 2) self.assertEqual(sample_indices.size(1), n_sample) for i in range(n_row): zero_prob_idx = zero_prob_indices[i] if zero_prob_idx < 0: continue for j in range(n_sample): self.assertNotEqual(sample_indices[i, j], zero_prob_idx, msg="sampled an index with zero probability") # without replacement n_row = 3 for n_col in range(2, 10 + 1, 2): prob_dist = make_prob_dist([n_row, n_col], is_contiguous) # indices that shouldn't be sampled (<0 means none) zero_prob_indices = torch.LongTensor(n_row).random_(-1, n_col).tolist() for i, j in enumerate(zero_prob_indices): if j >= 0: prob_dist[i, j] = 0 n_sample = max(1, n_col - 2) sample_indices = torch.multinomial(prob_dist, n_sample, False) self.assertEqual(prob_dist.dim(), 2) self.assertEqual(sample_indices.size(1), n_sample) for i in range(n_row): row_samples = {} zero_prob_idx = zero_prob_indices[i] for j in range(n_sample): sample_idx = sample_indices[i, j] if zero_prob_idx >= 0: self.assertNotEqual(sample_idx, zero_prob_idx, msg="sampled an index with zero probability") self.assertNotIn(sample_idx, row_samples, "sampled an index twice") row_samples[sample_idx] = True # vector n_col = 4 prob_dist = make_prob_dist([n_col], is_contiguous).fill_(1) zero_prob_idx = 1 # index that shouldn't be sampled prob_dist[zero_prob_idx] = 0 n_sample = 20 sample_indices = torch.multinomial(prob_dist, n_sample, True) for sample_index in sample_indices: self.assertNotEqual(sample_index, zero_prob_idx, msg="sampled an index with zero probability") s_dim = sample_indices.dim() self.assertEqual(sample_indices.dim(), 1, msg="wrong number of dimensions") self.assertEqual(prob_dist.dim(), 1, msg="wrong number of prob_dist dimensions") self.assertEqual(sample_indices.size(0), n_sample, msg="wrong number of samples") # CUDA misalignment issue (#46702) n_row, n_col = 2, 3 prob_dist = make_prob_dist([n_row, n_col], True) n_sample = 1 sample_indices = torch.multinomial(prob_dist, n_sample, True) self.assertEqual(sample_indices.dim(), 2, msg="wrong number of dimensions") self.assertEqual(sample_indices.size(1), n_sample, msg="wrong number of samples") # FIXME: move to test distributions @onlyCUDA @dtypes(torch.float, torch.double, torch.half) def test_multinomial_deterministic(self, device, dtype): gen = torch.Generator(device=device) trials = 5 seed = 0 prob_dist = torch.rand(10000, 1000, device=device, dtype=dtype) n_sample = 1 for i in range(trials): gen.manual_seed(seed) samples_1 = torch.multinomial(prob_dist, n_sample, True, generator=gen) gen.manual_seed(seed) samples_2 = torch.multinomial(prob_dist, n_sample, True, generator=gen) self.assertEqual(samples_1, samples_2) self.assertEqual(samples_1.dim(), 2, msg="wrong number of dimensions") self.assertEqual(samples_1.size(1), n_sample, msg="wrong number of samples") # FIXME: move to test distributions @slowTest @dtypes(torch.float) def test_multinomial_rng_state_advance(self, device, dtype): corpus_size = 100000 freqs = torch.ones(corpus_size, dtype=torch.float, device=device) n_sample = 100 samples1 = torch.multinomial(freqs, n_sample, replacement=True) samples2 = torch.multinomial(freqs, n_sample, replacement=True) samples = torch.cat([samples1, samples2]) # expect no more than 1 repeating elements generated in 2 attempts # the probability of at least element being repeated is surprisingly large, 18% self.assertLessEqual(2 * n_sample - samples.unique().size(0), 2) samples1 = torch.multinomial(freqs, n_sample, replacement=False) samples2 = torch.multinomial(freqs, n_sample, replacement=False) samples = torch.cat([samples1, samples2]) # expect no more than 1 repeating elements generated in 2 attempts self.assertLessEqual(2 * n_sample - samples.unique().size(0), 1) def _test_memory_format_transformations(self, device, input_generator_fn, transformation_fn, memory_format, compare_data=True, default_is_preserve=False): assert(memory_format == torch.channels_last or memory_format == torch.channels_last_3d) # xc is a channels last tensor xc = input_generator_fn(device) # xc is not memory dense, but looks like channels last if memory_format == torch.channels_last: xc = xc[..., ::2, ::2] else: xc = xc[..., ::2, ::2, ::2] clone = transformation_fn(xc, memory_format=torch.preserve_format) self.assertFalse(clone.is_contiguous()) self.assertTrue(clone.is_contiguous(memory_format=memory_format)) self.assertFalse(xc.is_contiguous()) self.assertFalse(xc.is_contiguous(memory_format=memory_format)) if compare_data: self.assertEqual(xc, clone.to(xc)) xc = input_generator_fn(device) clone = transformation_fn(xc, memory_format=torch.contiguous_format) self.assertTrue(clone.is_contiguous()) self.assertFalse(clone.is_contiguous(memory_format=memory_format)) if compare_data: self.assertEqual(xc, clone.to(xc)) xc = input_generator_fn(device) clone = transformation_fn(xc) if default_is_preserve: self.assertFalse(clone.is_contiguous()) self.assertTrue(clone.is_contiguous(memory_format=memory_format)) else: self.assertTrue(clone.is_contiguous()) self.assertFalse(clone.is_contiguous(memory_format=memory_format)) if compare_data: self.assertEqual(xc, clone.to(xc)) x = torch.randn((3, 4, 5, 6, 7, 8, 9), device=device) for _ in range(10): permutation = list(range(len(x.shape))) random.shuffle(permutation) x = x.permute(permutation) self.assertEqual(x.stride(), transformation_fn(x, memory_format=torch.preserve_format).stride()) def test_memory_format_to(self, device): def get_generator(memory_format, shape): def input_generator_fn(device): return torch.randn(shape, device=device, dtype=torch.float32).contiguous(memory_format=memory_format) return input_generator_fn def transformation_fn(tensor, **kwargs): return tensor.to(dtype=torch.float64, **kwargs) formats_shapes = ( (torch.channels_last, (4, 3, 8, 8)), (torch.channels_last_3d, (4, 3, 8, 8, 8))) for mf, shape in formats_shapes: self._test_memory_format_transformations( device, get_generator(mf, shape), transformation_fn, mf, default_is_preserve=True) def test_memory_format_type(self, device): def get_generator(memory_format, shape): def input_generator_fn(device): return torch.randn(shape, device=device, dtype=torch.float32).contiguous(memory_format=memory_format) return input_generator_fn def transformation_fn(tensor, **kwargs): return tensor.to(torch.float64, **kwargs) formats_shapes = ( (torch.channels_last, (4, 3, 8, 8)), (torch.channels_last_3d, (4, 3, 8, 8, 8))) for mf, shape in formats_shapes: self._test_memory_format_transformations( device, get_generator(mf, shape), transformation_fn, mf, default_is_preserve=True) def test_memory_format_clone(self, device): def get_generator(memory_format, shape): def input_generator_fn(device): return torch.randn(shape, device=device, dtype=torch.float32).contiguous(memory_format=memory_format) return input_generator_fn def transformation_fn(tensor, **kwargs): return tensor.clone(**kwargs) formats_shapes = ( (torch.channels_last, (4, 3, 8, 8)), (torch.channels_last_3d, (4, 3, 8, 8, 8))) for mf, shape in formats_shapes: self._test_memory_format_transformations( device, get_generator(mf, shape), transformation_fn, mf, True, default_is_preserve=True) def test_memory_format_factory_like_functions_preserve(self, device): def get_generator(memory_format, shape): def input_generator_fn(device): return torch.randn(shape, device=device, dtype=torch.float32).contiguous(memory_format=memory_format) return input_generator_fn transformation_fns = [ lambda t, **kwargs: torch.zeros_like(t, **kwargs), lambda t, **kwargs: torch.ones_like(t, **kwargs), lambda t, **kwargs: torch.randint_like(t, 10, 100, **kwargs), lambda t, **kwargs: torch.randint_like(t, 100, **kwargs), lambda t, **kwargs: torch.randn_like(t, **kwargs), lambda t, **kwargs: torch.rand_like(t, **kwargs), lambda t, **kwargs: torch.full_like(t, 7, **kwargs), lambda t, **kwargs: torch.empty_like(t, **kwargs)] formats_shapes = ( (torch.channels_last, (4, 3, 8, 8)), (torch.channels_last_3d, (4, 3, 8, 8, 8))) for mf, shape, in formats_shapes: for transformation_fn in transformation_fns: self._test_memory_format_transformations( device, get_generator(mf, shape), transformation_fn, mf, compare_data=False, default_is_preserve=True) def test_memory_format_type_shortcuts(self, device): def get_generator(memory_format, shape, dtype): def input_generator_fn(device): return torch.randn(shape, device=device, dtype=dtype).clamp(0, 1) \ .round().contiguous(memory_format=memory_format) return input_generator_fn def get_fn(fn_name): def transformation_fn(tensor, **kwargs): fn = getattr(tensor, fn_name) return fn(**kwargs) return transformation_fn shortcuts = ['byte', 'char', 'double', 'bool', 'half', 'int', 'long', 'short'] if device == 'cpu': shortcuts += ['bfloat16'] formats_shapes = ( (torch.channels_last, (4, 3, 8, 8)), (torch.channels_last_3d, (4, 3, 8, 8, 8))) for mf, shape in formats_shapes: for fn_name in shortcuts: self._test_memory_format_transformations( device, get_generator(mf, shape, torch.float32), get_fn(fn_name), mf, default_is_preserve=True) # Test 'float' separately to avoid float->float no-op. for mf, shape in formats_shapes: self._test_memory_format_transformations( device, get_generator(mf, shape, torch.float64), get_fn('float'), mf, default_is_preserve=True) @onlyCUDA def test_memory_format_cpu_and_cuda_ops(self, device): def get_generator(memory_format, shape): def input_generator_fn(device): return torch.randn(shape, device=device, dtype=torch.float32).contiguous(memory_format=memory_format) return input_generator_fn def transformation_cpu_fn(tensor, **kwargs): return tensor.cpu(**kwargs) def transformation_cuda_fn(tensor, **kwargs): return tensor.cuda(**kwargs) formats_shapes = ( (torch.channels_last, (4, 3, 8, 8)), (torch.channels_last_3d, (4, 3, 8, 8, 8))) for mf, shape in formats_shapes: self._test_memory_format_transformations( 'cuda', get_generator(mf, shape), transformation_cpu_fn, mf, default_is_preserve=True) self._test_memory_format_transformations( 'cpu', get_generator(mf, shape), transformation_cuda_fn, mf, default_is_preserve=True) # FIXME: move to test_serialization def test_pickle_gradscaler(self, device): # This test is not in test_cuda.py because it should pass in 3 cases: # 1. cuda is not available. # 2. cuda is available but device is not cuda. # 3. cuda is available and device is cuda. # In case 1, a and b disable themselves on construction and shouldn't try to pickle workhorse attributes. # In case 2, a and b are enabled. Workhorse attributes participate in pickling, but none are lazy-inited # to cuda Tensors, because I don't want to do cuda things if device is not cuda. # In case 3, a and b are enabled and we may also try lazy-initing _scale to a cuda tensor. device = torch.device(device) try_lazy_inits = (True, False) if device.type == "cuda" else (False,) for lazy_init_scale in try_lazy_inits: a = torch.cuda.amp.GradScaler(init_scale=3., growth_factor=4., backoff_factor=.5, growth_interval=2) self.assertTrue(not a.is_enabled() if torch.cuda.amp.common.amp_definitely_not_available() else a.is_enabled()) if lazy_init_scale: # Dummy a.scale() call lazy-inits a._scale Tensor. a.scale(torch.tensor([4.0], dtype=torch.float32, device=device)) self.assertTrue(isinstance(a._scale, torch.cuda.FloatTensor)) # The following three lines should work whether or not cuda is available. serialized = pickle.dumps(a) b = pickle.loads(serialized) self.assertEqual(b.is_enabled(), a.is_enabled()) if a.is_enabled(): self.assertEqual(b.get_scale(), 3.) self.assertEqual(b.get_growth_factor(), 4.) self.assertEqual(b.get_backoff_factor(), .5) self.assertEqual(b.get_growth_interval(), 2) self.assertEqual(b._init_growth_tracker, 0) # supplies a dummy key to test the defaultdict's default_factory self.assertEqual(b._per_optimizer_states["fdsa"], torch.cuda.amp.grad_scaler._refresh_per_optimizer_state()) if lazy_init_scale: self.assertEqual(b.scale(torch.tensor([4.0], dtype=torch.float32, device=device)), 12.0) # FIXME: convert to ErrorInputs @skipIfMps def test_multinomial_invalid(self, device): def test(probs): with self.assertRaisesRegex(RuntimeError, 'probability tensor contains either `inf`, `nan` or element < 0'): torch.multinomial(probs.to(device), 2) torch.cuda.synchronize() test(torch.tensor([1., -1., 1.])) test(torch.tensor([1., inf, 1.])) test(torch.tensor([1., -inf, 1.])) test(torch.tensor([1., 1., nan])) # FIXME: convert to ErrorInputs @skipIfMps def test_multinomial_invalid_distribution(self, device): def test(probs, replacement): with self.assertRaisesRegex(RuntimeError, r"invalid multinomial distribution \(sum of probabilities <= 0\)"): torch.multinomial(probs, 2, replacement) torch.cuda.synchronize() x = torch.zeros(3, device=device) y = torch.zeros(3, 3, device=device) z = torch.zeros(3, 3, device=device) z[1, :] = 1 test(x, False) test(y, False) test(z, False) # Verify only for CPU as replacement=True # throws device side assert triggered. if self.device_type == 'cpu': test(x, True) test(y, True) test(z, True) # FIXME: move to test distributions def _test_multinomial_empty(self, device, replacement, num_samples): probs = torch.ones(0, 3, device=device) expected = torch.empty(0, num_samples, dtype=torch.int64) out = torch.multinomial(probs, num_samples=num_samples, replacement=replacement) self.assertEqual(out, expected) # FIXME: move to test distributions def test_multinomial_empty_w_replacement(self, device): self._test_multinomial_empty(device, True, 1) self._test_multinomial_empty(device, True, 2) # FIXME: move to test distributions def test_multinomial_empty_wo_replacement(self, device): self._test_multinomial_empty(device, False, 1) self._test_multinomial_empty(device, False, 2) @dtypesIfCUDA(torch.float, torch.double, torch.half) @dtypesIfCPU(torch.float, torch.double, torch.bfloat16) @dtypes(torch.float, torch.double) def test_multinomial_cpu(self, device, dtype): def make_prob_dist(shape, is_contiguous): if is_contiguous: if dtype == torch.half or dtype == torch.bfloat16: return torch.zeros(shape, device=device).uniform_().to(dtype=dtype) return torch.zeros(shape, device=device, dtype=dtype).uniform_() elif len(shape) == 1: if dtype == torch.half or dtype == torch.bfloat16: return torch.zeros((shape + [5]), device=device).uniform_().to(dtype=dtype)[:, 2] return torch.zeros((shape + [5]), device=device, dtype=dtype).uniform_()[:, 2] else: # num dim = 2 new_shape = [2, shape[1], 7, 1, shape[0], 1, 10] if dtype == torch.half or dtype == torch.bfloat16: prob_dist = torch.zeros(new_shape, device=device).uniform_().to(dtype=dtype) else: prob_dist = torch.zeros(new_shape, device=device, dtype=dtype).uniform_() prob_dist = prob_dist.transpose(1, 4) prob_dist = prob_dist[1, :, 5, 0, :, 0, 4] assert not prob_dist.is_contiguous() # sanity check return prob_dist # FIXME: move to elementwise ternary test suite # As the test fails with Runtime Error not raised on XLA @onlyNativeDeviceTypes def test_where_scalar_handcrafted_values(self, device): # Tests ScalarxScalar, ScalarxTensor and TensorxScalar # variant of `where` against NumPy version with # handcrafted values. condition_shape = (5, 5) dtypes = ( torch.bool, torch.uint8, torch.int8, torch.int16, torch.int64, torch.float16, torch.float32, torch.float64, torch.complex64, torch.complex128, ) shapes = ((), (5,), (1, 5),) with torch.no_grad(): tensors = (torch.empty(shape, dtype=dtype, device=device).fill_(17) for shape, dtype in product(shapes, dtypes)) # Use different values for `x` and `y` # as they are the output values which are compared. x_vals = (True, 3, 7.0, 1 + 0.5j) y_vals = itertools.chain((False, 4, 8.0, 2 + 0.5j), tensors) for x in x_vals: for y in y_vals: condition = torch.empty(*condition_shape, dtype=torch.bool, device=device).bernoulli_() common_dtype = torch.result_type(x, y) def check_equal(condition, x, y): condition_np = condition.cpu().numpy() x_np = x.cpu().numpy() if isinstance(x, torch.Tensor) else x y_np = y.cpu().numpy() if isinstance(y, torch.Tensor) else y # NumPy aggressively promotes to double, hence cast to output to correct dtype expected = torch.from_numpy(np.where(condition_np, x_np, y_np)).to(common_dtype) result = torch.where(condition, x, y) self.assertEqual(expected, result) check_equal(condition, x, y) check_equal(condition, y, x) def test_hook_remove(self, device): # Reference: https://github.com/pytorch/pytorch/issues/58354 def _test_helper(remove_hook): def install_hook(tensor): handle = None def hook(tensor): if remove_hook: handle.remove() return torch.zeros_like(tensor) handle = tensor.register_hook(hook) t = torch.ones((1, 5), device=device, requires_grad=True) install_hook(t) # First call to backward t.mean().backward() self.assertEqual(t.grad, torch.zeros_like(t)) # Second call to backward t.mean().backward() if remove_hook: # After removing the hook, make sure the usual gradient is returned self.assertEqual(t.grad, 0.2 * torch.ones_like(t)) else: self.assertEqual(t.grad, torch.zeros_like(t)) _test_helper(remove_hook=True) _test_helper(remove_hook=False) # FIXME: get PyTorch/XLA to run test_testing # This test should ideally be in test_testing.py, # but since pytorch/xla runs tests from test_torch.py, we have it here. @skipXLA def test_skip_xla(self, device): if self.device_type == 'xla': # Should not reach here! self.assertTrue(False) # FIXME: get PyTorch/XLA to run test_testing # This test should ideally be in test_testing.py, # but since pytorch/xla runs tests from test_torch.py, we have it here. @expectedFailureXLA def test_expected_failure_xla(self, device): if self.device_type == 'xla': self.assertTrue(False) # FIXME: get PyTorch/XLA to run test_testing # This test should ideally be in test_testing.py, # but since pytorch/xla runs tests from test_torch.py, we have it here. def test_assertRaisesRegex_ignore_msg_non_native_device(self, device): # Verify that self.assertRaisesRegex only checks the Error and ignores # message for non-native devices. x = torch.randn((10, 3), device=device) t = torch.empty(10, dtype=torch.int64, device=device).random_(0, 3) invalid_weight = torch.randn(4, device=device) msg = "weight tensor should be defined either for all 3 classes or no classes" # XLA raises RuntimeError with a different message. with self.assertRaisesRegex(RuntimeError, msg): torch.nn.functional.nll_loss(x, t, weight=invalid_weight) @dtypes(*all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16, torch.complex32)) def test_copy_(self, device, dtype): def can_cast(src_dtype, dst_dtype): # torch.can_cast(torch.int16, torch.uint8) returns True # which isn't actually safe-cast. # This function returns False in this case. def is_unsigned_int(dtype): return dtype is torch.uint8 if is_unsigned_int(dst_dtype): return is_unsigned_int(src_dtype) return torch.can_cast(src_dtype, dst_dtype) def make_tensor_wrapper(shape, dtype): if dtype is not torch.complex32: # Make tensor does not support generating # complex32 tensor return make_tensor(shape, device=device, dtype=dtype) return torch.randn(shape, device=device, dtype=dtype) t = make_tensor_wrapper((50,), dtype) src_dtypes = all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16, torch.complex32) for src_dtype in src_dtypes: src = make_tensor_wrapper((50,), dtype=src_dtype) t.copy_(src) dst = make_tensor_wrapper((50, ), dtype=src_dtype) if can_cast(src_dtype, dtype): rtol = None atol = None if dtype in (torch.half, torch.complex32): rtol = 1e-3 atol = 1e-3 if dtype in (torch.bfloat16,): rtol = 1e-2 atol = 1e-2 self.assertEqual(src, dst.copy_(t), rtol=rtol, atol=atol) @dtypes(*all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16, torch.complex32)) def test_item(self, device, dtype): t = torch.ones((), device=device, dtype=dtype) self.assertEqual(1, t.item()) # Tests that compare a device's computation with the (gold-standard) CPU's. class TestDevicePrecision(TestCase): exact_dtype = True # FIXME: move to indexing test suite @onlyCUDA def test_index_add_bfloat16(self, device): inp_tensor = torch.randn(5, 3, device='cpu').bfloat16() t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.bfloat16, device='cpu') index = torch.tensor([0, 4, 2], device='cpu') out_cpu = inp_tensor.index_add(0, index, t) inp_tensor = inp_tensor.to(device=device) t = t.to(device=device) index = index.to(device=device) out_gpu = inp_tensor.index_add(0, index, t) self.assertEqual(out_cpu, out_gpu, atol=1e-2, rtol=0) # FIXME: move to serialization test suite def test_device_serialization(self, device): x = torch.randn(4, 4, device=device) with tempfile.NamedTemporaryFile() as f: torch.save(x, f) f.seek(0) x_copy = torch.load(f) self.assertEqual(x_copy, x) self.assertIs(type(x_copy), type(x)) self.assertEqual(x_copy.device, x.device) # FIXME: move to serialization test suite @deviceCountAtLeast(2) def test_multidevice_serialization(self, devices): x = [torch.randn(4, 4, device=devices[0]), torch.randn(4, 4, device=devices[1])] with tempfile.NamedTemporaryFile() as f: torch.save(x, f) f.seek(0) x_copy = torch.load(f) for original, cp in zip(x, x_copy): self.assertEqual(cp, original) self.assertIs(type(cp), type(original)) self.assertEqual(cp.device, original.device) # FIXME: move to data movement test suite @deviceCountAtLeast(1) def test_copy_noncontig(self, devices): def do_test(d0, d1): x = torch.tensor([1.5, 2.5, 3.5, 4.5, 5.5, 6.5], device=d0) y = torch.tensor([0, 0, 0, 0, 0, 0], device=d1) self.assertNotEqual(x.dtype, y.dtype) y[::2].copy_(x[::2]) self.assertEqual(y, [1, 0, 3, 0, 5, 0]) do_test('cpu', devices[0]) do_test(devices[0], 'cpu') if len(devices) > 1: do_test(devices[0], devices[1]) @deviceCountAtLeast(2) def test_type_conversions_same_device(self, devices): x = torch.randn(5, 5, device=devices[1]) self.assertEqual(x.int().device, torch.device(devices[1])) self.assertEqual(x.type(torch.int).device, torch.device(devices[1])) self.assertEqual(x.to(torch.int).device, torch.device(devices[1])) @dtypesIfCUDA(torch.half, torch.float, torch.double, torch.int8, torch.short, torch.int, torch.long, torch.uint8) @dtypes(torch.float, torch.double, torch.int8, torch.short, torch.int, torch.long, torch.uint8) def test_from_sequence(self, device, dtype): seq = [list(range(i * 4, i * 4 + 4)) for i in range(5)] reference = torch.arange(0, 20).resize_(5, 4) self.assertEqual(torch.tensor(seq, dtype=dtype, device=device), reference, exact_dtype=False) # FIXME: moved to indexing test suite @deviceCountAtLeast(1) def test_advancedindex_mixed_cpu_devices(self, devices) -> None: def test(x: torch.Tensor, ia: torch.Tensor, ib: torch.Tensor) -> None: # test getitem self.assertEqual(x[:, ia, None, ib, 0].cpu(), x.cpu()[:, ia.cpu(), None, ib.cpu(), 0]) self.assertEqual(x[ia], x.cpu()[ia.cpu()]) # test setitem x_clone1 = x.clone() x_clone2 = x.clone() first_shape = x[:, ia, None, ib, 0].shape second_shape = x[ia].shape x_clone1[:, ia, None, ib, 0] = torch.randn(first_shape).to(x_clone1) x_clone2[ia] = torch.randn(second_shape).to(x_clone2) cpu = torch.device('cpu') for device in devices: # Index cpu tensor with device tensor x = torch.randn(3, 4, 4, 4, 3) ia = torch.tensor([0, 2, 1]).to(device) ib = torch.tensor([0, 2, 1]).to(device) test(x, ia, ib) # Index device tensor with cpu tensor x = x.to(device) ia = ia.to(cpu) ib = ib.to(cpu) test(x, ia, ib) # Index cpu tensor with mixed cpu, device tensors x = x.to(cpu) ia = ia.to(cpu) ib = ib.to(device) test(x, ia, ib) # Index device tensor with mixed cpu, device tensors x = x.to(device) ia = ia.to(cpu) ib = ib.to(device) test(x, ia, ib) if len(devices) > 1: other_device = devices[0] if device == devices[0]: other_device = devices[1] # Index device tensor with mixed cpu, device tensors on different devices x = x.to(device) ia = ia.to(cpu) ib = ib.to(other_device) test(x, ia, ib) # FIXME: move to data movement test suite def test_copy_broadcast(self, device) -> None: x = torch.randn(10, 5) y = torch.randn(5, device=device) x.copy_(y) self.assertEqual(x[3], y) x = torch.randn(10, 5, device=device) y = torch.randn(5) x.copy_(y) self.assertEqual(x[3], y) # FIXME: move to an elementwise ternary test suite @dtypes(torch.int64, torch.float32, torch.float64) def test_clamp(self, device, dtype): test_args = [ *product( [(100, 50), (10, 64), (97,)], # shape (True, False), # non-contiguous ) ] for shape, noncontig in test_args: x = make_tensor(shape, device=device, dtype=dtype, noncontiguous=noncontig) ub = make_tensor(shape, device=device, dtype=dtype, noncontiguous=noncontig) lb = make_tensor(shape, device=device, dtype=dtype, noncontiguous=noncontig) expect = x.max(lb).min(ub) actual = x.clamp(lb, ub) self.assertEqual(expect, actual) expect = np.clip(x.cpu().numpy(), lb.cpu().numpy(), ub.cpu().numpy()) self.assertEqual(expect, actual) expect = x.max(lb) actual = x.clamp(min=lb) self.assertEqual(expect, actual) expect = x.min(ub) actual = x.clamp(max=ub) self.assertEqual(expect, actual) # Test broadcasting min & max expect = x.max(lb[0]).min(ub[..., :1]) actual = x.clamp(lb[0], ub[..., :1]) self.assertEqual(expect, actual) # Test broadcasting x expect = x[..., :1].max(lb).min(ub) actual = x[..., :1].clamp(lb, ub) self.assertEqual(expect, actual) def test_cuda_device_idx(self, device): x = torch.zeros(3, device=device) y = torch._efficientzerotensor(3, device=device) self.assertEqual(x.device, y.device) # we implemented custom deallocation for subclasses, so it behooves # us to make sure all of these bits work. We'll use __del__ to # track if objects die or not class Tracker: def __init__(self, marker): self.marker = marker @staticmethod def make(): marker = [False] return marker, Tracker(marker) def __del__(self): self.marker[0] = True @contextlib.contextmanager def disable_gc(): if gc.isenabled(): try: gc.disable() yield finally: gc.enable() else: yield class TestTorch(TestCase): exact_dtype = True def test_dir(self): dir(torch) def test_wildcard_import(self): exec('from torch import *') def test_newaxis_numpy_comparison(self): def run_test(tensor, *idx): npt = tensor.numpy() self.assertEqual(tensor[idx], npt[idx]) # 1D Tensor Tests x = torch.arange(0, 10) cases = [ [None], [None, None], [Ellipsis, None], [None, Ellipsis], [2, None], [None, 2], [Ellipsis, None, 2], [Ellipsis, 2, None], [2, Ellipsis, None], [2, None, Ellipsis], [None, 2, Ellipsis], [None, Ellipsis, 2], ] for case in cases: run_test(x, *case) # 2D Tensor Tests x = torch.arange(0, 12).view(3, 4) cases = [ [None], [None, None], [None, None, None], [Ellipsis, None], [Ellipsis, None, None], [None, Ellipsis], [None, Ellipsis, None], [None, None, Ellipsis], [2, None], [2, None, Ellipsis], [2, Ellipsis, None], [None, 2, Ellipsis], [Ellipsis, 2, None], [Ellipsis, None, 2], [None, Ellipsis, 2], [1, 2, None], [1, 2, Ellipsis, None], [1, Ellipsis, 2, None], [Ellipsis, 1, None, 2], [Ellipsis, 1, 2, None], [1, None, 2, Ellipsis], [None, 1, Ellipsis, 2], [None, 1, 2, Ellipsis], ] for case in cases: run_test(x, *case) def _consecutive(self, size, start=1): sequence = torch.ones(torch.tensor(size).prod(0)).cumsum(0) sequence.add_(start - 1) return sequence.resize_(*size) def test_newindex(self): reference = self._consecutive((3, 3, 3)) # This relies on __index__() being correct - but we have separate tests for that def checkPartialAssign(index): reference = torch.zeros(3, 3, 3) reference[index] = self._consecutive((3, 3, 3))[index] self.assertEqual(reference[index], self._consecutive((3, 3, 3))[index], atol=0, rtol=0) reference[index] = 0 self.assertEqual(reference, torch.zeros(3, 3, 3), atol=0, rtol=0) checkPartialAssign(0) checkPartialAssign(1) checkPartialAssign(2) checkPartialAssign((0, 1)) checkPartialAssign((1, 2)) checkPartialAssign((0, 2)) checkPartialAssign(torch.LongTensor((0, 2))) with self.assertRaises(IndexError): reference[1, 1, 1, 1] = 1 with self.assertRaises(IndexError): reference[1, 1, 1, (1, 1)] = 1 with self.assertRaises(IndexError): reference[3, 3, 3, 3, 3, 3, 3, 3] = 1 with self.assertRaises(IndexError): reference[0.0] = 1 with self.assertRaises(TypeError): reference[0.0:2.0] = 1 with self.assertRaises(IndexError): reference[0.0, 0.0:2.0] = 1 with self.assertRaises(IndexError): reference[0.0, :, 0.0:2.0] = 1 with self.assertRaises(IndexError): reference[0.0, ..., 0.0:2.0] = 1 with self.assertRaises(IndexError): reference[0.0, :, 0.0] = 1 # FIXME: move to indexing test suite def test_index_add(self): for device in get_all_device_types(): for dest_contig, src_contig, index_contig in product([True, False], repeat=3): for other_sizes in ((), (4, 5)): for dtype in [torch.int, torch.long]: num_copy, num_dest = 3, 3 dest = torch.randn(num_dest, *other_sizes, device=device) if not dest_contig: dest = make_tensor(dest.shape, device=device, dtype=dest.dtype, noncontiguous=True) src = torch.randn(num_copy, *other_sizes, device=device) if not src_contig: src = torch.testing.make_non_contiguous(src) idx = torch.randperm(num_dest, dtype=dtype, device=device).narrow(0, 0, num_copy) if not index_contig: idx = torch.testing.make_non_contiguous(idx) # index_add_ without alpha argument dest2 = dest.clone() dest.index_add_(0, idx, src) for i in range(idx.size(0)): dest2[idx[i]] += src[i] self.assertEqual(dest, dest2) # index_add_ with alpha argument dest2 = dest.clone() dest.index_add_(0, idx, src, alpha=2) for i in range(idx.size(0)): dest2[idx[i]] += src[i] * 2 self.assertEqual(dest, dest2) # FIXME: resolve comment below and move this to indexing test suite # add coverage for issue with atomic add that appeared only for # specific dtypes on cuda: # https://github.com/pytorch/pytorch/issues/29153 def test_index_add_all_dtypes(self): for device in get_all_device_types(): for dtype in get_all_math_dtypes(device): for idx_dtype in [torch.int, torch.long]: size = [5, 5] if dtype.is_floating_point or dtype.is_complex: tensor = torch.rand(size, dtype=dtype, device=device) elif dtype.is_signed: tensor = torch.randint(-5, 15, size, dtype=dtype, device=device) else: tensor = torch.randint(0, 10, size, dtype=dtype, device=device) # index_add calls atomicAdd on cuda. zeros = torch.zeros(size, dtype=dtype, device=device) added = zeros.index_add(0, torch.arange(0, size[0], dtype=idx_dtype, device=device), tensor) self.assertEqual(added, tensor) added = zeros.index_add(0, torch.arange(0, size[0], dtype=idx_dtype, device=device), tensor, alpha=-1) self.assertEqual(added, -tensor) # FIXME: move to shape ops test suite def test_unflatten(self): # test args: tensor, int, sizes self.assertEqual(torch.tensor([]).unflatten(0, (0, 1)), torch.empty(0, 1)) self.assertEqual(torch.tensor([1]).unflatten(0, (1, 1)), torch.tensor([[1]])) self.assertEqual(torch.tensor([1, 2, 3, 4]).unflatten(0, (2, 2)), torch.tensor([[1, 2], [3, 4]])) self.assertEqual(torch.tensor([1, 2, 3, 4]).unflatten(0, [2, 2]), torch.tensor([[1, 2], [3, 4]])) self.assertEqual(torch.tensor([1, 2, 3, 4]).unflatten(0, torch.Size([2, 2])), torch.tensor([[1, 2], [3, 4]])) self.assertEqual(torch.ones(2, 10).unflatten(1, (5, 2)), torch.ones(2, 5, 2)) self.assertEqual(torch.tensor([1, 2, 3, 4]).unflatten(0, (-1, 2)), torch.tensor([[1, 2], [3, 4]])) self.assertEqual(torch.ones(2, 10).unflatten(1, (5, -1)), torch.ones(2, 5, 2)) self.assertEqual(torch.ones(2, 10).unflatten(1, (-1,)), torch.ones(2, 10)) self.assertEqual(torch.ones(2, 3 * 4 * 5 * 6).unflatten(1, (3, 4, -1, 6)), torch.ones(2, 3, 4, 5, 6)) self.assertEqual(torch.ones(2, 0, 2).unflatten(1, (3, -1, 4, 5)), torch.ones(2, 3, 0, 4, 5, 2)) # test invalid args: tensor, str, sizes with self.assertRaisesRegex(TypeError, r"received an invalid combination of arguments"): torch.tensor([1]).unflatten('A', (1, 1)) # test invalid args: tensor, str, namedshape with self.assertRaisesRegex(RuntimeError, r"Name 'A' not found in Tensor\[None\]."): torch.ones(4).unflatten('A', (('A', 2), ('B', 2))) # test other invalid arguments with self.assertRaisesRegex(RuntimeError, r"sizes must be non-empty"): torch.tensor([1]).unflatten(0, []) with self.assertRaisesRegex(RuntimeError, r"Provided sizes \[2, 2\] don't multiply up to the size of dim 0 \(1\)"): torch.tensor([1]).unflatten(0, [2, 2]) with self.assertRaisesRegex(IndexError, r"dimension specified as 0 but tensor has no dimensions"): torch.tensor(1).unflatten(0, [0]) with self.assertRaisesRegex(RuntimeError, r"only one dimension can be inferred"): torch.randn(5, 10).unflatten(1, (-1, -1)) with self.assertRaisesRegex(RuntimeError, r"Provided sizes \[-1, 4\] don't multiply up to the size of dim 1 \(10\)"): torch.randn(5, 10).unflatten(1, (-1, 4)) with self.assertRaisesRegex(RuntimeError, r"the unspecified dimension size -1 can be any value and is ambiguous"): torch.randn(2, 0).unflatten(1, (2, -1, 0)) def test_structseq_repr(self): a = torch.arange(250).reshape(5, 5, 10) expected = """ torch.return_types.max( values=tensor([[ 40, 41, 42, 43, 44, 45, 46, 47, 48, 49], [ 90, 91, 92, 93, 94, 95, 96, 97, 98, 99], [140, 141, 142, 143, 144, 145, 146, 147, 148, 149], [190, 191, 192, 193, 194, 195, 196, 197, 198, 199], [240, 241, 242, 243, 244, 245, 246, 247, 248, 249]]), indices=tensor([[4, 4, 4, 4, 4, 4, 4, 4, 4, 4], [4, 4, 4, 4, 4, 4, 4, 4, 4, 4], [4, 4, 4, 4, 4, 4, 4, 4, 4, 4], [4, 4, 4, 4, 4, 4, 4, 4, 4, 4], [4, 4, 4, 4, 4, 4, 4, 4, 4, 4]]))""" self.assertEqual(repr(a.max(1)), textwrap.dedent(expected).strip()) def test_is_same_size(self): t1 = torch.empty(3, 4, 9, 10) t2 = torch.empty(3, 4) t3 = torch.empty(1, 9, 3, 3) t4 = torch.empty(3, 4, 9, 10) self.assertFalse(t1.is_same_size(t2)) self.assertFalse(t1.is_same_size(t3)) self.assertTrue(t1.is_same_size(t4)) def test_tensor_set(self): t1 = torch.tensor([]) t2 = torch.empty(3, 4, 9, 10).uniform_() t1.set_(t2) self.assertEqual(t1.storage()._cdata, t2.storage()._cdata) size = torch.Size([9, 3, 4, 10]) t1.set_(t2.storage(), 0, size) self.assertEqual(t1.size(), size) t1.set_(t2.storage(), 0, tuple(size)) self.assertEqual(t1.size(), size) self.assertEqual(t1.stride(), (120, 40, 10, 1)) stride = (10, 360, 90, 1) t1.set_(t2.storage(), 0, size, stride) self.assertEqual(t1.stride(), stride) t1.set_(t2.storage(), 0, size=size, stride=stride) self.assertEqual(t1.size(), size) self.assertEqual(t1.stride(), stride) # test argument names t1 = torch.tensor([]) # 1. case when source is tensor t1.set_(source=t2) self.assertEqual(t1.storage()._cdata, t2.storage()._cdata) # 2. case when source is storage t1.set_(source=t2.storage()) self.assertEqual(t1.storage()._cdata, t2.storage()._cdata) # 3. case when source is storage, and other args also specified t1.set_(source=t2.storage(), storage_offset=0, size=size, stride=stride) self.assertEqual(t1.size(), size) self.assertEqual(t1.stride(), stride) t1 = torch.tensor([True, True], dtype=torch.bool) t2 = torch.tensor([False, False], dtype=torch.bool) t1.set_(t2) self.assertEqual(t1.storage()._cdata, t2.storage()._cdata) def test_tensor_set_errors(self): f_cpu = torch.randn((2, 3), dtype=torch.float32) d_cpu = torch.randn((2, 3), dtype=torch.float64) # change dtype self.assertRaises(RuntimeError, lambda: f_cpu.set_(d_cpu.storage())) self.assertRaises(RuntimeError, lambda: f_cpu.set_(d_cpu.storage(), 0, d_cpu.size(), d_cpu.stride())) self.assertRaises(RuntimeError, lambda: f_cpu.set_(d_cpu)) # change device if torch.cuda.is_available(): f_cuda = torch.randn((2, 3), dtype=torch.float32, device='cuda') # cpu -> cuda self.assertRaises(RuntimeError, lambda: f_cpu.set_(f_cuda.storage())) self.assertRaises(RuntimeError, lambda: f_cpu.set_(f_cuda.storage(), 0, f_cuda.size(), f_cuda.stride())) self.assertRaises(RuntimeError, lambda: f_cpu.set_(f_cuda)) # cuda -> cpu self.assertRaises(RuntimeError, lambda: f_cuda.set_(f_cpu.storage())) self.assertRaises(RuntimeError, lambda: f_cuda.set_(f_cpu.storage(), 0, f_cpu.size(), f_cpu.stride())) self.assertRaises(RuntimeError, lambda: f_cuda.set_(f_cpu)) # FIXME: move this test test_testing.py (along with allclose testing) # NOTE: test_equal will be deprecated in favor of torch.testing.assert_close # once torch.testing is out of beta def test_equal(self): # Contiguous, 1D t1 = torch.tensor((3., 4., 9., 10.)) t2 = t1.contiguous() t3 = torch.tensor((1., 9., 3., 10.)) t4 = torch.tensor((3., 4., 9.)) t5 = torch.tensor([]) self.assertTrue(t1.equal(t2)) self.assertFalse(t1.equal(t3)) self.assertFalse(t1.equal(t4)) self.assertFalse(t1.equal(t5)) self.assertTrue(torch.equal(t1, t2)) self.assertFalse(torch.equal(t1, t3)) self.assertFalse(torch.equal(t1, t4)) self.assertFalse(torch.equal(t1, t5)) # Non contiguous, 2D s = torch.tensor(((1, 2, 3, 4), (5, 6, 7, 8))) s1 = s[:, 1:3] s2 = s1.clone() s3 = torch.tensor(((2, 3), (6, 7))) s4 = torch.tensor(((0, 0), (0, 0))) self.assertFalse(s1.is_contiguous()) self.assertTrue(s1.equal(s2)) self.assertTrue(s1.equal(s3)) self.assertFalse(s1.equal(s4)) self.assertTrue(torch.equal(s1, s2)) self.assertTrue(torch.equal(s1, s3)) self.assertFalse(torch.equal(s1, s4)) def test_element_size(self): byte = torch.ByteStorage().element_size() char = torch.CharStorage().element_size() short = torch.ShortStorage().element_size() int = torch.IntStorage().element_size() long = torch.LongStorage().element_size() float = torch.FloatStorage().element_size() double = torch.DoubleStorage().element_size() bool = torch.BoolStorage().element_size() bfloat16 = torch.BFloat16Storage().element_size() complexfloat = torch.ComplexFloatStorage().element_size() complexdouble = torch.ComplexDoubleStorage().element_size() self.assertEqual(byte, torch.ByteTensor().element_size()) self.assertEqual(char, torch.CharTensor().element_size()) self.assertEqual(short, torch.ShortTensor().element_size()) self.assertEqual(int, torch.IntTensor().element_size()) self.assertEqual(long, torch.LongTensor().element_size()) self.assertEqual(float, torch.FloatTensor().element_size()) self.assertEqual(double, torch.DoubleTensor().element_size()) self.assertEqual(bool, torch.BoolTensor().element_size()) self.assertEqual(bfloat16, torch.tensor([], dtype=torch.bfloat16).element_size()) self.assertEqual(complexfloat, torch.tensor([], dtype=torch.complex64).element_size()) self.assertEqual(complexdouble, torch.tensor([], dtype=torch.complex128).element_size()) self.assertGreater(byte, 0) self.assertGreater(char, 0) self.assertGreater(short, 0) self.assertGreater(int, 0) self.assertGreater(long, 0) self.assertGreater(float, 0) self.assertGreater(double, 0) self.assertGreater(bool, 0) self.assertGreater(bfloat16, 0) self.assertGreater(complexfloat, 0) self.assertGreater(complexdouble, 0) # These tests are portable, not necessarily strict for your system. self.assertEqual(byte, 1) self.assertEqual(char, 1) self.assertEqual(bool, 1) self.assertGreaterEqual(short, 2) self.assertGreaterEqual(int, 2) self.assertGreaterEqual(int, short) self.assertGreaterEqual(long, 4) self.assertGreaterEqual(long, int) self.assertGreaterEqual(double, float) def test_permute(self): orig = [1, 2, 3, 4, 5, 6, 7] perm = torch.randperm(7).tolist() x = torch.empty(*orig).fill_(0) new = [i - 1 for i in x.permute(*perm).size()] self.assertEqual(perm, new) self.assertEqual(x.size(), orig) def test_reversed(self): val = torch.arange(0, 10) self.assertEqual(reversed(val), torch.arange(9, -1, -1)) val = torch.arange(1, 10).view(3, 3) self.assertEqual(reversed(val), torch.tensor([[7, 8, 9], [4, 5, 6], [1, 2, 3]])) val = torch.tensor(42) self.assertEqual(reversed(val), torch.tensor(42)) def test_contains(self): x = torch.arange(0, 10) self.assertEqual(4 in x, True) self.assertEqual(12 in x, False) x = torch.arange(1, 10).view(3, 3) val = torch.arange(1, 4) self.assertEqual(val in x, True) val += 10 self.assertEqual(val in x, False) self.assertRaisesRegex( RuntimeError, "Tensor.__contains__ only supports Tensor or scalar, but you passed in a {}.".format(type("foo")), lambda: "foo" in x) self.assertRaisesRegex( RuntimeError, "Tensor.__contains__ only supports Tensor or scalar, but you passed in a {}.".format(type([1, 2])), lambda: [1, 2] in x) def test_deepcopy_parameter(self): from copy import deepcopy l = torch.nn.Linear(10, 1) s = l.state_dict(keep_vars=True) self.assertEqual(torch.nn.Parameter, type(s['weight'])) self.assertEqual(torch.nn.Parameter, type(s['bias'])) s2 = deepcopy(s) self.assertEqual(torch.nn.Parameter, type(s2['weight'])) self.assertEqual(torch.nn.Parameter, type(s2['bias'])) def test_pickle(self): import pickle a = torch.randn(5, 5) serialized = pickle.dumps(a) b = pickle.loads(serialized) self.assertEqual(a, b) def test_pickle_parameter(self): import pickle a = torch.nn.Parameter(torch.randn(5, 5)) serialized = pickle.dumps(a) b = pickle.loads(serialized) self.assertTrue(isinstance(b, torch.nn.Parameter)) self.assertEqual(a.requires_grad, b.requires_grad) self.assertEqual(a, b) def test_pickle_parameter_no_requires_grad(self): import pickle a = torch.nn.Parameter(torch.randn(5, 5), requires_grad=False) serialized = pickle.dumps(a) b = pickle.loads(serialized) self.assertTrue(isinstance(b, torch.nn.Parameter)) self.assertEqual(a.requires_grad, b.requires_grad) self.assertEqual(a, b) def test_pickle_dtype(self): t = torch.float32 serialized = pickle.dumps(t) b = pickle.loads(serialized) self.assertTrue(isinstance(b, torch.dtype)) self.assertEqual(id(b), id(t)) def test_pickle_size(self): a = torch.rand(10).size() serialized = pickle.dumps(a) b = pickle.loads(serialized) self.assertTrue(isinstance(b, torch.Size)) self.assertEqual(a, b) def test_pickle_function(self): # https://github.com/pytorch/pytorch/issues/37703 a = torch.tanh serialized = pickle.dumps(a) b = pickle.loads(serialized) self.assertEqual(a, b) def test_generator_cpu(self): # test default generators are equal self.assertEqual(torch.default_generator, torch.default_generator) # tests Generator API # manual_seed, seed, initial_seed, get_state, set_state g1 = torch.Generator() g2 = torch.Generator() g1.manual_seed(12345) g2.manual_seed(12345) self.assertEqual(g1.initial_seed(), g2.initial_seed()) g1.seed() g2.seed() self.assertNotEqual(g1.initial_seed(), g2.initial_seed()) g1 = torch.Generator() g2_state = g2.get_state() g2_randn = torch.randn(1, generator=g2) g1.set_state(g2_state) g1_randn = torch.randn(1, generator=g1) self.assertEqual(g1_randn, g2_randn) default_state = torch.default_generator.get_state() q = torch.empty(100) g1_normal = q.normal_() g2 = torch.Generator() g2.set_state(default_state) g2_normal = q.normal_(generator=g2) self.assertEqual(g1_normal, g2_normal) def test_invalid_generator_raises(self): self.assertRaises(RuntimeError, lambda: torch.Generator('opengl')) def _sobol_reference_samples(self, scramble: bool) -> torch.Tensor: if not scramble: # theoretical values from Joe Kuo 2010 return torch.tensor( [ [0., 0.], [0.5, 0.5], [0.75, 0.25], [0.25, 0.75], [0.375, 0.375], [0.875, 0.875], [0.625, 0.125], [0.125, 0.625], ], ) else: # theoretical values unknown: convergence properties checked return torch.tensor( [ [0.50860737, 0.29320504], [0.07116939, 0.89594537], [0.49354145, 0.11524881], [0.93097717, 0.70244044], [0.87266153, 0.23887917], [0.31021884, 0.57600391], [0.13687253, 0.42054182], [0.69931293, 0.77336788], ], ) def test_sobolengine_bounds(self, scramble: bool = False): engine = torch.quasirandom.SobolEngine(100, scramble=scramble, seed=123456) sample = engine.draw(512) self.assertTrue(torch.all(sample >= 0)) self.assertTrue(torch.all(sample <= 1)) def test_sobolengine_bounds_scrambled(self): self.test_sobolengine_bounds(scramble=True) def test_sobolengine_draw(self, scramble: bool = False): ref_sample = self._sobol_reference_samples(scramble=scramble) engine = torch.quasirandom.SobolEngine(2, scramble=scramble, seed=123456) sample = engine.draw(n=len(ref_sample)) self.assertEqual(sample, ref_sample) self.assertEqual(engine.num_generated, len(ref_sample)) def test_sobolengine_draw_scrambled(self): self.test_sobolengine_draw(scramble=True) def test_sobolengine_first_point(self): for dtype in (torch.float, torch.double): engine = torch.quasirandom.SobolEngine(2, scramble=False) sample = engine.draw(1, dtype=dtype) self.assertTrue(torch.all(sample == 0)) self.assertEqual(sample.dtype, dtype) for dtype in (torch.float, torch.double): engine = torch.quasirandom.SobolEngine(2, scramble=True, seed=123456) sample = engine.draw(1, dtype=dtype) self.assertTrue(torch.all(sample != 0)) self.assertEqual(sample.dtype, dtype) def test_sobolengine_continuing(self, scramble: bool = False): ref_sample = self._sobol_reference_samples(scramble=scramble) engine = torch.quasirandom.SobolEngine(2, scramble=scramble, seed=123456) n_half = len(ref_sample) // 2 _ = engine.draw(n=n_half) sample = engine.draw(n=n_half) torch.testing.assert_close(sample, ref_sample[n_half:]) def test_sobolengine_continuing_scrambled(self): self.test_sobolengine_continuing(scramble=True) def test_sobolengine_reset(self, scramble: bool = False): ref_sample = self._sobol_reference_samples(scramble=scramble) engine = torch.quasirandom.SobolEngine(2, scramble=scramble, seed=123456) _ = engine.draw(n=len(ref_sample) // 2) engine.reset() self.assertEqual(engine.num_generated, 0) sample = engine.draw(n=len(ref_sample)) torch.testing.assert_close(sample, ref_sample) def test_sobolengine_reset_scrambled(self): self.test_sobolengine_reset(scramble=True) def test_sobolengine_fast_forward(self, scramble: bool = False): ref_sample = self._sobol_reference_samples(scramble=scramble) engine = torch.quasirandom.SobolEngine(2, scramble=scramble, seed=123456) engine.fast_forward(4) sample = engine.draw(n=4) torch.testing.assert_close(sample, ref_sample[4:]) # alternate fast forwarding with sampling engine.reset() even_draws = [] for i in range(8): if i % 2 == 0: even_draws.append(engine.draw()) else: engine.fast_forward(1) torch.testing.assert_close( ref_sample[[i for i in range(8) if i % 2 == 0]], torch.from_numpy(np.concatenate(even_draws)), ) def test_sobolengine_fast_forward_scrambled(self): self.test_sobolengine_fast_forward(scramble=True) def test_sobolengine_distribution(self, scramble=False): d = 50 engine = torch.quasirandom.SobolEngine(d, scramble=scramble, seed=123456) sample = engine.draw(1024) torch.testing.assert_close( torch.mean(sample, dim=0), torch.full((d,), 0.5), atol=2, rtol=2 ) torch.testing.assert_close( np.percentile(sample, 25, axis=0), np.repeat(0.25, d), atol=2, rtol=2 ) torch.testing.assert_close( np.percentile(sample, 75, axis=0), np.repeat(0.75, d), atol=2, rtol=2 ) def test_sobolengine_distribution_scrambled(self): self.test_sobolengine_distribution(scramble=True) def test_sobolengine_draw_base2(self, scramble=False): ref_sample = self._sobol_reference_samples(scramble=scramble) engine = torch.quasirandom.SobolEngine(2, scramble=scramble, seed=123456) sample = engine.draw_base2(2) self.assertEqual(ref_sample[:4], sample) # resampling still having N=2**n sample = engine.draw_base2(2) self.assertEqual(ref_sample[4:8], sample) def test_sobolengine_draw_base2_scrambled(self): self.test_sobolengine_draw_base2(scramble=True) def test_sobolengine_raise(self): maxdim = torch.quasirandom.SobolEngine.MAXDIM with self.assertRaises(ValueError): torch.quasirandom.SobolEngine(maxdim + 1) def test_sobolengine_high_dim(self): engine = torch.quasirandom.SobolEngine(1111, scramble=False, seed=123456) samples1 = engine.draw() vals1, counts1 = torch.unique(samples1, return_counts=True) samples2 = engine.draw() vals2, counts2 = torch.unique(samples2, return_counts=True) self.assertEqual(vals1.item(), 0.0) self.assertEqual(counts1.item(), 1111) self.assertEqual(vals2.item(), 0.5) self.assertEqual(counts1.item(), 1111) def test_parsing_int64(self): # accepts integer arguments x = torch.cumsum(torch.ones(5, 5), 0) self.assertEqual(x, torch.cumsum(torch.ones(5, 5), torch.tensor(0))) # doesn't accept floating point variables self.assertRaises(TypeError, lambda: torch.cumsum(torch.ones(5, 5), torch.tensor(0.))) def test_parsing_double(self): # accepts floating point and integer arguments x = torch.randn(2, 3) torch.isclose(x, x, 1, 1) self.assertTrue(torch.isclose(x, x, 1, 1).all()) self.assertTrue(torch.isclose(x, x, 1.5, 1.).all()) # accepts floating point and integer tensors self.assertTrue(torch.isclose(x, x, torch.tensor(1), torch.tensor(1)).all()) self.assertTrue(torch.isclose(x, x, torch.tensor(1.5), torch.tensor(1.)).all()) # doesn't accept variables with requires_grad self.assertRaises(TypeError, lambda: torch.isclose(x, x, torch.tensor(1.5), torch.tensor(1., requires_grad=True)).all()) def test_parsing_intlist(self): # parse with integer variables self.assertEqual(torch.Size([3, 4]), torch.ones((torch.tensor(3), torch.tensor(4))).shape) self.assertEqual(torch.Size([3, 4]), torch.ones(torch.tensor(3), torch.tensor(4)).shape) # parse with numpy integers self.assertEqual(torch.Size([3, 4]), torch.ones((np.array(3), np.int64(4))).shape) self.assertEqual(torch.Size([3, 4]), torch.ones(np.array(3), np.int64(4)).shape) self.assertEqual(torch.Size([3, 4]), torch.ones((np.int64(3), np.array(4))).shape) self.assertEqual(torch.Size([3, 4]), torch.ones(np.int64(3), np.array(4)).shape) # fail parse with float variables self.assertRaises(TypeError, lambda: torch.ones((torch.tensor(3.), torch.tensor(4)))) # fail parse with numpy floats self.assertRaises(TypeError, lambda: torch.ones((np.float(3.), torch.tensor(4)))) self.assertRaises(TypeError, lambda: torch.ones((np.array(3.), torch.tensor(4)))) # fail parse with > 1 element variables self.assertRaises(TypeError, lambda: torch.ones(torch.tensor(3, 3))) self.assertRaises(TypeError, lambda: torch.ones((torch.tensor(3, 3)))) self.assertRaises(TypeError, lambda: torch.ones(np.array(3, 3))) self.assertRaises(TypeError, lambda: torch.ones((np.array(3, 3)))) # fail parse with additional positional args after intlist arg self.assertRaisesRegex(TypeError, "received an invalid combination of arguments", lambda: torch.LongTensor((6, 0), 1, 1, 0)) self.assertRaisesRegex(TypeError, "missing 1 required positional arguments", lambda: torch.tensor().new_zeros((5, 5), 0)) def test_from_buffer(self): a = bytearray([1, 2, 3, 4]) self.assertEqual(torch.ByteStorage.from_buffer(a).tolist(), [1, 2, 3, 4]) shorts = torch.ShortStorage.from_buffer(a, 'big') self.assertEqual(shorts.size(), 2) self.assertEqual(shorts.tolist(), [258, 772]) ints = torch.IntStorage.from_buffer(a, 'little') self.assertEqual(ints.size(), 1) self.assertEqual(ints[0], 67305985) f = bytearray([0x40, 0x10, 0x00, 0x00]) floats = torch.FloatStorage.from_buffer(f, 'big') self.assertEqual(floats.size(), 1) self.assertEqual(floats[0], 2.25) f = bytearray([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x10, 0x40]) bools = torch.BoolStorage.from_buffer(f, 'big') self.assertEqual(bools.size(), 8) self.assertEqual(bools.tolist(), [False, True, True, True, True, True, True, True]) self.assertEqual(bools.type(), 'torch.BoolStorage') self.assertTrue(isinstance(bools, torch.BoolStorage)) f = bytearray(b'\x80\x02\x8a\nl\xfc\x9cF\xf9 j\xa8P\x19.\x80\x02M\xe9') bools = torch.BoolStorage.from_buffer(f, 'big') self.assertEqual(bools.size(), 19) f = bytearray(b'\0x4A') bools = torch.BoolStorage.from_buffer(f, 'big') self.assertEqual(bools.size(), 4) self.assertEqual(bools.tolist(), [False, True, True, True]) bytes = torch.ByteStorage.from_buffer(a) self.assertEqual(bytes.nbytes(), 4) self.assertEqual(bytes.tolist(), [1, 2, 3, 4]) self.assertTrue(isinstance(bytes, torch.ByteStorage)) def test_storage_error(self): quantized_storages = [ torch.QInt32Storage, torch.QInt8Storage, torch.QUInt2x4Storage, torch.QUInt4x2Storage, torch.QUInt8Storage, ] with self.assertRaisesRegex(RuntimeError, r"Only child classes of _LegacyStorage can be instantiated"): torch.storage._LegacyStorage() for storage_class in torch._storage_classes: if storage_class in [torch._UntypedStorage, torch._TypedStorage]: continue device = 'cuda' if storage_class.__module__ == 'torch.cuda' else 'cpu' dtype = storage_class.dtype if device == 'cuda' and not torch.cuda.is_available(): continue # Legacy <type>Storage constructor errors with self.assertRaisesRegex(RuntimeError, r"'device' cannot be specified"): storage_class(device='cpu') with self.assertRaisesRegex(RuntimeError, r"'dtype' cannot be specified"): storage_class(dtype=torch.float) with self.assertRaisesRegex(TypeError, r"got an unexpected keyword"): storage_class(sdlkjf=torch.float) with self.assertRaisesRegex(RuntimeError, r"Too many positional arguments"): storage_class(0, 0) with self.assertRaisesRegex(TypeError, r"invalid data type"): storage_class('string') with self.assertRaisesRegex(TypeError, r"Argument type not recognized"): storage_class(torch.tensor([])) s = storage_class() with self.assertRaisesRegex(RuntimeError, r"No positional arguments"): storage_class(0, wrap_storage=s._untyped()) with self.assertRaisesRegex(TypeError, r"must be _UntypedStorage"): storage_class(wrap_storage=s) if torch.cuda.is_available(): if storage_class in quantized_storages: with self.assertRaisesRegex(RuntimeError, r"Cannot create CUDA storage with quantized dtype"): s.cuda() else: if s.is_cuda: s_other_device = s.cpu() else: s_other_device = s.cuda() with self.assertRaisesRegex(RuntimeError, r"Device of 'wrap_storage' must be"): storage_class(wrap_storage=s_other_device._untyped()) # _TypedStorage constructor errors with self.assertRaisesRegex(RuntimeError, r"No positional arguments"): torch._TypedStorage(0, wrap_storage=s._untyped(), dtype=dtype) with self.assertRaisesRegex(RuntimeError, r"Argument 'dtype' must be specified"): torch._TypedStorage(wrap_storage=s._untyped()) with self.assertRaisesRegex(TypeError, r"Argument 'dtype' must be torch.dtype"): torch._TypedStorage(wrap_storage=s._untyped(), dtype=0) with self.assertRaisesRegex(RuntimeError, r"Argument 'device' should not be specified"): torch._TypedStorage(wrap_storage=s._untyped(), dtype=dtype, device=device) with self.assertRaisesRegex(TypeError, r"Argument 'wrap_storage' must be _UntypedStorage"): torch._TypedStorage(wrap_storage=s, dtype=dtype) with self.assertRaisesRegex(RuntimeError, r"Storage device not recognized"): torch._TypedStorage(dtype=dtype, device='xla') if torch.cuda.is_available(): if storage_class in quantized_storages: with self.assertRaisesRegex(RuntimeError, r"Cannot create CUDA storage with quantized dtype"): torch._TypedStorage(dtype=dtype, device='cuda') with self.assertRaisesRegex(TypeError, r"Argument type not recognized"): torch._TypedStorage(torch.tensor([]), dtype=dtype, device=device) with self.assertRaisesRegex(RuntimeError, r"Too many positional arguments"): torch._TypedStorage(0, 0, dtype=dtype, device=device) if isinstance(s, torch._TypedStorage): s_other = torch._TypedStorage([1, 2, 3, 4], device=device, dtype=dtype) with self.assertRaisesRegex(RuntimeError, r'cannot set item'): s.fill_(s_other) def test_storage_error_no_attribute(self): storage_classes = [ torch.cuda.ByteStorage, torch.cuda.FloatStorage, ] for storage_class in storage_classes: with self.assertRaisesRegex(RuntimeError, r'Not available for CUDA storage'): storage_class.from_buffer() with self.assertRaisesRegex(RuntimeError, r'Not available for CUDA storage'): storage_class._new_with_weak_ptr() with self.assertRaisesRegex(RuntimeError, r'Not available for CUDA storage'): storage_class._new_shared_filename(0, 0, 0) def test_storage_casts(self): storage = torch.IntStorage([-1, 0, 1, 2, 3, 4]) self.assertEqual(storage.size(), 6) self.assertEqual(storage.tolist(), [-1, 0, 1, 2, 3, 4]) self.assertEqual(storage.type(), 'torch.IntStorage') self.assertIs(storage.dtype, torch.int32) floatStorage = storage.float() self.assertEqual(floatStorage.size(), 6) self.assertEqual(floatStorage.tolist(), [-1, 0, 1, 2, 3, 4]) self.assertEqual(floatStorage.type(), 'torch.FloatStorage') self.assertEqual(floatStorage.int().tolist(), [-1, 0, 1, 2, 3, 4]) self.assertIs(floatStorage.dtype, torch.float32) halfStorage = storage.half() self.assertEqual(halfStorage.size(), 6) self.assertEqual(halfStorage.tolist(), [-1, 0, 1, 2, 3, 4]) self.assertEqual(halfStorage.type(), 'torch.HalfStorage') self.assertEqual(halfStorage.int().tolist(), [-1, 0, 1, 2, 3, 4]) self.assertIs(halfStorage.dtype, torch.float16) bfloat16Storage = storage.bfloat16() self.assertEqual(bfloat16Storage.size(), 6) self.assertEqual(bfloat16Storage.tolist(), [-1, 0, 1, 2, 3, 4]) self.assertEqual(bfloat16Storage.type(), 'torch.BFloat16Storage') self.assertEqual(bfloat16Storage.int().tolist(), [-1, 0, 1, 2, 3, 4]) self.assertIs(bfloat16Storage.dtype, torch.bfloat16) longStorage = storage.long() self.assertEqual(longStorage.size(), 6) self.assertEqual(longStorage.tolist(), [-1, 0, 1, 2, 3, 4]) self.assertEqual(longStorage.type(), 'torch.LongStorage') self.assertEqual(longStorage.int().tolist(), [-1, 0, 1, 2, 3, 4]) self.assertIs(longStorage.dtype, torch.int64) shortStorage = storage.short() self.assertEqual(shortStorage.size(), 6) self.assertEqual(shortStorage.tolist(), [-1, 0, 1, 2, 3, 4]) self.assertEqual(shortStorage.type(), 'torch.ShortStorage') self.assertEqual(shortStorage.int().tolist(), [-1, 0, 1, 2, 3, 4]) self.assertIs(shortStorage.dtype, torch.int16) doubleStorage = storage.double() self.assertEqual(doubleStorage.size(), 6) self.assertEqual(doubleStorage.tolist(), [-1.0, 0.0, 1.0, 2.0, 3.0, 4.0]) self.assertEqual(doubleStorage.type(), 'torch.DoubleStorage') self.assertEqual(doubleStorage.int().tolist(), [-1, 0, 1, 2, 3, 4]) self.assertIs(doubleStorage.dtype, torch.float64) charStorage = storage.char() self.assertEqual(charStorage.size(), 6) self.assertEqual(charStorage.tolist(), [-1.0, 0.0, 1.0, 2.0, 3.0, 4.0]) self.assertEqual(charStorage.type(), 'torch.CharStorage') self.assertEqual(charStorage.int().tolist(), [-1, 0, 1, 2, 3, 4]) self.assertIs(charStorage.dtype, torch.int8) byteStorage = storage.byte() self.assertEqual(byteStorage.size(), 6) self.assertEqual(byteStorage.tolist(), [255, 0, 1, 2, 3, 4]) self.assertEqual(byteStorage.type(), 'torch.ByteStorage') self.assertEqual(byteStorage.int().tolist(), [255, 0, 1, 2, 3, 4]) self.assertIs(byteStorage.dtype, torch.uint8) boolStorage = storage.bool() self.assertEqual(boolStorage.size(), 6) self.assertEqual(boolStorage.tolist(), [True, False, True, True, True, True]) self.assertEqual(boolStorage.type(), 'torch.BoolStorage') self.assertEqual(boolStorage.int().tolist(), [1, 0, 1, 1, 1, 1]) self.assertIs(boolStorage.dtype, torch.bool) complexfloat_storage = torch.ComplexFloatStorage([-1, 0, 1 + 2j, 2.5j, 3.5, 4 - 2j]) self.assertEqual(complexfloat_storage.size(), 6) self.assertEqual(complexfloat_storage.tolist(), [-1, 0, 1 + 2j, 2.5j, 3.5, 4 - 2j]) self.assertEqual(complexfloat_storage.type(), 'torch.ComplexFloatStorage') self.assertIs(complexfloat_storage.dtype, torch.complex64) complexdouble_storage = complexfloat_storage.complex_double() self.assertEqual(complexdouble_storage.size(), 6) self.assertEqual(complexdouble_storage.tolist(), [-1, 0, 1 + 2j, 2.5j, 3.5, 4 - 2j]) self.assertEqual(complexdouble_storage.type(), 'torch.ComplexDoubleStorage') self.assertIs(complexdouble_storage.dtype, torch.complex128) def test_from_file(self): def assert_with_filename(filename): size = 10000 s1 = torch.FloatStorage.from_file(filename, True, size) t1 = torch.FloatTensor(s1).copy_(torch.randn(size)) self.assertEqual(s1.data_ptr(), torch.FloatTensor(s1).data_ptr()) # check mapping s2 = torch.FloatStorage.from_file(filename, True, size) t2 = torch.FloatTensor(s2) self.assertEqual(t1, t2, atol=0, rtol=0) # check changes to t1 from t2 rnum = random.uniform(-1, 1) t1.fill_(rnum) self.assertEqual(t1, t2, atol=0, rtol=0) # check changes to t2 from t1 rnum = random.uniform(-1, 1) t2.fill_(rnum) self.assertEqual(t1, t2, atol=0, rtol=0) # release the tensors del s1, t1, s2, t2 with TemporaryFileName() as fname: assert_with_filename(fname) if IS_FILESYSTEM_UTF8_ENCODING: with TemporaryDirectoryName(suffix='中文') as dname, TemporaryFileName(dir=dname) as fname: assert_with_filename(fname) def test_torch_from_file(self): def assert_with_filename(filename): size = 10000 s1 = torch.from_file(filename, True, size, dtype=torch.float) t1 = torch.FloatTensor(s1).copy_(torch.randn(size)) # check mapping s2 = torch.from_file(filename, True, size, dtype=torch.float) t2 = torch.FloatTensor(s2) self.assertEqual(t1, t2, atol=0, rtol=0) # check changes to t1 from t2 rnum = random.uniform(-1, 1) t1.fill_(rnum) self.assertEqual(t1, t2, atol=0, rtol=0) # check changes to t2 from t1 rnum = random.uniform(-1, 1) t2.fill_(rnum) self.assertEqual(t1, t2, atol=0, rtol=0) # release the tensors del s1, t1, s2, t2 with TemporaryFileName() as fname: assert_with_filename(fname) if IS_FILESYSTEM_UTF8_ENCODING: with TemporaryDirectoryName(suffix='中文') as dname, TemporaryFileName(dir=dname) as fname: assert_with_filename(fname) def test_print(self): default_type = torch.tensor([]).type() for t in torch._tensor_classes: if t == torch.HalfTensor: continue # HalfTensor does not support fill if t.is_sparse: continue if t.is_cuda and not torch.cuda.is_available(): continue obj = t(100, 100).fill_(1) obj.__repr__() str(obj) # test half tensor obj = torch.rand(100, 100, device='cpu').half() obj.__repr__() str(obj) for t in torch._storage_classes: if t == torch.BFloat16Storage: continue # Fix once fill is enabled for bfloat16 if t.is_cuda and not torch.cuda.is_available(): continue if t == torch.BoolStorage or t == torch.cuda.BoolStorage: obj = t(100).fill_(True) else: obj = t(100).fill_(1) obj.__repr__() str(obj) # test complex tensor # complex tensor print uses two formatters, one for real values # and the other for imag values. this is consistent with numpy x = torch.tensor([2.3 + 4j, 7 + 6j]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([2.3000+4.j, 7.0000+6.j])''') # test complex half tensor x = torch.tensor([1.25 + 4j, -7. + 6j], dtype=torch.chalf) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([ 1.2500+4.j, -7.0000+6.j], dtype=torch.complex32)''') # test scientific notation for complex tensors x = torch.tensor([1e28 + 2j , -1e-28j]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1.0000e+28+2.0000e+00j, -0.0000e+00-1.0000e-28j])''') # test big integer x = torch.tensor(2341234123412341) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor(2341234123412341)''') # test scientific notation x = torch.tensor([1e28, 1e-28]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1.0000e+28, 1.0000e-28])''') # test scientific notation using set_printoptions x = torch.tensor([1e2, 1e-2]) torch.set_printoptions(sci_mode=True) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1.0000e+02, 1.0000e-02])''') torch.set_printoptions(sci_mode=False) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([ 100.0000, 0.0100])''') torch.set_printoptions(sci_mode=None) # reset to the default value # test no leading space if all elements positive x = torch.tensor([1, 2]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1, 2])''') # test for leading space if there are negative elements x = torch.tensor([1, -2]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([ 1, -2])''') # test inf and nan x = torch.tensor([4, inf, 1.5, -inf, 0, nan, 1]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([4.0000, inf, 1.5000, -inf, 0.0000, nan, 1.0000])''') y = torch.tensor([4, inf, complex(1.5, inf), complex(-inf, 4), 0, complex(nan, inf), complex(3, nan)]) self.assertEqual(y.__repr__(), str(y)) expected_str = '''\ tensor([4.0000+0.j, inf+0.j, 1.5000+infj, -inf+4.j, 0.0000+0.j, nan+infj, 3.0000+nanj])''' self.assertExpectedInline(str(y), expected_str) # test dtype torch.set_default_dtype(torch.float) x = torch.tensor([1e-324, 1e-323, 1e-322, 1e307, 1e308, 1e309], dtype=torch.float64) self.assertEqual(x.__repr__(), str(x)) expected_str = '''\ tensor([ 0.0000e+00, 9.8813e-324, 9.8813e-323, 1.0000e+307, 1.0000e+308, inf], dtype=torch.float64)''' self.assertExpectedInline(str(x), expected_str) # test changing default dtype torch.set_default_dtype(torch.float64) self.assertEqual(x.__repr__(), str(x)) expected_str = '''\ tensor([ 0.0000e+00, 9.8813e-324, 9.8813e-323, 1.0000e+307, 1.0000e+308, inf])''' self.assertExpectedInline(str(x), expected_str) # test summary x = torch.zeros(10000) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([0., 0., 0., ..., 0., 0., 0.])''') # test internal summary function x = torch.rand(1, 20, 5, 30) summary = torch._tensor_str.get_summarized_data(x) self.assertEqual(summary.shape, (1, 6, 5, 6)) first_and_last = [0, 1, 2, -3, -2, -1] self.assertEqual(summary, x[:, first_and_last][..., first_and_last]) # test device if torch.cuda.is_available(): x = torch.tensor([123], device='cuda:0') self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([123], device='cuda:0')''') # test changing default to cuda torch.set_default_tensor_type(torch.cuda.FloatTensor) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([123])''') # test printing a tensor on a different gpu than current one. if torch.cuda.device_count() >= 2: with torch.cuda.device(1): self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([123], device='cuda:0')''') # test printing cpu tensor when default device is cuda y = torch.tensor([123], device='cpu') self.assertEqual(y.__repr__(), str(y)) self.assertExpectedInline(str(y), '''tensor([123], device='cpu')''') torch.set_default_tensor_type(default_type) # test integral floats and requires_grad x = torch.tensor([123.], requires_grad=True) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([123.], requires_grad=True)''') # test non-contiguous print # sliced tensor should have > PRINT_OPTS.threshold elements x = torch.ones(100, 2, 2, 10) y = x.as_strided(size=(100, 2, 10), stride=(2 * 2 * 10, 2 * 10, 1)) self.assertEqual(str(y), y.__repr__()) expected_str = '''\ tensor([[[1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.]], [[1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.]], [[1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.]], ..., [[1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.]], [[1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.]], [[1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.]]])\ ''' self.assertExpectedInline(str(y), expected_str) x = torch.ones(100, 2, 2, 10) * (1 + 1j) y = x.as_strided(size=(100, 2, 10), stride=(2 * 2 * 10, 2 * 10, 1)) self.assertEqual(str(y), y.__repr__()) expected_str = '''\ tensor([[[1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j], [1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j]], [[1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j], [1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j]], [[1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j], [1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j]], ..., [[1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j], [1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j]], [[1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j], [1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j]], [[1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j], [1.+1.j, 1.+1.j, 1.+1.j, ..., 1.+1.j, 1.+1.j, 1.+1.j]]])\ ''' self.assertExpectedInline(str(y), expected_str) # test print 0-dim tensor: there's no 0-dim in Numpy, we match arrayprint style x = torch.tensor(0.00002) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor(2.0000e-05)''') # test print boolean tensor x = torch.tensor([True]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([True])''') x = torch.tensor(True) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor(True)''') # [Numpy] test print float in sci_mode when min < 0.0001. x = torch.tensor([0.00002]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([2.0000e-05])''') # [Numpy] test print complex in sci_mode when real_min < 0.0001 and (or) imag_min < 0.0001. x = torch.tensor([0.00002]) * (1 + 1j) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([2.0000e-05+2.0000e-05j])''') # [Numpy] test print float in sci_mode when max > 1e8. # TODO: Pytorch uses fixed precision to print, while Numpy uses dragon4_scientific # to do automatic trimming and padding. x = torch.tensor([123456789.]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1.2346e+08])''') # [Numpy] test print float in sci_mode when max / min > 1000. x = torch.tensor([0.01, 11]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1.0000e-02, 1.1000e+01])''') # [Numpy] test print int max / min > 1000, no sci_mode x = torch.tensor([1, 1010]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([ 1, 1010])''') # [Numpy] test print int > 1e8, no sci_mode x = torch.tensor([1000000000]) # 1e9 self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1000000000])''') # [Numpy] test printing float in int_mode x = torch.tensor([1., 1000.]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([ 1., 1000.])''') # [Numpy] test printing float in int_mode in sci format when max / min > 1000. x = torch.tensor([1., 1010.]) self.assertEqual(x.__repr__(), str(x)) self.assertExpectedInline(str(x), '''tensor([1.0000e+00, 1.0100e+03])''') def test_sizeof(self) -> None: sizeof_empty = torch.randn(0).storage().__sizeof__() sizeof_10 = torch.randn(10).storage().__sizeof__() sizeof_100 = torch.randn(100).storage().__sizeof__() self.assertEqual((sizeof_100 - sizeof_empty) // (sizeof_10 - sizeof_empty), 10) self.assertEqual((sizeof_100 - sizeof_empty) % (sizeof_10 - sizeof_empty), 0) sizeof_empty = torch.randn(0).to(torch.uint8).storage().__sizeof__() sizeof_10 = torch.randn(10).to(torch.uint8).storage().__sizeof__() sizeof_100 = torch.randn(100).to(torch.uint8).storage().__sizeof__() self.assertEqual((sizeof_100 - sizeof_empty) // (sizeof_10 - sizeof_empty), 10) self.assertEqual((sizeof_100 - sizeof_empty) % (sizeof_10 - sizeof_empty), 0) def test_iter(self) -> None: x = torch.randn(5, 5) for i, sub in enumerate(x): self.assertEqual(sub, x[i]) x = torch.tensor([]) self.assertEqual(list(x), []) def test_new(self) -> None: x = torch.autograd.Variable(torch.tensor([])) y = torch.autograd.Variable(torch.randn(4, 4)) z = torch.autograd.Variable(torch.IntTensor([1, 2, 3])) self.assertEqual(x.new().shape, [0]) self.assertEqual(x.new(), x) self.assertEqual(x.new(1, 2).shape, [1, 2]) self.assertEqual(x.new(torch.Size([3, 4])).shape, [3, 4]) self.assertEqual(x.new([3, 4]).shape, [2]) self.assertEqual(x.new([3, 4]).tolist(), [3, 4]) self.assertEqual(x.new((3, 4)).tolist(), [3, 4]) self.assertEqual(x.new([np.int32(3), np.float64(4)]).tolist(), [3, 4]) self.assertEqual(x.new(np.array((3, 4))).tolist(), [3, 4]) self.assertEqual(x.new([z[2], z[0] + 3]).tolist(), [3, 4]) self.assertEqual(x.new(size=(3, 4)).shape, [3, 4]) self.assertEqual(x.new(()).shape, [0]) self.assertEqual(x.new(y.storage()).data_ptr(), y.data_ptr()) self.assertEqual(x.new(y).data_ptr(), y.data_ptr()) self.assertIsNot(x.new(y), y) self.assertRaises(TypeError, lambda: x.new(z)) # TypeError would be better self.assertRaises(RuntimeError, lambda: x.new(z.storage())) @unittest.skipIf(PYTORCH_CUDA_MEMCHECK, "is_pinned uses failure to detect pointer property") def test_pin_memory(self): x = torch.randn(3, 5) self.assertFalse(x.is_pinned()) if not torch.cuda.is_available(): self.assertRaises(RuntimeError, lambda: x.pin_memory()) else: pinned = x.pin_memory() self.assertTrue(pinned.is_pinned()) self.assertEqual(pinned, x) self.assertNotEqual(pinned.data_ptr(), x.data_ptr()) # test that pin_memory on already pinned tensor has no effect self.assertIs(pinned, pinned.pin_memory()) self.assertEqual(pinned.data_ptr(), pinned.pin_memory().data_ptr()) def test_error_msg_type_translation(self): with self.assertRaisesRegex( RuntimeError, # message includes both Double and Long '(?=.*Double)(?=.*Long)'): # Calls model with a LongTensor input but DoubleTensor weights input = torch.zeros(1, 1, 1, 6, dtype=torch.long) weight = torch.nn.Parameter(torch.zeros(1, 1, 1, 3, dtype=torch.double)) model = torch.nn.Conv2d(1, 1, (1, 3), stride=1, padding=0, bias=False) model.weight = weight out = model(input) def test_apply(self): x = torch.arange(1, 6) res = x.clone().apply_(lambda k: k + k) self.assertEqual(res, x * 2) self.assertRaises(TypeError, lambda: x.apply_(lambda k: "str")) def test_map(self): x = torch.autograd.Variable(torch.randn(3, 3)) y = torch.autograd.Variable(torch.randn(3)) res = x.clone() res.map_(y, lambda a, b: a + b) self.assertEqual(res, x + y) self.assertRaisesRegex(TypeError, "not callable", lambda: res.map_(y, "str")) def test_map2(self): x = torch.autograd.Variable(torch.randn(3, 3)) y = torch.autograd.Variable(torch.randn(3)) z = torch.autograd.Variable(torch.randn(1, 3)) res = x.clone() res.map2_(y, z, lambda a, b, c: a + b * c) self.assertEqual(res, x + y * z) z.requires_grad = True self.assertRaisesRegex( RuntimeError, "requires grad", lambda: res.map2_(y, z, lambda a, b, c: a + b * c)) def test_Size(self): x = torch.Size([1, 2, 3]) self.assertIsInstance(x, tuple) self.assertEqual(x[0], 1) self.assertEqual(x[1], 2) self.assertEqual(x[2], 3) self.assertEqual(len(x), 3) self.assertRaises(TypeError, lambda: torch.Size(torch.ones(3))) self.assertIsInstance(x * 2, torch.Size) self.assertIsInstance(x[:-1], torch.Size) self.assertIsInstance(x + x, torch.Size) def test_Size_scalar(self): three = torch.tensor(3) two = torch.tensor(2) x = torch.Size([0, 1, two, three, 4]) for i in range(1, 5): self.assertEqual(x[i], i) def test_Size_iter(self): for sizes in [iter([1, 2, 3, 4, 5]), range(1, 6)]: x = torch.Size(sizes) for i in range(0, 5): self.assertEqual(x[i], i + 1) def test_t_not_2d_error(self): self.assertRaises(RuntimeError, lambda: torch.randn(2, 3, 4).t()) self.assertRaises(RuntimeError, lambda: torch.randn(2, 3, 4).t_()) # skip this test for now as it affects all tests @unittest.skipIf(True, "flush_denormal not supported") def test_set_flush_denormal(self): tiny_float = 1e-42 tiny_double = 1e-320 float_tensor = torch.FloatTensor([1.0, tiny_float]) double_tensor = torch.DoubleTensor([1.0, tiny_float, tiny_double]) self.assertEqual(float_tensor[0], 1.0, atol=0.0, rtol=0) self.assertEqual(float_tensor[1], tiny_float, atol=tiny_float / 16, rtol=0) self.assertEqual(double_tensor[0], 1.0, atol=0.0, rtol=0) self.assertEqual(double_tensor[1], tiny_float, atol=0.0, rtol=0) self.assertEqual(double_tensor[2], tiny_double, atol=0.0, rtol=0) torch.set_flush_denormal(True) self.assertEqual(float_tensor[0], 1.0, atol=0.0, rtol=0) self.assertEqual(float_tensor[1], 0.0, atol=0.0, rtol=0) # tiny_float to zero self.assertEqual(double_tensor[0], 1.0, atol=0.0, rtol=0) # tiny_float is not converted to zero in double type self.assertEqual(double_tensor[1], tiny_float, atol=0.0, rtol=0) self.assertEqual(double_tensor[2], 0.0, atol=0.0, rtol=0) # tiny_double to zero torch.set_flush_denormal(False) def test_show_config(self): # We can't usefully test the output; just make sure this doesn't crash torch.__config__.show() @unittest.skipIf(IS_FBCODE, "CXX_FLAGS is only for OSS build.") def test_cxx_flags(self): torch.__config__._cxx_flags() def test_parallel_info(self): torch.__config__.parallel_info() @slowTest def test_slow_test(self): # Just a smoketest to make sure our slowTest decorator works. pass def test_is_nonzero(self): with self.assertRaisesRegex(RuntimeError, "Boolean value of Tensor with no values is ambiguous"): torch.tensor([]).is_nonzero() with self.assertRaisesRegex(RuntimeError, "Boolean value of Tensor with more than one value is ambiguous"): torch.tensor([0, 0]).is_nonzero() self.assertFalse(torch.tensor(0).is_nonzero()) self.assertTrue(torch.tensor(1).is_nonzero()) self.assertFalse(torch.tensor([0]).is_nonzero()) self.assertTrue(torch.tensor([1]).is_nonzero()) self.assertFalse(torch.tensor([[0]]).is_nonzero()) self.assertTrue(torch.tensor([[1]]).is_nonzero()) self.assertTrue(torch.tensor(0.1).is_nonzero()) self.assertTrue(torch.tensor(-0.1).is_nonzero()) self.assertFalse(torch.tensor(0.0).is_nonzero()) self.assertTrue(torch.tensor(True).is_nonzero()) self.assertFalse(torch.tensor(False).is_nonzero()) self.assertFalse(torch.tensor(0 + 0j).is_nonzero()) self.assertTrue(torch.tensor(0 + 0.1j).is_nonzero()) def test_assert_async(self): with self.assertRaisesRegex(RuntimeError, "Boolean value of Tensor with no values is ambiguous"): torch._assert_async(torch.tensor([])) with self.assertRaisesRegex(RuntimeError, "Boolean value of Tensor with more than one value is ambiguous"): torch._assert_async(torch.tensor([0, 0])) with self.assertRaisesRegex(RuntimeError, "Expected Tensor with single nonzero value, but got zero"): torch._assert_async(torch.tensor(0)) torch._assert_async(torch.tensor(1)) torch._assert_async(torch.tensor(0.1)) torch._assert_async(torch.tensor(-0.1)) with self.assertRaisesRegex(RuntimeError, "Expected Tensor with single nonzero value, but got zero"): torch._assert_async(torch.tensor(0.0)) torch._assert_async(torch.tensor(True)) with self.assertRaisesRegex(RuntimeError, "Expected Tensor with single nonzero value, but got zero"): torch._assert_async(torch.tensor(False)) torch._assert_async(torch.tensor(0 + 0.1j)) with self.assertRaisesRegex(RuntimeError, "Expected Tensor with single nonzero value, but got zero"): torch._assert_async(torch.tensor(0 + 0j)) # NB: we must not be built with CUDA; if we are built with CUDA but no CUDA # is available, we get a different error. @unittest.skipIf(torch.backends.cuda.is_built() or IS_SANDCASTLE, "CUDA is built, can't test CUDA not built error") def test_cuda_not_built(self): msg = "Torch not compiled with CUDA enabled" self.assertRaisesRegex(AssertionError, msg, lambda: torch.cuda.current_device()) self.assertRaisesRegex(AssertionError, msg, lambda: torch.tensor([1], device="cuda")) self.assertRaisesRegex(AssertionError, msg, lambda: torch.tensor([1]).cuda()) self.assertRaisesRegex(TypeError, msg, lambda: torch.cuda.FloatTensor()) self.assertRaisesRegex(TypeError, msg, lambda: torch.set_default_tensor_type(torch.cuda.FloatTensor)) self.assertRaisesRegex(AssertionError, msg, lambda: torch.tensor([1]).to(device="cuda")) def test_has_internal_overlap(self): OVERLAP_NO = 0 OVERLAP_YES = 1 OVERLAP_TOO_HARD = 2 # Check for contiguous tensors a = torch.randn(3, 3) self.assertEqual(torch._debug_has_internal_overlap(a), OVERLAP_NO) # Checks for zero strides b = torch.randn(1, 3) b_expanded = b.expand(4, 3) self.assertEqual(torch._debug_has_internal_overlap(b_expanded), OVERLAP_YES) # Check for zero strided, size 1 axis, in non-contiguous storage (gh-33812) c = torch.randn(10).as_strided([2, 1, 5], [1, 0, 2]) self.assertEqual(torch._debug_has_internal_overlap(c), OVERLAP_NO) c = torch.randn(2, 1, 10)[::2].as_strided((2, 1, 5), (10, 0, 2)) self.assertEqual(torch._debug_has_internal_overlap(c), OVERLAP_TOO_HARD) def test_allow_tensor_metadata_change(self): def do_test(t): with self.assertRaisesRegex( RuntimeError, "set_sizes_contiguous is not allowed on a Tensor created from .data or .detach()"): t.resize_((2, 1)) with self.assertRaisesRegex( RuntimeError, "set_storage is not allowed on a Tensor created from .data or .detach()"): t.set_() with self.assertRaisesRegex( RuntimeError, "set_storage_offset is not allowed on a Tensor created from .data or .detach()"): t.set_(t.storage(), 0, t.size(), list(t.stride())) do_test(torch.tensor([[1, 2]]).data) do_test(torch.tensor([[1, 2]]).detach()) @skipIfNotRegistered("LayerNorm", "Skipping as LayerNorm is not registered") def test_c10_layer_norm(self): # test that we can call c10 ops and they return a reasonable result X = torch.rand(5, 5, dtype=torch.float) weight = torch.rand(*X.size()[1:], dtype=torch.float) bias = torch.rand(*X.size()[1:], dtype=torch.float) epsilon = 1e-4 expected_norm = torch.nn.functional.layer_norm( X, X.size()[1:], weight=weight, bias=bias, eps=epsilon) actual_norm, actual_mean, actual_stdev = \ torch.ops._caffe2.LayerNorm(torch.tensor(X), torch.tensor( weight), torch.tensor(bias), 1, epsilon, True) torch.testing.assert_close(expected_norm, actual_norm) def test_memory_format(self): def test_helper(x, memory_format): y = x.contiguous(memory_format=memory_format) self.assertFalse(y.is_contiguous()) self.assertTrue(y.is_contiguous(memory_format=memory_format)) self.assertEqual(y, x) test_helper(torch.randn(4, 3, 8, 8), torch.channels_last) test_helper(torch.randn(4, 3, 8, 8, 8), torch.channels_last_3d) def test_memory_format_contiguous_returns_same_tensor_if_already_satisfies(self): def test_helper(x, memory_format): alias = x.contiguous(memory_format=memory_format) alias.fill_(7) self.assertEqual(x, alias) test_helper(torch.randn(4, 8, 8, 3).permute(0, 3, 1, 2), torch.channels_last) test_helper(torch.randn(4, 8, 8, 8, 3).permute(0, 4, 1, 2, 3), torch.channels_last_3d) def test_memory_format_empty(self): def test_helper(dim1, dim2, memory_format): with self.assertRaises(RuntimeError): x = torch.empty(dim1, memory_format=memory_format) x = torch.empty(dim2, memory_format=memory_format) self.assertTrue(x.is_contiguous(memory_format=memory_format)) test_helper((3, 3), (3, 3, 3, 3), torch.channels_last) test_helper((3, 3, 3), (3, 3, 3, 3, 3), torch.channels_last_3d) def test_subclass_tensors(self): # raise an error when trying to subclass FloatTensor with self.assertRaisesRegex(TypeError, "type 'torch.FloatTensor' is not an acceptable base type"): class Foo1(torch.FloatTensor): pass # but allow subclassing Tensor: class Foo2(torch.Tensor): def foo(self): return 5 f = Foo2() self.assertEqual(f.foo(), 5) def test_ndim(self): a = torch.randn(1, 2, 3) self.assertEqual(3, a.ndim) b = torch.randn(()) self.assertEqual(0, b.ndim) c = torch.randn(1, 0) self.assertEqual(2, c.ndim) def test_fill_diagonal(self): a1 = torch.randn(7, 3) a2 = a1.clone() v = 1 for i in range(3): a2[i][i] = v a1.fill_diagonal_(v) self.assertEqual(a1, a2) b1 = torch.randn(7, 3) b2 = b1.clone() for i in range(3): b2[i][i] = v b2[i + 4][i] = v b1.fill_diagonal_(v, wrap=True) self.assertEqual(b1, b2) c1 = torch.rand(3, 3, 3) c2 = c1.clone() for i in range(3): c2[i][i][i] = v c1.fill_diagonal_(v) self.assertEqual(c1, c2) # non-contiguous tensor d1 = torch.rand(3, 3, 3)[:, 1, ...] d2 = d1.clone() for i in range(3): d2[i][i] = v d1.fill_diagonal_(v) self.assertEqual(d1, d2) e1 = torch.rand(7, 3, 3)[:, 1, ...] e2 = e1.clone() for i in range(3): e2[i][i] = v e2[i + 4][i] = v e1.fill_diagonal_(v, wrap=True) self.assertEqual(e1, e2) def test_setting_real_imag_to_a_number(self): x = torch.randn(4, dtype=torch.cfloat) x.real = 0 x.imag = 0 zeros = torch.zeros(4) self.assertEqual(x.real, zeros) self.assertEqual(x.imag, zeros) def test_batch_norm_cpu_inference(self): # input nchw in (2,1,1,1), (2,2,2,2) inputs = [ torch.tensor([[[[-0.5000]]], [[[0.5000]]]]), torch.tensor([ [ [[-0.5000, 0.5000], [-1.0000, 1.0000]], [[-0.2500, -0.5000], [0.2500, 0.5000]] ], [ [[0.1000, 1.0000], [1.0000, 0.1000]], [[1.0000, 0.5000], [1.5000, -1.5000]] ]])] # output nchw in (2,1,1,1), (2,2,2,2) outputs = [ torch.tensor([ [[[-0.499997496604919433593750000]]], [[[0.499997496604919433593750000]]]]), torch.tensor([ [[[-0.499997496604919433593750000, 0.499997496604919433593750000], [-0.999994993209838867187500000, 0.999994993209838867187500000]], [[-0.249998748302459716796875000, -0.499997496604919433593750000], [0.249998748302459716796875000, 0.499997496604919433593750000]]], [[[0.099999502301216125488281250, 0.999994993209838867187500000], [0.999994993209838867187500000, 0.099999502301216125488281250]], [[0.999994993209838867187500000, 0.499997496604919433593750000], [1.499992489814758300781250000, -1.499992489814758300781250000]]]])] for i in range(len(inputs)): for affine in [False, True]: m = torch.nn.BatchNorm2d(inputs[i].size()[1], 1e-05, 0.1, affine=affine) m.eval() # contiguous case input1 = inputs[i].contiguous() output1 = m(input1) # non-contiguous case input2 = input1.permute(0, 1, 3, 2) output2 = m(input2).permute(0, 1, 3, 2) # channels last case input3 = input1.contiguous(memory_format=torch.channels_last) output3 = m(input3) self.assertEqual(output3, outputs[i]) self.assertEqual(output3, output1) self.assertEqual(output3, output2) # FIXME: move these meta tests to their own test suite/class or # distribute them among the appropriate test suites for their ops def test_empty_meta(self): x = torch.empty(2 ** 20, 2 ** 20, device='meta') y = torch.empty(2 ** 20, device='meta') z = x + y self.assertEqual(z.size(), (2 ** 20, 2 ** 20)) self.assertRaises(RuntimeError, lambda: z[0][0].item()) def test_format_scalar_meta(self): x = torch.empty((), device='meta') self.assertEqual(format(x), repr(x)) def test_upsample_nearest1d_meta(self): # TODO: this test should be triggered by test_nn.py but right # now meta is not enabled (and even if it was, we are probably # missing too many meta functions to get through the test unmolested) # NB: Can't make the exponent too big, or it will overflow # signed 64-bit integer x = torch.empty(2 * 10 ** 8, 3, 2 * 10 ** 8, device='meta') z = torch.nn.functional.interpolate(x, scale_factor=2) self.assertEqual(z.size(), (2 * 10 ** 8, 3, 4 * 10 ** 8)) self.assertRaises(RuntimeError, lambda: z[0][0][0].item()) # TODO: the out tests cannot be triggered by test_nn.py because # we don't actually do out= arguments for nn functions, so there # is no public API by which to get the out version # interpolate doesn't seem to support out= # (not sure why passing None here doesn't work? How strange...) z = torch.empty(0, device='meta') torch._C._nn.upsample_nearest1d(x, (4 * 10 ** 8,), 2, out=z) self.assertEqual(z.size(), (2 * 10 ** 8, 3, 4 * 10 ** 8)) self.assertRaises(RuntimeError, lambda: z[0][0][0].item()) def test_upsample_nearest2d_meta(self): # TODO: the out tests cannot be triggered by test_nn.py because # we don't actually do out= arguments for nn functions, so there # is no public API by which to get the out version # Make sure we don't clobber strides of out tensor. NB: this # test must be done on 2d/3d, because 1d doesn't have any meaningful # layout support x = torch.empty(4, 3, 8, 8, device='meta') out = torch.empty(4, 3, 16, 16, device='meta', memory_format=torch.channels_last) torch._C._nn.upsample_nearest2d(x, (16, 16), out=out) self.assertTrue(out.is_contiguous(memory_format=torch.channels_last)) x = torch.empty(4, 3, 8, 8, device='meta', memory_format=torch.channels_last) out = torch.empty(4, 3, 16, 16, device='meta') torch._C._nn.upsample_nearest2d(x, (16, 16), out=out) self.assertTrue(out.is_contiguous()) # But if resize occurs, do clobber x = torch.empty(4, 3, 8, 8, device='meta', memory_format=torch.channels_last) out = torch.empty(0, device='meta') torch._C._nn.upsample_nearest2d(x, (16, 16), out=out) self.assertTrue(out.is_contiguous(memory_format=torch.channels_last)) # Complain if out dtype mismatch x = torch.empty(4, 3, 8, 8, device='meta', dtype=torch.float) out = torch.empty(4, 3, 16, 16, device='meta', dtype=torch.double) self.assertExpectedRaisesInline( RuntimeError, lambda: torch._C._nn.upsample_nearest2d(x, (16, 16), out=out), """Expected out tensor to have dtype float, but got double instead""" ) # Complain if out device mismatch x = torch.empty(0, 3, 8, 8, device='meta') out = torch.empty(0, 3, 16, 16, device='cpu') self.assertExpectedRaisesInline( RuntimeError, lambda: torch._C._nn.upsample_nearest2d(x, (16, 16), out=out), """Expected out tensor to have device meta, but got cpu instead""" ) def test_add_meta_scalar(self): # From https://github.com/pytorch/pytorch/issues/53815 x = torch.empty(2, device='meta') y = x + 2 self.assertEqual(y.size(), x.size()) def test_normal_shape(self): warned = False for device in get_all_device_types(): tensor1 = torch.rand(1, device=device) tensor4 = torch.rand(4, device=device) tensor120 = torch.rand(120, device=device) tensor2145 = torch.rand(2, 1, 4, 5, device=device) tensor2345 = torch.rand(2, 3, 4, 5, device=device) tensor2345_non_contiguous = torch.rand(2, 4, 3, 5, device=device).permute(0, 2, 1, 3) tensor2345_channels_last = tensor2345.contiguous(memory_format=torch.channels_last) output2345 = torch.zeros(2, 3, 4, 5, device=device) output345 = torch.zeros(3, 4, 5, device=device) # inputs have same size self.assertEqual(torch.normal(tensor2345, tensor2345).size(), (2, 3, 4, 5)) self.assertEqual(torch.normal(tensor2345_non_contiguous, tensor2345).size(), (2, 3, 4, 5)) self.assertEqual(torch.normal(tensor2345, tensor2345_channels_last).size(), (2, 3, 4, 5)) self.assertEqual(torch.normal(tensor2345_non_contiguous, tensor2345_channels_last).size(), (2, 3, 4, 5)) # scalar case self.assertEqual(torch.normal(tensor2345, 2).size(), (2, 3, 4, 5)) self.assertEqual(torch.normal(2, tensor2345).size(), (2, 3, 4, 5)) # inputs are expandable tensors self.assertEqual(torch.normal(tensor2345, tensor1).size(), (2, 3, 4, 5)) self.assertEqual(torch.normal(tensor2145, tensor2345).size(), (2, 3, 4, 5)) # inputs are non-expandable tensors, but they have same number of elements with self.assertRaisesRegex( RuntimeError, r"The size of tensor a \(120\) must match the size of " r"tensor b \(5\) at non-singleton dimension 3"): self.assertEqual(torch.normal(tensor120, tensor2345).size(), (120,)) with self.assertRaisesRegex( RuntimeError, r"The size of tensor a \(5\) must match the size of " r"tensor b \(120\) at non-singleton dimension 3"): self.assertEqual(torch.normal(tensor2345, tensor120).size(), (2, 3, 4, 5)) # inputs are non-expandable tensors and they don't have same number of elements with self.assertRaisesRegex( RuntimeError, r"The size of tensor a \(5\) must match the size of " r"tensor b \(4\) at non-singleton dimension 3"): torch.normal(tensor2345, tensor4) # output and inputs are size compatible self.assertEqual(torch.normal(tensor2345, tensor2345, out=output2345).size(), (2, 3, 4, 5)) # output and inputs are not size compatible with self.assertWarnsRegex( UserWarning, "This behavior is deprecated, and in a future PyTorch " "release outputs will not be resized unless they have " "zero elements"): self.assertEqual(torch.normal(tensor2345, tensor2145, out=output345).size(), (2, 3, 4, 5)) with self.assertRaisesRegex( RuntimeError, r"The size of tensor a \(5\) must match the size of " r"tensor b \(120\) at non-singleton dimension 3"): # inputs are not expandable, output size is not the same as mean torch.normal(tensor2345, tensor120, out=output345) def test_tensoriterator_output_setup(self): # Test whether the output's memory layout is correct def test_memory_layout(x, y, scale, zero_point, out): self.assertEqual(x.dim(), 4) self.assertEqual(x.size(), y.size()) self.assertEqual(y.size(), out.size()) shape = x.size() for n in range(shape[0]): for c in range(shape[1]): for h in range(shape[2]): for w in range(shape[3]): if scale is not None and zero_point is not None: self.assertEqual( out[n][c][h][w], torch.ops.quantized.add(x[n][c][h][w], y[n][c][h][w], scale, zero_point)) else: self.assertEqual(out[n][c][h][w], x[n][c][h][w] + y[n][c][h][w]) xraw = torch.rand(2, 3, 4, 4) yraw = torch.rand(2, 3, 4, 4) qxraw = torch.quantize_per_tensor(xraw, 0.1, 5, torch.quint8) qyraw = torch.quantize_per_tensor(yraw, 0.1, 5, torch.quint8) # contiguous case fast setup test_memory_layout(xraw, yraw, None, None, xraw + yraw) test_memory_layout(qxraw, qyraw, 0.1, 5, torch.ops.quantized.add(qxraw, qyraw, 0.1, 5)) # channels last case fast setup x = xraw.contiguous(memory_format=torch.channels_last) y = yraw.contiguous(memory_format=torch.channels_last) test_memory_layout(x, y, None, None, x + y) qx = qxraw.contiguous(memory_format=torch.channels_last) qy = qyraw.contiguous(memory_format=torch.channels_last) test_memory_layout(qx, qy, 0.1, 5, torch.ops.quantized.add(qx, qy, 0.1, 5)) # non contiguous case fast setup (dense, non-overlapping, same shape and strides) x = xraw.permute(0, 2, 3, 1) y = yraw.permute(0, 2, 3, 1) test_memory_layout(x, y, None, None, x + y) qx = qxraw.permute(0, 2, 3, 1) qy = qyraw.permute(0, 2, 3, 1) test_memory_layout(qx, qy, 0.1, 5, torch.ops.quantized.add(qx, qy, 0.1, 5)) # non contiguous case fast setup (dense, non-overlapping) # input tensors have same shape and strides # output tensor have same shape as input tensors but different stride # output tensor should preserve its strides in this case x = xraw.permute(0, 2, 3, 1) y = yraw.permute(0, 2, 3, 1) out = torch.empty_like(xraw) out = out.permute(0, 3, 2, 1) expected_stride = out.stride() test_memory_layout(x, y, None, None, torch.add(x, y, out=out)) self.assertEqual(expected_stride, out.stride()) # non contiguous case non fast setup x = xraw.permute(0, 2, 3, 1) y = yraw.permute(0, 3, 2, 1) test_memory_layout(x, y, None, None, x + y) qx = qxraw.permute(0, 2, 3, 1) qy = qyraw.permute(0, 3, 2, 1) test_memory_layout(qx, qy, 0.1, 5, torch.ops.quantized.add(qx, qy, 0.1, 5)) # Tests to make sure we still handle .data properly until it is removed def test_dot_data_use(self): # .data allows to change the Tensors types inplace, check that we still # raise a nice error. with self.assertRaisesRegex( RuntimeError, # message includes both Double and Long '(?=.*Double)(?=.*Long)'): # Calls model with a LongTensor input but DoubleTensor weights input = torch.randn(1, 1, 1, 6, dtype=torch.double) weight = torch.zeros(1, 1, 1, 3, dtype=torch.long) model = torch.nn.Conv2d(1, 1, (1, 3), stride=1, padding=0, bias=False) model.weight.data = weight out = model(input) def test_empty_storage_view(self): # we should be able to "modify" slices of a 0-element # array without an error being raised due to # trying to resize its storage t = torch.from_numpy(np.empty((0, 4))) t[:, 1::2] *= 1 def test_has_storage(self): self.assertIsNotNone(torch.tensor([]).storage()) self.assertIsNotNone(torch.empty(0).storage()) self.assertIsNotNone(torch.tensor([]).clone().storage()) self.assertIsNotNone(torch.tensor([0, 0, 0]).nonzero().storage()) self.assertIsNotNone(torch.tensor([]).new().storage()) # FIXME: Extend this test and put in a TensorProperties test class def test_numel(self): b = torch.ByteTensor(3, 100, 100) self.assertEqual(b.nelement(), 3 * 100 * 100) self.assertEqual(b.numel(), 3 * 100 * 100) # Verifies that (deep)copies of dtypes are the same objects def test_copy_dtypes(self): for dtype in all_types_and_complex_and(torch.half, torch.bfloat16, torch.bool): copied_dtype = copy.deepcopy(dtype) self.assertIs(dtype, copied_dtype) def test_dtype_is_signed(self): for dtype in all_types_and_complex_and(torch.half, torch.bfloat16, torch.half): self.assertEqual(dtype.is_signed, torch.is_signed(torch.tensor(0, dtype=dtype))) self.assertRaisesRegex(RuntimeError, 'not supported for quantized', lambda: torch.quint8.is_signed) self.assertRaisesRegex(RuntimeError, 'not supported for quantized', lambda: torch.qint8.is_signed) self.assertRaisesRegex(RuntimeError, 'not supported for quantized', lambda: torch.qint32.is_signed) # FIXME: Put the following random tests into their own test class or test suite def test_RNGState(self): state = torch.get_rng_state() stateCloned = state.clone() before = torch.rand(1000) self.assertEqual(state.ne(stateCloned).long().sum(), 0, atol=0, rtol=0) torch.set_rng_state(state) after = torch.rand(1000) self.assertEqual(before, after, atol=0, rtol=0) def test_RNGStateAliasing(self): # Fork the random number stream at this point gen = torch.Generator() gen.set_state(torch.get_rng_state()) self.assertEqual(gen.get_state(), torch.get_rng_state()) target_value = torch.rand(1000) # Dramatically alter the internal state of the main generator _ = torch.rand(100000) forked_value = torch.rand(1000, generator=gen) self.assertEqual(target_value, forked_value, atol=0, rtol=0, msg="RNG has not forked correctly.") def test_RNG_after_pickle(self): torch.random.manual_seed(100) before = torch.rand(10) torch.random.manual_seed(100) buf = io.BytesIO() tensor = torch.tensor([1, 2, 3]) ForkingPickler(buf, pickle.HIGHEST_PROTOCOL).dump(tensor) after = torch.rand(10) self.assertEqual(before, after, atol=0, rtol=0) def test_boxMullerState(self): torch.manual_seed(123) odd_number = 101 seeded = torch.randn(odd_number) state = torch.get_rng_state() midstream = torch.randn(odd_number) torch.set_rng_state(state) repeat_midstream = torch.randn(odd_number) torch.manual_seed(123) reseeded = torch.randn(odd_number) self.assertEqual(midstream, repeat_midstream, atol=0, rtol=0, msg='get_rng_state/set_rng_state not generating same sequence of normally distributed numbers') self.assertEqual(seeded, reseeded, atol=0, rtol=0, msg='repeated calls to manual_seed not generating same sequence of normally distributed numbers') def test_manual_seed(self): rng_state = torch.get_rng_state() torch.manual_seed(2) x = torch.randn(100) self.assertEqual(torch.initial_seed(), 2) torch.manual_seed(2) y = torch.randn(100) self.assertEqual(x, y) max_int64 = 0x7fff_ffff_ffff_ffff min_int64 = -max_int64 - 1 max_uint64 = 0xffff_ffff_ffff_ffff # Check all boundary cases of valid seed value inputs test_cases = [ # (seed, expected_initial_seed) # Positive seeds should be unchanged (max_int64, max_int64), (max_int64 + 1, max_int64 + 1), (max_uint64, max_uint64), (0, 0), # Negative seeds wrap around starting from the largest seed value (-1, max_uint64), (min_int64, max_int64 + 1) ] for seed, expected_initial_seed in test_cases: torch.manual_seed(seed) actual_initial_seed = torch.initial_seed() msg = "expected initial_seed() = %x after calling manual_seed(%x), but got %x instead" % ( expected_initial_seed, seed, actual_initial_seed) self.assertEqual(expected_initial_seed, actual_initial_seed, msg=msg) for invalid_seed in [min_int64 - 1, max_uint64 + 1]: with self.assertRaisesRegex(RuntimeError, r'Overflow when unpacking long'): torch.manual_seed(invalid_seed) torch.set_rng_state(rng_state) # FIXME: Describe this test and port to the generic device framework in a more # appropriate test suite for the copy operation def test_copy_transpose(self): x = torch.arange(100 * 100, dtype=torch.float).reshape(100, 100).t() y = torch.empty(100, 100, dtype=torch.float) y.copy_(x) self.assertEqual(y[:, 0], range(100)) self.assertEqual(y[:, 40], range(4000, 4100)) y = torch.empty(100, 100, dtype=torch.double) y.copy_(x) self.assertEqual(y[:, 0], range(100)) self.assertEqual(y[:, 40], range(4000, 4100)) # Validates regression reported in https://github.com/pytorch/pytorch/issues/45269 x = torch.arange(100 * 100).reshape(100, 100).to(dtype=torch.cfloat).t() y = torch.empty(100, 100, dtype=torch.cfloat) y.copy_(x) self.assertEqual(y[:, 0], range(100)) self.assertEqual(y[:, 40], range(4000, 4100)) x = torch.arange(100 * 100).reshape(100, 100).to(dtype=torch.complex32).t() y = torch.empty(100, 100, dtype=torch.complex32) y.copy_(x) self.assertEqual(y[:, 0], range(100)) self.assertEqual(y[:, 40], range(4000, 4100)) # FIXME: Port to a more appropriate test suite def test_copy_broadcast(self): torch.zeros(5, 6).copy_(torch.zeros(6)) self.assertRaises(RuntimeError, lambda: torch.zeros(5, 6).copy_(torch.zeros(30))) # FIXME: Port to a more appropriate test suite def test_copy_many_to_one(self): # Testing in-place copy where it attempt to write from many memory # storage to a single storage would cause RuntimeError to be thrown self.assertRaises(RuntimeError, lambda: torch.zeros(1, 6).expand(5, 6).copy_(torch.zeros(5, 6))) # FIXME: Port to a more appropriate test suite def _test_to_with_layout(self, layout): def test_copy_behavior(t, non_blocking=False): self.assertIs(t, t.to(t, non_blocking=non_blocking)) self.assertIs(t, t.to(t.dtype, non_blocking=non_blocking)) self.assertIs(t, t.to(torch.empty_like(t), non_blocking=non_blocking)) self.assertIsNot(t, t.to(t, non_blocking=non_blocking, copy=True)) self.assertIsNot(t, t.to(t.dtype, non_blocking=non_blocking, copy=True)) self.assertIsNot(t, t.to(torch.empty_like(t), non_blocking=non_blocking, copy=True)) devices = [t.device] if t.device.type == 'cuda': if t.device.index == -1: devices.append('cuda:{}'.format(torch.cuda.current_device())) elif t.device.index == torch.cuda.current_device(): devices.append('cuda') for device in devices: self.assertIs(t, t.to(device, non_blocking=non_blocking)) self.assertIs(t, t.to(device, t.dtype, non_blocking=non_blocking)) self.assertIsNot(t, t.to(device, non_blocking=non_blocking, copy=True)) self.assertIsNot(t, t.to(device, t.dtype, non_blocking=non_blocking, copy=True)) a = torch.tensor(5) if layout == torch.sparse_csr: a = torch.tensor([[0, 1, 2], [2, 0, 3]]).to_sparse_csr() test_copy_behavior(a) self.assertEqual(a.device, a.to('cpu').device) self.assertEqual(a.device, a.to('cpu', dtype=torch.float32).device) self.assertIs(torch.float32, a.to('cpu', dtype=torch.float32).dtype) self.assertEqual(a.device, a.to(torch.float32).device) self.assertIs(torch.float32, a.to(dtype=torch.float32).dtype) def test_data_ptr(getter): self.assertEqual(getter(a), getter(a.to('cpu'))) self.assertEqual(getter(a), getter(a.to(dtype=a.dtype, device=a.device, copy=False))) self.assertEqual(getter(a), getter(a.to('cpu', copy=False))) self.assertNotEqual(getter(a), getter(a.to('cpu', copy=True))) if layout == torch.sparse_csr: # TODO: compressed sparse tensors currently don't support data_ptr. # Exercising failure will allow us to widen coverage of this test once it does. with self.assertRaisesRegex(RuntimeError, "Cannot access data pointer of Tensor that doesn't have storage"): a.data_ptr() # While compressed sparse tensors don't have a concept of data_ptr # the underlying tensors do. The implementation of to appropriately forwards # the call to the components, which is what we're test here. test_data_ptr(lambda a: a.values().data_ptr()) test_data_ptr(lambda a: a.crow_indices().data_ptr()) test_data_ptr(lambda a: a.col_indices().data_ptr()) else: test_data_ptr(lambda a: a.data_ptr()) if torch.cuda.is_available(): for non_blocking in [True, False]: for cuda in ['cuda', 'cuda:0' if torch.cuda.device_count() == 1 else 'cuda:1']: b = torch.tensor(5., device=cuda) test_copy_behavior(b, non_blocking) self.assertEqual(b.device, b.to(cuda, non_blocking=non_blocking).device) self.assertEqual(a.device, b.to('cpu', non_blocking=non_blocking).device) self.assertEqual(b.device, a.to(cuda, non_blocking=non_blocking).device) self.assertIs(torch.int32, b.to('cpu', dtype=torch.int32, non_blocking=non_blocking).dtype) self.assertEqual(a.device, b.to('cpu', dtype=torch.int32, non_blocking=non_blocking).device) self.assertIs(torch.int32, b.to(dtype=torch.int32).dtype) self.assertEqual(b.device, b.to(dtype=torch.int32).device) def test_to(self): self._test_to_with_layout(torch.strided) is_cuda10_2_or_higher = ( (torch.version.cuda is not None) and ([int(x) for x in torch.version.cuda.split(".")] >= [10, 2])) if is_cuda10_2_or_higher: # in cuda10_1 sparse_csr is beta self._test_to_with_layout(torch.sparse_csr) # FIXME: describe this test def test_as_subclass(self): class SubTensor(torch.Tensor): member_var = object() t0 = torch.tensor(0) t1 = torch.tensor([1, 2]) t2 = torch.tensor([[3, 4], [5, 6]]) s0 = t0.as_subclass(SubTensor) s1 = t1.as_subclass(SubTensor) s2 = t2.as_subclass(SubTensor) # Check that the correct type is returned. self.assertTrue(type(s0) is SubTensor) self.assertTrue(type(s1) is SubTensor) self.assertTrue(type(s2) is SubTensor) # Check that the data is equal. self.assertEqual(t0, s0) self.assertEqual(t1, s1) self.assertEqual(t2, s2) t0[()] = 1 t1[1] = 3 t2[1, 1] = 7 # Check that the data is equal even after modification. self.assertEqual(t0, s0) self.assertEqual(t1, s1) self.assertEqual(t2, s2) # Check that member variables are passed through. self.assertTrue(s0.member_var is SubTensor.member_var) self.assertTrue(s1.member_var is SubTensor.member_var) self.assertTrue(s2.member_var is SubTensor.member_var) # Test that autograd is propagated. t = torch.tensor(5, dtype=torch.float32, requires_grad=True) # Run a calculation on the tensor. exp_t = torch.exp(t) # Cast exp_t to a subclass. exp_s = exp_t.as_subclass(SubTensor) # Make sure that t.grad was initially None self.assertTrue(t.grad is None) # Run the autograd calculation. exp_s.backward() # Make sure autograd was propagated to the original tensor # declared with requires_grad. self.assertTrue(t.grad is not None) # Make sure invalid subclasses raise nice errors class BadSubTensor(): member_var = object() err_msg = "Creating a Tensor subclass from a class that does not inherit from Tensor" with self.assertRaisesRegex(RuntimeError, err_msg): s0 = t0.as_subclass(BadSubTensor) # FIXME: Port to a test suite that better fits slicing def test_slice(self): empty = torch.empty(0, 4) x = torch.arange(0., 16).view(4, 4) self.assertEqual(x[:], x) self.assertEqual(x[:4], x) # start and stop are clamped to the size of dim self.assertEqual(x[:5], x) # if start >= stop then the result is empty self.assertEqual(x[2:1], empty) self.assertEqual(x[2:2], empty) # out of bounds is also empty self.assertEqual(x[10:12], empty) # additional correctness checks self.assertEqual(x[:1].tolist(), [[0, 1, 2, 3]]) self.assertEqual(x[:-3].tolist(), [[0, 1, 2, 3]]) self.assertEqual(x[:, -2:3].tolist(), [[2], [6], [10], [14]]) self.assertEqual(x[0:-1:2].tolist(), [[0, 1, 2, 3], [8, 9, 10, 11]]) def test_type(self): x = torch.randn(3, 3).double() self.assertEqual(x.type('torch.FloatTensor').dtype, torch.float32) self.assertEqual(x.type(torch.FloatTensor).dtype, torch.float32) self.assertEqual(x.int().type(torch.Tensor).dtype, torch.get_default_dtype()) self.assertEqual(x.type(torch.int32).dtype, torch.int32) # FIXME: port to a quantization test suite def test_qengine(self): qengines = torch.backends.quantized.supported_engines original_qe = torch.backends.quantized.engine for qe in qengines: torch.backends.quantized.engine = qe assert torch.backends.quantized.engine == qe, 'qengine not set successfully' torch.backends.quantized.engine = original_qe # FIXME: port to a distributed test suite -- also... how could this be OOMing on Windows CUDA? @slowTest @unittest.skipIf(NO_MULTIPROCESSING_SPAWN, "Disabled for environments that \ don't support multiprocessing with spawn start method") @unittest.skipIf(IS_WINDOWS, 'FIXME: CUDA OOM error on Windows') def test_multinomial_invalid_probs(self): def _spawn_method(self, method, arg): try: mp.set_start_method('spawn') except RuntimeError: pass with mp.Pool(1) as pool: out: list = pool.map(method, [arg]) self.assertTrue(out[0]) def _test_multinomial_invalid_probs(probs): try: # n_sample = 1 is a special case, test n_sample=2 which is more general torch.multinomial(probs.to('cpu'), 2) return False # Should not be reached except RuntimeError as e: return 'probability tensor contains either `inf`, `nan` or element < 0' in str(e) _spawn_method(_test_multinomial_invalid_probs, torch.tensor([1., -1., 1.])) _spawn_method(_test_multinomial_invalid_probs, torch.tensor([1., inf, 1.])) _spawn_method(_test_multinomial_invalid_probs, torch.tensor([1., -inf, 1.])) _spawn_method(_test_multinomial_invalid_probs, torch.tensor([1., 1., nan])) # FIXME: port to more appropriate test suite def test_to_with_tensor(self): a = torch.tensor(5) self.assertEqual(a.device, a.to(a).device) if torch.cuda.is_available(): for non_blocking in [True, False]: for cuda in ['cuda', 'cuda:0' if torch.cuda.device_count() == 1 else 'cuda:1']: b = torch.tensor(5., device=cuda) self.assertEqual(b.device, b.to(b, non_blocking=non_blocking).device) self.assertEqual(a.device, b.to(a, non_blocking=non_blocking).device) self.assertEqual(b.device, a.to(b, non_blocking=non_blocking).device) def test_device(self): cpu = torch.device('cpu') self.assertEqual('cpu', str(cpu)) self.assertEqual('cpu', cpu.type) self.assertEqual(None, cpu.index) cpu0 = torch.device('cpu:0') self.assertEqual('cpu:0', str(cpu0)) self.assertEqual('cpu', cpu0.type) self.assertEqual(0, cpu0.index) cpu0 = torch.device('cpu', 0) self.assertEqual('cpu:0', str(cpu0)) self.assertEqual('cpu', cpu0.type) self.assertEqual(0, cpu0.index) cuda = torch.device('cuda') self.assertEqual('cuda', str(cuda)) self.assertEqual('cuda', cuda.type) self.assertEqual(None, cuda.index) cuda1 = torch.device('cuda:1') self.assertEqual('cuda:1', str(cuda1)) self.assertEqual('cuda', cuda1.type) self.assertEqual(1, cuda1.index) cuda1 = torch.device('cuda', 1) self.assertEqual('cuda:1', str(cuda1)) self.assertEqual('cuda', cuda1.type) self.assertEqual(1, cuda1.index) cuda90 = torch.device('cuda', 90) self.assertEqual('cuda:90', str(cuda90)) self.assertEqual('cuda', cuda90.type) self.assertEqual(90, cuda90.index) self.assertRaises(RuntimeError, lambda: torch.device('cpu:-1')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:-1')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2 ')) self.assertRaises(RuntimeError, lambda: torch.device('cuda: 2')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2 2')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2.')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2?')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:?2')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2.232')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2 cuda:3')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2+cuda:3')) self.assertRaises(RuntimeError, lambda: torch.device('cuda:2cuda:3')) self.assertRaises(RuntimeError, lambda: torch.device(-1)) self.assertRaises(RuntimeError, lambda: torch.device('other')) self.assertRaises(RuntimeError, lambda: torch.device('other:0')) device_set = {'cpu', 'cpu:0', 'cuda', 'cuda:0', 'cuda:1', 'cuda:10', 'cuda:100'} device_hash_set = set() for device in list(device_set): device_hash_set.add(hash(torch.device(device))) self.assertEqual(len(device_set), len(device_hash_set)) def get_expected_device_repr(device): if device.index is not None: return "device(type='{type}', index={index})".format( type=device.type, index=device.index) return "device(type='{type}')".format(type=device.type) for device in device_set: dev = torch.device(device) self.assertEqual(repr(dev), get_expected_device_repr(dev)) # Tests that the use_deterministic_flag can be set as expected @wrapDeterministicFlagAPITest def test_deterministic_flag(self): for deterministic, warn_only in product([True, False], [True, False]): torch.use_deterministic_algorithms(deterministic, warn_only=warn_only) self.assertEqual(deterministic, torch.are_deterministic_algorithms_enabled()) self.assertEqual(warn_only, torch.is_deterministic_algorithms_warn_only_enabled()) if deterministic: if warn_only: debug_mode = 1 else: debug_mode = 2 else: debug_mode = 0 self.assertEqual(debug_mode, torch.get_deterministic_debug_mode()) for debug_mode in [0, 1, 2]: torch.set_deterministic_debug_mode(debug_mode) self.assertEqual(debug_mode, torch.get_deterministic_debug_mode()) deterministic = debug_mode in [1, 2] warn_only = debug_mode == 1 self.assertEqual(deterministic, torch.are_deterministic_algorithms_enabled()) self.assertEqual(warn_only, torch.is_deterministic_algorithms_warn_only_enabled()) for debug_mode, debug_mode_str in [(0, 'default'), (1, 'warn'), (2, 'error')]: torch.set_deterministic_debug_mode(debug_mode_str) self.assertEqual(debug_mode, torch.get_deterministic_debug_mode()) with self.assertRaisesRegex( TypeError, r"_set_deterministic_algorithms\(\): argument 'mode' \(position 1\) must be bool, not int"): torch.use_deterministic_algorithms(1) with self.assertRaisesRegex( TypeError, r"_set_deterministic_algorithms\(\): argument 'warn_only' must be bool, not int"): torch.use_deterministic_algorithms(False, warn_only=1) def test_type_conversion_via_dtype_name(self): x = torch.tensor([1]) self.assertEqual(x.byte().dtype, torch.uint8) self.assertEqual(x.bool().dtype, torch.bool) self.assertEqual(x.char().dtype, torch.int8) self.assertEqual(x.double().dtype, torch.float64) self.assertEqual(x.float().dtype, torch.float32) self.assertEqual(x.half().dtype, torch.float16) self.assertEqual(x.int().dtype, torch.int32) self.assertEqual(x.bfloat16().dtype, torch.bfloat16) cfloat = x.cfloat() self.assertEqual(cfloat.dtype, torch.complex64) self.assertEqual(cfloat.real, x.float()) self.assertEqual(cfloat.imag, torch.zeros_like(cfloat.imag)) cdouble = x.cdouble() self.assertEqual(cdouble.dtype, torch.complex128) self.assertEqual(cdouble.real, x.double()) self.assertEqual(cdouble.imag, torch.zeros_like(cdouble.imag)) chalf = x.chalf() self.assertEqual(chalf.dtype, torch.complex32) self.assertEqual(chalf.real, x.half()) self.assertEqual(chalf.imag, torch.zeros_like(chalf.imag)) def test_type_alias(self): type_alias_map = {torch.float64: torch.double, torch.float32: torch.float, torch.int32: torch.int, torch.int64: torch.long, torch.int16: torch.short, torch.float16: torch.half, torch.complex32: torch.chalf, torch.complex64: torch.cfloat} for dtype, alias in type_alias_map.items(): self.assertIs(alias, dtype) # FIXME: Describe this test def test_doc_template(self) -> None: from torch._torch_docs import __file__ as doc_file from torch._torch_docs import multi_dim_common, single_dim_common, factory_common_args, factory_like_common_args with open(doc_file, "r", encoding="utf-8") as f: doc_strs = f.read() for doc_str in re.findall(r'add_docstr\((.*?),.*?("""|\'\'\')(.*?)("""|\'\'\')\)', doc_strs, re.MULTILINE | re.DOTALL): for common_args in [multi_dim_common, single_dim_common, factory_common_args, factory_like_common_args]: for k, v in common_args.items(): self.assertNotIn(v, doc_str[2], 'The argument description "{}" in {} can be ' 'replaced by {{{}}}'.format(v, doc_str[0], k)) def test_doc(self): checked_types = (types.MethodType, types.FunctionType, types.BuiltinFunctionType, types.BuiltinMethodType) def _test_namespace(ns, *skips): if isinstance(ns, object): ns_name = ns.__class__.__name__ else: ns_name = ns.__name__ skip_regexes = [] for r in skips: if isinstance(r, string_classes): skip_regexes.append(re.compile('^{}$'.format(re.escape(r)))) else: skip_regexes.append(r) for name in dir(ns): if name.startswith('_'): continue if name in ['real', 'imag']: y = torch.randn(1, dtype=torch.cfloat) var = getattr(y, name) elif name in ["H", "mT", "mH"]: y = torch.randn(1, 1) var = getattr(y, name) else: var = getattr(ns, name) if not isinstance(var, checked_types): continue doc = var.__doc__ has_doc = doc is not None and len(doc.strip()) > 0 full_name = ns_name + '.' + name if any(r.match(name) for r in skip_regexes): self.assertFalse(has_doc, 'New docs have been added for {}, please remove ' 'it from the skipped list in TestTorch.test_doc'.format(full_name)) else: self.assertTrue(has_doc, '{} is missing documentation'.format(full_name)) # FIXME: All of the following should be marked as expected failures # so that it is easier to tell when missing has been added. # FIXME: fix all the skipped ones below! test_namespace(torch.randn(1), 'as_strided_', re.compile('^clamp_(min|max)_?$'), 'is_distributed', 'is_nonzero', 'is_same_size', 'log_softmax', 'map2_', 'new', 'reinforce', 'relu', 'relu_', 'prelu', 'resize', 'resize_as', 'softmax', 'split_with_sizes', 'unsafe_split_with_sizes', '_autocast_to_fp16', '_autocast_to_fp32', ) test_namespace(torch.nn) test_namespace(torch.nn.functional, 'assert_int_or_pair') # TODO: add torch.* tests when we have proper namespacing on ATen functions # test_namespace(torch) # FIXME: deprecate torch.Tensor constructor def test_tensor_ctor_scalar(self): x = torch.Tensor(torch.tensor(1.0)) self.assertEqual(x, torch.tensor(1.0)) def test_deepcopy_gradient(self): from copy import deepcopy a = torch.zeros(10) a.grad = torch.ones(10) self.assertEqual(a.grad, deepcopy(a).grad) s = torch.zeros(10).to_sparse() s.grad = torch.ones(10).to_sparse() self.assertEqual(s.grad, deepcopy(s).grad) # ensure sharing is not broken c = deepcopy([a, a.grad]) self.assertTrue(c[0].grad is c[1]) def test_tensor_base_init(self): # Direct construction not OK self.assertRaises(RuntimeError, lambda: torch._C._TensorBase()) # But construction of subclass is OK class T(torch._C._TensorBase): pass T() def test_tensor_base_new(self): # OK to call super().__new__, see # https://github.com/pytorch/pytorch/issues/57421 class TestTensor(torch._C._TensorBase): @staticmethod def __new__(cls, x, *args, **kwargs): return super().__new__(cls, x, *args, **kwargs) x = torch.ones(5) test_tensor = TestTensor(x) def test_pyobj_preserved(self): x = torch.empty(2) x.foo = 2 # put something on __dict__ y = torch.empty(2) y.grad = x del x # x is dead in Python self.assertEqual(y.grad.foo, 2) z = y.grad # it's live del z # it's dead again self.assertEqual(y.grad.foo, 2) def test_subclass_preserved(self): class MyTensor(torch.Tensor): pass x = MyTensor(torch.empty(2)) y = torch.empty(2) y.grad = x del x # x is dead in Python self.assertEqual(type(y.grad), MyTensor) z = y.grad # it's live del z # it's dead again self.assertEqual(type(y.grad), MyTensor) def test_tensor_slot_dealloc(self): class SlotTensor1(torch._C._TensorBase): __slots__ = ['slot1'] class SlotTensor2(SlotTensor1): __slots__ = ['slot2'] m1, t1 = Tracker.make() m2, t2 = Tracker.make() slot_tensor = SlotTensor2(torch.empty(2)) slot_tensor.slot1 = t1 slot_tensor.slot2 = t2 del t1 del t2 self.assertFalse(m1[0]) self.assertFalse(m2[0]) del slot_tensor self.assertTrue(m1[0]) self.assertTrue(m2[0]) def test_tensor_dict_dealloc(self): m, t = Tracker.make() x = torch.empty(2) x.arf = t del t self.assertFalse(m[0]) del x self.assertTrue(m[0]) def test_tensor_finalizer_dealloc(self): m = [False] class FinalizerTensor(torch._C._TensorBase): def __del__(self): m[0] = True fin_tensor = FinalizerTensor(torch.empty(2)) self.assertFalse(m[0]) del fin_tensor self.assertTrue(m[0]) def test_tensor_weakref_dealloc(self): x = torch.empty(2) m = [False] def cb(r): m[0] = True wref = weakref.ref(x, cb) del x self.assertTrue(m[0]) self.assertEqual(wref(), None) def test_tensor_cycle_via_dict(self): m1, t1 = Tracker.make() x = torch.empty(2) x._tracker = t1 del t1 m2, t2 = Tracker.make() y = torch.empty(2) y._tracker = t2 del t2 x._loop = y y._loop = x # C++ reference should keep the cycle live! # This exercise THPVariable_subtype_traverse # NB: Because z.grad is a reference done entirely in C++, cycles # involving it directly are NOT broken by Python GC; you've # set up a good old C++ reference cycle which we cannot safely # break (because C++ references are allowed to be accessed # multithreaded-ly) (TODO: except maybe if you can prove that # only Python has access to the C++ object, in which case you can # also prove that no multithreaded access occurs) z = torch.empty(2) z.grad = x del x del y gc.collect() self.assertFalse(m1[0]) self.assertFalse(m2[0]) with disable_gc(): del z self.assertFalse(m1[0]) self.assertFalse(m2[0]) gc.collect() self.assertTrue(m1[0]) self.assertTrue(m2[0]) def test_tensor_cycle_via_slots(self): m1 = [False] m2 = [False] class SlotTensor1(torch._C._TensorBase): __slots__ = ['slot1'] def __del__(self): m1[0] = True class SlotTensor2(SlotTensor1): __slots__ = ['slot2'] def __del__(self): m2[0] = True x = SlotTensor1(torch.empty(2)) y = SlotTensor2(torch.empty(2)) x.slot1 = y y.slot2 = x del x with disable_gc(): del y self.assertFalse(m1[0]) self.assertFalse(m2[0]) gc.collect() self.assertTrue(m1[0]) self.assertTrue(m2[0]) # FIXME: move to test_autograd? def test_backward_hooks_traverse(self): m1, t1 = Tracker.make() m2, t2 = Tracker.make() x = torch.empty(2, requires_grad=True) x._tracker = t1 y = torch.empty(2, requires_grad=True) y._tracker = t2 del t1 del t2 # this hits a special setter, it's not just a __dict__ entry x._backward_hooks = y y._backward_hooks = x del x with disable_gc(): del y self.assertFalse(m1[0]) self.assertFalse(m2[0]) gc.collect() self.assertTrue(m1[0]) self.assertTrue(m2[0]) def test_dead_weak_ref(self): x = torch.empty(2) w_x = weakref.ref(x) y = torch.empty(2) y.grad = x del x x = w_x() # Ideally, x would keep the tensor live. But CPython doesn't # provide enough hooks to do this. So it will go dead and x # will transmute into an undefined tensor. Not great, but the # best we can do. del y self.assertRaises(RuntimeError, lambda: x.sigmoid()) def test_resurrected_weak_ref(self): x = torch.empty(2) w_x = weakref.ref(x) y = torch.empty(2) y.grad = x del x x = w_x() # Use this to manually fix weak references after dereferencing them x._fix_weakref() del y x.sigmoid() # FIXME: move to test_linalg @torch.inference_mode() def test_bmm_multithreaded(self): device = 'cpu' num_threads = torch.get_num_threads() torch.set_num_threads(4) batch_sizes = [1, 10] M, N, O = 23, 8, 12 dtype = torch.float32 numpy_dtype = dtype def invert_perm(p): d = {x: i for i, x in enumerate(p)} return (d[0], d[1], d[2]) def generate_inputs(num_batches): # transposed tensors for perm1, perm2 in itertools.product(itertools.permutations((0, 1, 2)), repeat=2): b1 = make_tensor((num_batches, M, N), dtype=dtype, device=device, low=-1, high=1) b2 = make_tensor((num_batches, N, O), dtype=dtype, device=device, low=-1, high=1) b1 = b1.permute(perm1).contiguous().permute(invert_perm(perm1)) b2 = b2.permute(perm2).contiguous().permute(invert_perm(perm2)) yield b1, b2 # broadcasting tensors for b1, b2, b3, b4, b5, b6 in itertools.product((True, False), repeat=6): shape1 = (num_batches if b1 else 1, M if b2 else 1, N if b3 else 1) shape2 = (num_batches if b4 else 1, N if b5 else 1, O if b6 else 1) b1 = make_tensor(shape1, dtype=dtype, device=device, low=-1, high=1).expand(num_batches, M, N) b2 = make_tensor(shape2, dtype=dtype, device=device, low=-1, high=1).expand(num_batches, N, O) yield b1, b2 # zero-sized tensors for z1, z2, z3, z4 in itertools.product((True, False), repeat=4): shape1 = (num_batches if z1 else 0, M if z2 else 0, N if z3 else 0) shape2 = (num_batches if z1 else 0, N if z3 else 0, O if z4 else 0) b1 = torch.randn(shape1, dtype=dtype, device=device) b2 = torch.randn(shape2, dtype=dtype, device=device) yield b1, b2 try: for num_batches in batch_sizes: for (b1, b2), perm3 in itertools.product(generate_inputs(num_batches), itertools.permutations((0, 1, 2))): res1 = torch.bmm(b1, b2) res2 = torch.full((num_batches, M, O), math.nan, dtype=dtype, device=device) \ .permute(perm3).contiguous().permute(invert_perm(perm3)) torch.bmm(b1, b2, out=res2) expect = torch.from_numpy( b1.to(numpy_dtype).cpu().numpy() @ b2.to(numpy_dtype).cpu().numpy()).to(device=device, dtype=dtype) self.assertEqual(expect, res1) self.assertEqual(expect, res2) finally: torch.set_num_threads(num_threads) def test_conj_neg_tolist(self): x = torch.randn(2, dtype=torch.cfloat) y1 = x.conj() y1_expect = x.conj_physical() y2 = y1.imag self.assertEqual(y1, y1_expect.tolist()) self.assertEqual(y2, y1_expect.imag.tolist()) # The following block extends TestTorch with negative dim wrapping tests # FIXME: replace these with OpInfo sample inputs or systemic OpInfo tests # Functions to test negative dimension wrapping METHOD = 1 INPLACE_METHOD = 2 FUNCTIONAL = 4 DIM_ARG = None def make_neg_dim_test(name, tensor_arg, arg_constr, types, extra_dim=0): def neg_dim_test(self): if isinstance(tensor_arg, list): assert METHOD not in types and INPLACE_METHOD not in types x = [torch.randn(arg) for arg in tensor_arg] ndim = len(tensor_arg[-1]) else: x = torch.randn(*tensor_arg) ndim = len(tensor_arg) ndim += extra_dim n_dim_to_test = sum(e is DIM_ARG for e in arg_constr()) for dims_val in combinations(range(ndim), n_dim_to_test): arg = arg_constr() arg_neg = copy.deepcopy(arg) idx = 0 for i, v in enumerate(arg): if v is DIM_ARG: arg[i] = dims_val[idx] arg_neg[i] = dims_val[idx] - ndim idx += 1 if METHOD in types: a = getattr(x, name)(*arg) b = getattr(x, name)(*arg_neg) self.assertEqual(a, b) if INPLACE_METHOD in types: a = x.clone() getattr(a, name + '_')(*arg) b = x.clone() getattr(b, name + '_')(*arg_neg) self.assertEqual(a, b) if FUNCTIONAL in types: a = getattr(torch, name)(x, *arg) b = getattr(torch, name)(x, *arg_neg) self.assertEqual(a, b) return neg_dim_test def idx_tensor(size, max_val): return torch.LongTensor(*size).random_(0, max_val - 1) def add_neg_dim_tests(): neg_dim_tests = [ ('narrow', (10, 20, 30), lambda: [DIM_ARG, 0, 5], [METHOD]), ('transpose', (10, 20, 30), lambda: [DIM_ARG, DIM_ARG], [METHOD, INPLACE_METHOD, FUNCTIONAL]), ('size', (10, 20, 30), lambda: [DIM_ARG], [METHOD]), ('cat', [(2, 3, 4), (2, 3, 4)], lambda: [DIM_ARG], [FUNCTIONAL]), ('chunk', (10, 20, 30), lambda: [5, DIM_ARG], [METHOD, FUNCTIONAL]), ('gather', (10, 20), lambda: [DIM_ARG, idx_tensor((10, 20), 10)], [METHOD, FUNCTIONAL]), ('index_select', (10, 10), lambda: [DIM_ARG, idx_tensor((10,), 10)], [METHOD, FUNCTIONAL]), ('split', (10, 20), lambda: [5, DIM_ARG], [METHOD, FUNCTIONAL]), ('squeeze', (10, 1, 20, 1), lambda: [DIM_ARG], [METHOD, INPLACE_METHOD, FUNCTIONAL]), ('unbind', (2, 3, 4), lambda: [DIM_ARG], [FUNCTIONAL]), ('unsqueeze', (10, 20), lambda: [DIM_ARG], [METHOD, INPLACE_METHOD, FUNCTIONAL], 1), ('logcumsumexp', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('cumprod', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('cumsum', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('cummax', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('cummin', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('mean', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('median', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('nanmedian', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('mode', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('norm', (10, 20), lambda: [2, DIM_ARG], [METHOD, FUNCTIONAL]), ('prod', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('std', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('sum', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('var', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('kthvalue', (10, 20), lambda: [3, DIM_ARG], [METHOD, FUNCTIONAL]), ('max', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('min', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('sort', (10, 20), lambda: [DIM_ARG], [METHOD, FUNCTIONAL]), ('topk', (10, 20), lambda: [5, DIM_ARG], [METHOD, FUNCTIONAL]), ('renorm', (10, 20), lambda: [2, DIM_ARG, 1], [METHOD, INPLACE_METHOD, FUNCTIONAL]), ('index_add', (10, 10), lambda: [DIM_ARG, idx_tensor((10,), 10), torch.randn(10, 10)], [INPLACE_METHOD]), ('index_copy', (10, 10), lambda: [DIM_ARG, idx_tensor((10,), 10), torch.randn(10, 10)], [INPLACE_METHOD]), ('index_fill', (10, 10), lambda: [DIM_ARG, idx_tensor((10,), 10), 12], [INPLACE_METHOD]), ('scatter', (10, 10), lambda: [DIM_ARG, idx_tensor((10, 10), 10), torch.randn(10, 10)], [INPLACE_METHOD]), ('select', (10, 20), lambda: [DIM_ARG, 3], [METHOD]), ('unfold', (10, 20), lambda: [DIM_ARG, 5, 2], [METHOD]), ] for decl in neg_dim_tests: if len(decl) == 4: name, tensor_arg, arg_constr, types = decl extra_dim = 0 elif len(decl) == 5: name, tensor_arg, arg_constr, types, extra_dim = decl test_name = 'test_' + name + '_neg_dim' assert not hasattr(TestTorch, test_name), "Duplicated test name: " + test_name setattr(TestTorch, test_name, make_neg_dim_test(name, tensor_arg, arg_constr, types, extra_dim)) # TODO: these empy classes are temporarily instantiated for XLA compatibility # once XLA updates their test suite it should be removed class TestViewOps(TestCase): pass class TestTensorDeviceOps(TestCase): pass # Generates tests # Note: test generation must be done at file scope, not within main, or # pytest will fail. add_neg_dim_tests() instantiate_device_type_tests(TestViewOps, globals()) instantiate_device_type_tests(TestVitalSignsCuda, globals()) instantiate_device_type_tests(TestTensorDeviceOps, globals()) instantiate_device_type_tests(TestTorchDeviceType, globals()) instantiate_device_type_tests(TestDevicePrecision, globals(), except_for='cpu') if __name__ == '__main__': run_tests()
import argparse import os from pathlib import Path import cv2 from codenames.preprocessing import Split, ExtractCards, Rotate, get_all_images_in def preprocess() -> None: preprocessors = { 'split': Split(), 'extract_cards': ExtractCards(), 'rotate': Rotate() } parser = argparse.ArgumentParser(description='Batch image preprocessing') parser.add_argument('preprocessor') parser.add_argument('--in') parser.add_argument('--out') args = vars(parser.parse_args()) input_path = Path(args['in']) output_path = Path(args['out']) if not input_path.is_dir(): raise ValueError(f'{input_path} is not an existing directory') os.makedirs(output_path, exist_ok=True) processor = preprocessors[args['preprocessor']] files_to_process = get_all_images_in(input_path) for file_to_process in files_to_process: filename, extension = file_to_process.stem, file_to_process.suffix original_image = cv2.imread(str(file_to_process)) processed_images_with_postfixes = processor.process(original_image) for processed_image, postfix in processed_images_with_postfixes: processed_image_path = output_path / f'{filename}{'_' + postfix if postfix else ''}{extension}' cv2.imwrite(str(processed_image_path), processed_image) preprocess()
import argparse import os from pathlib import Path import cv2 from codenames.preprocessing import Split, ExtractCards, Rotate, get_all_images_in def preprocess() -> None: preprocessors = { 'split': Split(), 'extract_cards': ExtractCards(), 'rotate': Rotate() } parser = argparse.ArgumentParser(description='Batch image preprocessing') parser.add_argument('preprocessor') parser.add_argument('--in') parser.add_argument('--out') args = vars(parser.parse_args()) input_path = Path(args['in']) output_path = Path(args['out']) if not input_path.is_dir(): raise ValueError(f'{input_path} is not an existing directory') os.makedirs(output_path, exist_ok=True) processor = preprocessors[args['preprocessor']] files_to_process = get_all_images_in(input_path) for file_to_process in files_to_process: filename, extension = file_to_process.stem, file_to_process.suffix original_image = cv2.imread(str(file_to_process)) processed_images_with_postfixes = processor.process(original_image) for processed_image, postfix in processed_images_with_postfixes: processed_image_path = output_path / f'{filename}{"_" + postfix if postfix else ""}{extension}' cv2.imwrite(str(processed_image_path), processed_image) preprocess()
import os from queue import Queue import time import threading from pyvips import Image, Error import shared.config as config import shared.logger as logger import shared.graphql_utility as gql import shared.aws_utility as aws_utility import shared.uri_utility as uri_utility import shared.google_utility as google_utility from shared.statistic import Statistic gdrive_creds = aws_utility.get_gdrive_creds() def _reprocess_image(queue: Queue) -> None: global stats while not queue.empty(): img_data = queue.get() img_data["filePath"] = f"{os.path.splitext(img_data["filePath"])[0]}.tif" tif_filename = os.path.basename(img_data["filePath"]) local_file = f"TEMP_{os.path.basename(img_data["id"])}" logger.info(f"Processing {img_data["id"]}") if _download_source_file(img_data, local_file): image = _preprocess_image(img_data, local_file) if image: image.tiffsave(tif_filename, tile=True, pyramid=True, compression=config.COMPRESSION_TYPE, tile_width=config.PYTIF_TILE_WIDTH, tile_height=config.PYTIF_TILE_HEIGHT, \ xres=config.DPI_VALUE, yres=config.DPI_VALUE) # noqa _upload_files(img_data, local_file, tif_filename) gql.update_processed_date(img_data['id']) os.remove(tif_filename) os.remove(local_file) logger.info(f'Completed {local_file}') else: Statistic.download_err(img_data) Statistic.attempted() queue.task_done() # print(f"{image.get_fields()}") # image fields, including exif def _preprocess_image(img_data: dict, local_file: str) -> Image: try: image = Image.new_from_file(local_file, access='sequential') max_height = config.DEFAULT_MAX_HEIGHT max_width = config.DEFAULT_MAX_WIDTH if img_data["copyrightStatus"] and \ img_data["copyrightStatus"].lower() == "copyright": max_height = config.COPYRIGHT_MAX_HEIGHT max_width = config.COPYRIGHT_MAX_WIDTH if image.height > max_height or image.width > max_width: if image.height >= image.width: shrink_by = image.height / max_height else: shrink_by = image.width / max_width logger.debug(f"Resizing {img_data["id"]} by {shrink_by}") image = image.shrink(shrink_by, shrink_by) except Error as pye: image = None Statistic.vips_err(img_data) logger.error(f"VIPs error - {pye.message}") return image def _download_source_file(img_data, local_file) -> bool: if img_data["sourceType"] == config.S3: return aws_utility.download_file(img_data["sourceBucketName"], img_data["sourceFilePath"], local_file) elif img_data["sourceType"] in [config.URI, config.CURATE]: return uri_utility.download_file(local_file, img_data['sourceUri']) else: conn = google_utility.establish_connection(gdrive_creds) return google_utility.download_file(conn, img_data["sourceUri"][41:-5], local_file) def _upload_files(img_data, local_file, tif_filename): if local_file.endswith(".pdf"): key = img_data["filePath"].replace(".tif", ".pdf") aws_utility.upload_file(config.IMAGE_BUCKET, key, local_file) aws_utility.upload_file(config.IMAGE_BUCKET, img_data["filePath"], tif_filename) def process_image_changes(data: list): jobs = Queue() for img_data in data: jobs.put(img_data) logger.info(f"{jobs.qsize()} IMAGES TO PROCESS") start_time = time.time() for i in range(config.MAX_THREADS): threading.Thread(target=_reprocess_image, args=(jobs,)).start() jobs.join() end_time = time.time() elapsed_time = end_time - start_time Statistic.summary() logger.info(f"ELAPSED TIME = {elapsed_time} seconds")
import os from queue import Queue import time import threading from pyvips import Image, Error import shared.config as config import shared.logger as logger import shared.graphql_utility as gql import shared.aws_utility as aws_utility import shared.uri_utility as uri_utility import shared.google_utility as google_utility from shared.statistic import Statistic gdrive_creds = aws_utility.get_gdrive_creds() def _reprocess_image(queue: Queue) -> None: global stats while not queue.empty(): img_data = queue.get() img_data["filePath"] = f"{os.path.splitext(img_data['filePath'])[0]}.tif" tif_filename = os.path.basename(img_data["filePath"]) local_file = f"TEMP_{os.path.basename(img_data['id'])}" logger.info(f"Processing {img_data['id']}") if _download_source_file(img_data, local_file): image = _preprocess_image(img_data, local_file) if image: image.tiffsave(tif_filename, tile=True, pyramid=True, compression=config.COMPRESSION_TYPE, tile_width=config.PYTIF_TILE_WIDTH, tile_height=config.PYTIF_TILE_HEIGHT, \ xres=config.DPI_VALUE, yres=config.DPI_VALUE) # noqa _upload_files(img_data, local_file, tif_filename) gql.update_processed_date(img_data['id']) os.remove(tif_filename) os.remove(local_file) logger.info(f'Completed {local_file}') else: Statistic.download_err(img_data) Statistic.attempted() queue.task_done() # print(f"{image.get_fields()}") # image fields, including exif def _preprocess_image(img_data: dict, local_file: str) -> Image: try: image = Image.new_from_file(local_file, access='sequential') max_height = config.DEFAULT_MAX_HEIGHT max_width = config.DEFAULT_MAX_WIDTH if img_data["copyrightStatus"] and \ img_data["copyrightStatus"].lower() == "copyright": max_height = config.COPYRIGHT_MAX_HEIGHT max_width = config.COPYRIGHT_MAX_WIDTH if image.height > max_height or image.width > max_width: if image.height >= image.width: shrink_by = image.height / max_height else: shrink_by = image.width / max_width logger.debug(f"Resizing {img_data['id']} by {shrink_by}") image = image.shrink(shrink_by, shrink_by) except Error as pye: image = None Statistic.vips_err(img_data) logger.error(f"VIPs error - {pye.message}") return image def _download_source_file(img_data, local_file) -> bool: if img_data["sourceType"] == config.S3: return aws_utility.download_file(img_data["sourceBucketName"], img_data["sourceFilePath"], local_file) elif img_data["sourceType"] in [config.URI, config.CURATE]: return uri_utility.download_file(local_file, img_data['sourceUri']) else: conn = google_utility.establish_connection(gdrive_creds) return google_utility.download_file(conn, img_data["sourceUri"][41:-5], local_file) def _upload_files(img_data, local_file, tif_filename): if local_file.endswith(".pdf"): key = img_data["filePath"].replace(".tif", ".pdf") aws_utility.upload_file(config.IMAGE_BUCKET, key, local_file) aws_utility.upload_file(config.IMAGE_BUCKET, img_data["filePath"], tif_filename) def process_image_changes(data: list): jobs = Queue() for img_data in data: jobs.put(img_data) logger.info(f"{jobs.qsize()} IMAGES TO PROCESS") start_time = time.time() for i in range(config.MAX_THREADS): threading.Thread(target=_reprocess_image, args=(jobs,)).start() jobs.join() end_time = time.time() elapsed_time = end_time - start_time Statistic.summary() logger.info(f"ELAPSED TIME = {elapsed_time} seconds")
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import, unicode_literals if __name__ == '__main__': import argparse, textwrap import script_utils # Append mripy to Python path from mripy import dicom_report, utils parser = argparse.ArgumentParser(description='', formatter_class=argparse.RawDescriptionHelpFormatter, epilog=textwrap.dedent('''\ examples: 1) report_parameters.py ../raw_fmri/func01 2) report_parameters.py -p mp2rage ../raw_fmri/'T1*' ''')) parser.add_argument('dicom_folder', help='a folder that contains all dicom files for a single sequence') parser.add_argument('-p', '--preset', help=f"preset for what parameters to report: {", ".join(dicom_report.preset4sequence.values())}") args = parser.parse_args() print('>> Reading dicom headers...') report, preset, info = dicom_report.report_parameters(args.dicom_folder, preset=args.preset, return_preset=True, return_info=True) print(f'>> Using "{preset}" preset') print(report) print(f">> Coil: {info["TransmittingCoil"]}, ReferenceAmplitude: {info["ReferenceAmplitude"]} V, TotalScanTime: {utils.format_duration(info["TotalScanTime"])}")
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import, unicode_literals if __name__ == '__main__': import argparse, textwrap import script_utils # Append mripy to Python path from mripy import dicom_report, utils parser = argparse.ArgumentParser(description='', formatter_class=argparse.RawDescriptionHelpFormatter, epilog=textwrap.dedent('''\ examples: 1) report_parameters.py ../raw_fmri/func01 2) report_parameters.py -p mp2rage ../raw_fmri/'T1*' ''')) parser.add_argument('dicom_folder', help='a folder that contains all dicom files for a single sequence') parser.add_argument('-p', '--preset', help=f"preset for what parameters to report: {', '.join(dicom_report.preset4sequence.values())}") args = parser.parse_args() print('>> Reading dicom headers...') report, preset, info = dicom_report.report_parameters(args.dicom_folder, preset=args.preset, return_preset=True, return_info=True) print(f'>> Using "{preset}" preset') print(report) print(f">> Coil: {info['TransmittingCoil']}, ReferenceAmplitude: {info['ReferenceAmplitude']} V, TotalScanTime: {utils.format_duration(info['TotalScanTime'])}")
"""Support for AirVisual air quality sensors.""" from homeassistant.components.sensor import SensorEntity from homeassistant.const import ( ATTR_LATITUDE, ATTR_LONGITUDE, ATTR_STATE, CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, CONCENTRATION_PARTS_PER_BILLION, CONCENTRATION_PARTS_PER_MILLION, CONF_LATITUDE, CONF_LONGITUDE, CONF_SHOW_ON_MAP, CONF_STATE, DEVICE_CLASS_BATTERY, DEVICE_CLASS_CO2, DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_TEMPERATURE, PERCENTAGE, TEMP_CELSIUS, ) from homeassistant.core import callback from . import AirVisualEntity from .const import ( CONF_CITY, CONF_COUNTRY, CONF_INTEGRATION_TYPE, DATA_COORDINATOR, DOMAIN, INTEGRATION_TYPE_GEOGRAPHY_COORDS, INTEGRATION_TYPE_GEOGRAPHY_NAME, ) ATTR_CITY = "city" ATTR_COUNTRY = "country" ATTR_POLLUTANT_SYMBOL = "pollutant_symbol" ATTR_POLLUTANT_UNIT = "pollutant_unit" ATTR_REGION = "region" DEVICE_CLASS_POLLUTANT_LABEL = "airvisual__pollutant_label" DEVICE_CLASS_POLLUTANT_LEVEL = "airvisual__pollutant_level" SENSOR_KIND_AQI = "air_quality_index" SENSOR_KIND_BATTERY_LEVEL = "battery_level" SENSOR_KIND_CO2 = "carbon_dioxide" SENSOR_KIND_HUMIDITY = "humidity" SENSOR_KIND_LEVEL = "air_pollution_level" SENSOR_KIND_PM_0_1 = "particulate_matter_0_1" SENSOR_KIND_PM_1_0 = "particulate_matter_1_0" SENSOR_KIND_PM_2_5 = "particulate_matter_2_5" SENSOR_KIND_POLLUTANT = "main_pollutant" SENSOR_KIND_SENSOR_LIFE = "sensor_life" SENSOR_KIND_TEMPERATURE = "temperature" SENSOR_KIND_VOC = "voc" GEOGRAPHY_SENSORS = [ (SENSOR_KIND_LEVEL, "Air Pollution Level", "mdi:gauge", None), (SENSOR_KIND_AQI, "Air Quality Index", "mdi:chart-line", "AQI"), (SENSOR_KIND_POLLUTANT, "Main Pollutant", "mdi:chemical-weapon", None), ] GEOGRAPHY_SENSOR_LOCALES = {"cn": "Chinese", "us": "U.S."} NODE_PRO_SENSORS = [ (SENSOR_KIND_AQI, "Air Quality Index", None, "mdi:chart-line", "AQI"), (SENSOR_KIND_BATTERY_LEVEL, "Battery", DEVICE_CLASS_BATTERY, None, PERCENTAGE), ( SENSOR_KIND_CO2, "C02", DEVICE_CLASS_CO2, None, CONCENTRATION_PARTS_PER_MILLION, ), (SENSOR_KIND_HUMIDITY, "Humidity", DEVICE_CLASS_HUMIDITY, None, PERCENTAGE), ( SENSOR_KIND_PM_0_1, "PM 0.1", None, "mdi:sprinkler", CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, ), ( SENSOR_KIND_PM_1_0, "PM 1.0", None, "mdi:sprinkler", CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, ), ( SENSOR_KIND_PM_2_5, "PM 2.5", None, "mdi:sprinkler", CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, ), ( SENSOR_KIND_TEMPERATURE, "Temperature", DEVICE_CLASS_TEMPERATURE, None, TEMP_CELSIUS, ), ( SENSOR_KIND_VOC, "VOC", None, "mdi:sprinkler", CONCENTRATION_PARTS_PER_MILLION, ), ] STATE_POLLUTANT_LABEL_CO = "co" STATE_POLLUTANT_LABEL_N2 = "n2" STATE_POLLUTANT_LABEL_O3 = "o3" STATE_POLLUTANT_LABEL_P1 = "p1" STATE_POLLUTANT_LABEL_P2 = "p2" STATE_POLLUTANT_LABEL_S2 = "s2" STATE_POLLUTANT_LEVEL_GOOD = "good" STATE_POLLUTANT_LEVEL_MODERATE = "moderate" STATE_POLLUTANT_LEVEL_UNHEALTHY_SENSITIVE = "unhealthy_sensitive" STATE_POLLUTANT_LEVEL_UNHEALTHY = "unhealthy" STATE_POLLUTANT_LEVEL_VERY_UNHEALTHY = "very_unhealthy" STATE_POLLUTANT_LEVEL_HAZARDOUS = "hazardous" POLLUTANT_LEVELS = { (0, 50): (STATE_POLLUTANT_LEVEL_GOOD, "mdi:emoticon-excited"), (51, 100): (STATE_POLLUTANT_LEVEL_MODERATE, "mdi:emoticon-happy"), (101, 150): (STATE_POLLUTANT_LEVEL_UNHEALTHY_SENSITIVE, "mdi:emoticon-neutral"), (151, 200): (STATE_POLLUTANT_LEVEL_UNHEALTHY, "mdi:emoticon-sad"), (201, 300): (STATE_POLLUTANT_LEVEL_VERY_UNHEALTHY, "mdi:emoticon-dead"), (301, 1000): (STATE_POLLUTANT_LEVEL_HAZARDOUS, "mdi:biohazard"), } POLLUTANT_UNITS = { "co": CONCENTRATION_PARTS_PER_MILLION, "n2": CONCENTRATION_PARTS_PER_BILLION, "o3": CONCENTRATION_PARTS_PER_BILLION, "p1": CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, "p2": CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, "s2": CONCENTRATION_PARTS_PER_BILLION, } async def async_setup_entry(hass, config_entry, async_add_entities): """Set up AirVisual sensors based on a config entry.""" coordinator = hass.data[DOMAIN][DATA_COORDINATOR][config_entry.entry_id] if config_entry.data[CONF_INTEGRATION_TYPE] in [ INTEGRATION_TYPE_GEOGRAPHY_COORDS, INTEGRATION_TYPE_GEOGRAPHY_NAME, ]: sensors = [ AirVisualGeographySensor( coordinator, config_entry, kind, name, icon, unit, locale, ) for locale in GEOGRAPHY_SENSOR_LOCALES for kind, name, icon, unit in GEOGRAPHY_SENSORS ] else: sensors = [ AirVisualNodeProSensor(coordinator, kind, name, device_class, icon, unit) for kind, name, device_class, icon, unit in NODE_PRO_SENSORS ] async_add_entities(sensors, True) class AirVisualGeographySensor(AirVisualEntity, SensorEntity): """Define an AirVisual sensor related to geography data via the Cloud API.""" def __init__(self, coordinator, config_entry, kind, name, icon, unit, locale): """Initialize.""" super().__init__(coordinator) if kind == SENSOR_KIND_LEVEL: self._attr_device_class = DEVICE_CLASS_POLLUTANT_LEVEL elif kind == SENSOR_KIND_POLLUTANT: self._attr_device_class = DEVICE_CLASS_POLLUTANT_LABEL self._attr_extra_state_attributes.update( { ATTR_CITY: config_entry.data.get(CONF_CITY), ATTR_STATE: config_entry.data.get(CONF_STATE), ATTR_COUNTRY: config_entry.data.get(CONF_COUNTRY), } ) self._attr_icon = icon self._attr_name = f"{GEOGRAPHY_SENSOR_LOCALES[locale]} {name}" self._attr_unique_id = f"{config_entry.unique_id}_{locale}_{kind}" self._attr_unit_of_measurement = unit self._config_entry = config_entry self._kind = kind self._locale = locale @property def available(self) -> bool: """Return if entity is available.""" return super().available and self.coordinator.data["current"]["pollution"] @callback def update_from_latest_data(self): """Update the entity from the latest data.""" try: data = self.coordinator.data["current"]["pollution"] except KeyError: return if self._kind == SENSOR_KIND_LEVEL: aqi = data[f"aqi{self._locale}"] [(self._attr_state, self._attr_icon)] = [ (name, icon) for (floor, ceiling), (name, icon) in POLLUTANT_LEVELS.items() if floor <= aqi <= ceiling ] elif self._kind == SENSOR_KIND_AQI: self._attr_state = data[f"aqi{self._locale}"] elif self._kind == SENSOR_KIND_POLLUTANT: symbol = data[f"main{self._locale}"] self._attr_state = symbol self._attr_extra_state_attributes.update( { ATTR_POLLUTANT_SYMBOL: symbol, ATTR_POLLUTANT_UNIT: POLLUTANT_UNITS[symbol], } ) # Displaying the geography on the map relies upon putting the latitude/longitude # in the entity attributes with "latitude" and "longitude" as the keys. # Conversely, we can hide the location on the map by using other keys, like # "lati" and "long". # # We use any coordinates in the config entry and, in the case of a geography by # name, we fall back to the latitude longitude provided in the coordinator data: latitude = self._config_entry.data.get( CONF_LATITUDE, self.coordinator.data["location"]["coordinates"][1], ) longitude = self._config_entry.data.get( CONF_LONGITUDE, self.coordinator.data["location"]["coordinates"][0], ) if self._config_entry.options[CONF_SHOW_ON_MAP]: self._attr_extra_state_attributes[ATTR_LATITUDE] = latitude self._attr_extra_state_attributes[ATTR_LONGITUDE] = longitude self._attr_extra_state_attributes.pop("lati", None) self._attr_extra_state_attributes.pop("long", None) else: self._attr_extra_state_attributes["lati"] = latitude self._attr_extra_state_attributes["long"] = longitude self._attr_extra_state_attributes.pop(ATTR_LATITUDE, None) self._attr_extra_state_attributes.pop(ATTR_LONGITUDE, None) class AirVisualNodeProSensor(AirVisualEntity, SensorEntity): """Define an AirVisual sensor related to a Node/Pro unit.""" def __init__(self, coordinator, kind, name, device_class, icon, unit): """Initialize.""" super().__init__(coordinator) self._attr_device_class = device_class self._attr_icon = icon self._attr_unit_of_measurement = unit self._kind = kind self._name = name @property def device_info(self): """Return device registry information for this entity.""" return { "identifiers": {(DOMAIN, self.coordinator.data["serial_number"])}, "name": self.coordinator.data["settings"]["node_name"], "manufacturer": "AirVisual", "model": f'{self.coordinator.data['status']['model']}', "sw_version": ( f'Version {self.coordinator.data['status']['system_version']}' f'{self.coordinator.data['status']['app_version']}' ), } @property def name(self): """Return the name.""" node_name = self.coordinator.data["settings"]["node_name"] return f"{node_name} Node/Pro: {self._name}" @property def unique_id(self): """Return a unique, Home Assistant friendly identifier for this entity.""" return f"{self.coordinator.data["serial_number"]}_{self._kind}" @callback def update_from_latest_data(self): """Update the entity from the latest data.""" if self._kind == SENSOR_KIND_AQI: if self.coordinator.data["settings"]["is_aqi_usa"]: self._attr_state = self.coordinator.data["measurements"]["aqi_us"] else: self._attr_state = self.coordinator.data["measurements"]["aqi_cn"] elif self._kind == SENSOR_KIND_BATTERY_LEVEL: self._attr_state = self.coordinator.data["status"]["battery"] elif self._kind == SENSOR_KIND_CO2: self._attr_state = self.coordinator.data["measurements"].get("co2") elif self._kind == SENSOR_KIND_HUMIDITY: self._attr_state = self.coordinator.data["measurements"].get("humidity") elif self._kind == SENSOR_KIND_PM_0_1: self._attr_state = self.coordinator.data["measurements"].get("pm0_1") elif self._kind == SENSOR_KIND_PM_1_0: self._attr_state = self.coordinator.data["measurements"].get("pm1_0") elif self._kind == SENSOR_KIND_PM_2_5: self._attr_state = self.coordinator.data["measurements"].get("pm2_5") elif self._kind == SENSOR_KIND_TEMPERATURE: self._attr_state = self.coordinator.data["measurements"].get( "temperature_C" ) elif self._kind == SENSOR_KIND_VOC: self._attr_state = self.coordinator.data["measurements"].get("voc")
"""Support for AirVisual air quality sensors.""" from homeassistant.components.sensor import SensorEntity from homeassistant.const import ( ATTR_LATITUDE, ATTR_LONGITUDE, ATTR_STATE, CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, CONCENTRATION_PARTS_PER_BILLION, CONCENTRATION_PARTS_PER_MILLION, CONF_LATITUDE, CONF_LONGITUDE, CONF_SHOW_ON_MAP, CONF_STATE, DEVICE_CLASS_BATTERY, DEVICE_CLASS_CO2, DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_TEMPERATURE, PERCENTAGE, TEMP_CELSIUS, ) from homeassistant.core import callback from . import AirVisualEntity from .const import ( CONF_CITY, CONF_COUNTRY, CONF_INTEGRATION_TYPE, DATA_COORDINATOR, DOMAIN, INTEGRATION_TYPE_GEOGRAPHY_COORDS, INTEGRATION_TYPE_GEOGRAPHY_NAME, ) ATTR_CITY = "city" ATTR_COUNTRY = "country" ATTR_POLLUTANT_SYMBOL = "pollutant_symbol" ATTR_POLLUTANT_UNIT = "pollutant_unit" ATTR_REGION = "region" DEVICE_CLASS_POLLUTANT_LABEL = "airvisual__pollutant_label" DEVICE_CLASS_POLLUTANT_LEVEL = "airvisual__pollutant_level" SENSOR_KIND_AQI = "air_quality_index" SENSOR_KIND_BATTERY_LEVEL = "battery_level" SENSOR_KIND_CO2 = "carbon_dioxide" SENSOR_KIND_HUMIDITY = "humidity" SENSOR_KIND_LEVEL = "air_pollution_level" SENSOR_KIND_PM_0_1 = "particulate_matter_0_1" SENSOR_KIND_PM_1_0 = "particulate_matter_1_0" SENSOR_KIND_PM_2_5 = "particulate_matter_2_5" SENSOR_KIND_POLLUTANT = "main_pollutant" SENSOR_KIND_SENSOR_LIFE = "sensor_life" SENSOR_KIND_TEMPERATURE = "temperature" SENSOR_KIND_VOC = "voc" GEOGRAPHY_SENSORS = [ (SENSOR_KIND_LEVEL, "Air Pollution Level", "mdi:gauge", None), (SENSOR_KIND_AQI, "Air Quality Index", "mdi:chart-line", "AQI"), (SENSOR_KIND_POLLUTANT, "Main Pollutant", "mdi:chemical-weapon", None), ] GEOGRAPHY_SENSOR_LOCALES = {"cn": "Chinese", "us": "U.S."} NODE_PRO_SENSORS = [ (SENSOR_KIND_AQI, "Air Quality Index", None, "mdi:chart-line", "AQI"), (SENSOR_KIND_BATTERY_LEVEL, "Battery", DEVICE_CLASS_BATTERY, None, PERCENTAGE), ( SENSOR_KIND_CO2, "C02", DEVICE_CLASS_CO2, None, CONCENTRATION_PARTS_PER_MILLION, ), (SENSOR_KIND_HUMIDITY, "Humidity", DEVICE_CLASS_HUMIDITY, None, PERCENTAGE), ( SENSOR_KIND_PM_0_1, "PM 0.1", None, "mdi:sprinkler", CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, ), ( SENSOR_KIND_PM_1_0, "PM 1.0", None, "mdi:sprinkler", CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, ), ( SENSOR_KIND_PM_2_5, "PM 2.5", None, "mdi:sprinkler", CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, ), ( SENSOR_KIND_TEMPERATURE, "Temperature", DEVICE_CLASS_TEMPERATURE, None, TEMP_CELSIUS, ), ( SENSOR_KIND_VOC, "VOC", None, "mdi:sprinkler", CONCENTRATION_PARTS_PER_MILLION, ), ] STATE_POLLUTANT_LABEL_CO = "co" STATE_POLLUTANT_LABEL_N2 = "n2" STATE_POLLUTANT_LABEL_O3 = "o3" STATE_POLLUTANT_LABEL_P1 = "p1" STATE_POLLUTANT_LABEL_P2 = "p2" STATE_POLLUTANT_LABEL_S2 = "s2" STATE_POLLUTANT_LEVEL_GOOD = "good" STATE_POLLUTANT_LEVEL_MODERATE = "moderate" STATE_POLLUTANT_LEVEL_UNHEALTHY_SENSITIVE = "unhealthy_sensitive" STATE_POLLUTANT_LEVEL_UNHEALTHY = "unhealthy" STATE_POLLUTANT_LEVEL_VERY_UNHEALTHY = "very_unhealthy" STATE_POLLUTANT_LEVEL_HAZARDOUS = "hazardous" POLLUTANT_LEVELS = { (0, 50): (STATE_POLLUTANT_LEVEL_GOOD, "mdi:emoticon-excited"), (51, 100): (STATE_POLLUTANT_LEVEL_MODERATE, "mdi:emoticon-happy"), (101, 150): (STATE_POLLUTANT_LEVEL_UNHEALTHY_SENSITIVE, "mdi:emoticon-neutral"), (151, 200): (STATE_POLLUTANT_LEVEL_UNHEALTHY, "mdi:emoticon-sad"), (201, 300): (STATE_POLLUTANT_LEVEL_VERY_UNHEALTHY, "mdi:emoticon-dead"), (301, 1000): (STATE_POLLUTANT_LEVEL_HAZARDOUS, "mdi:biohazard"), } POLLUTANT_UNITS = { "co": CONCENTRATION_PARTS_PER_MILLION, "n2": CONCENTRATION_PARTS_PER_BILLION, "o3": CONCENTRATION_PARTS_PER_BILLION, "p1": CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, "p2": CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, "s2": CONCENTRATION_PARTS_PER_BILLION, } async def async_setup_entry(hass, config_entry, async_add_entities): """Set up AirVisual sensors based on a config entry.""" coordinator = hass.data[DOMAIN][DATA_COORDINATOR][config_entry.entry_id] if config_entry.data[CONF_INTEGRATION_TYPE] in [ INTEGRATION_TYPE_GEOGRAPHY_COORDS, INTEGRATION_TYPE_GEOGRAPHY_NAME, ]: sensors = [ AirVisualGeographySensor( coordinator, config_entry, kind, name, icon, unit, locale, ) for locale in GEOGRAPHY_SENSOR_LOCALES for kind, name, icon, unit in GEOGRAPHY_SENSORS ] else: sensors = [ AirVisualNodeProSensor(coordinator, kind, name, device_class, icon, unit) for kind, name, device_class, icon, unit in NODE_PRO_SENSORS ] async_add_entities(sensors, True) class AirVisualGeographySensor(AirVisualEntity, SensorEntity): """Define an AirVisual sensor related to geography data via the Cloud API.""" def __init__(self, coordinator, config_entry, kind, name, icon, unit, locale): """Initialize.""" super().__init__(coordinator) if kind == SENSOR_KIND_LEVEL: self._attr_device_class = DEVICE_CLASS_POLLUTANT_LEVEL elif kind == SENSOR_KIND_POLLUTANT: self._attr_device_class = DEVICE_CLASS_POLLUTANT_LABEL self._attr_extra_state_attributes.update( { ATTR_CITY: config_entry.data.get(CONF_CITY), ATTR_STATE: config_entry.data.get(CONF_STATE), ATTR_COUNTRY: config_entry.data.get(CONF_COUNTRY), } ) self._attr_icon = icon self._attr_name = f"{GEOGRAPHY_SENSOR_LOCALES[locale]} {name}" self._attr_unique_id = f"{config_entry.unique_id}_{locale}_{kind}" self._attr_unit_of_measurement = unit self._config_entry = config_entry self._kind = kind self._locale = locale @property def available(self) -> bool: """Return if entity is available.""" return super().available and self.coordinator.data["current"]["pollution"] @callback def update_from_latest_data(self): """Update the entity from the latest data.""" try: data = self.coordinator.data["current"]["pollution"] except KeyError: return if self._kind == SENSOR_KIND_LEVEL: aqi = data[f"aqi{self._locale}"] [(self._attr_state, self._attr_icon)] = [ (name, icon) for (floor, ceiling), (name, icon) in POLLUTANT_LEVELS.items() if floor <= aqi <= ceiling ] elif self._kind == SENSOR_KIND_AQI: self._attr_state = data[f"aqi{self._locale}"] elif self._kind == SENSOR_KIND_POLLUTANT: symbol = data[f"main{self._locale}"] self._attr_state = symbol self._attr_extra_state_attributes.update( { ATTR_POLLUTANT_SYMBOL: symbol, ATTR_POLLUTANT_UNIT: POLLUTANT_UNITS[symbol], } ) # Displaying the geography on the map relies upon putting the latitude/longitude # in the entity attributes with "latitude" and "longitude" as the keys. # Conversely, we can hide the location on the map by using other keys, like # "lati" and "long". # # We use any coordinates in the config entry and, in the case of a geography by # name, we fall back to the latitude longitude provided in the coordinator data: latitude = self._config_entry.data.get( CONF_LATITUDE, self.coordinator.data["location"]["coordinates"][1], ) longitude = self._config_entry.data.get( CONF_LONGITUDE, self.coordinator.data["location"]["coordinates"][0], ) if self._config_entry.options[CONF_SHOW_ON_MAP]: self._attr_extra_state_attributes[ATTR_LATITUDE] = latitude self._attr_extra_state_attributes[ATTR_LONGITUDE] = longitude self._attr_extra_state_attributes.pop("lati", None) self._attr_extra_state_attributes.pop("long", None) else: self._attr_extra_state_attributes["lati"] = latitude self._attr_extra_state_attributes["long"] = longitude self._attr_extra_state_attributes.pop(ATTR_LATITUDE, None) self._attr_extra_state_attributes.pop(ATTR_LONGITUDE, None) class AirVisualNodeProSensor(AirVisualEntity, SensorEntity): """Define an AirVisual sensor related to a Node/Pro unit.""" def __init__(self, coordinator, kind, name, device_class, icon, unit): """Initialize.""" super().__init__(coordinator) self._attr_device_class = device_class self._attr_icon = icon self._attr_unit_of_measurement = unit self._kind = kind self._name = name @property def device_info(self): """Return device registry information for this entity.""" return { "identifiers": {(DOMAIN, self.coordinator.data["serial_number"])}, "name": self.coordinator.data["settings"]["node_name"], "manufacturer": "AirVisual", "model": f'{self.coordinator.data["status"]["model"]}', "sw_version": ( f'Version {self.coordinator.data["status"]["system_version"]}' f'{self.coordinator.data["status"]["app_version"]}' ), } @property def name(self): """Return the name.""" node_name = self.coordinator.data["settings"]["node_name"] return f"{node_name} Node/Pro: {self._name}" @property def unique_id(self): """Return a unique, Home Assistant friendly identifier for this entity.""" return f"{self.coordinator.data['serial_number']}_{self._kind}" @callback def update_from_latest_data(self): """Update the entity from the latest data.""" if self._kind == SENSOR_KIND_AQI: if self.coordinator.data["settings"]["is_aqi_usa"]: self._attr_state = self.coordinator.data["measurements"]["aqi_us"] else: self._attr_state = self.coordinator.data["measurements"]["aqi_cn"] elif self._kind == SENSOR_KIND_BATTERY_LEVEL: self._attr_state = self.coordinator.data["status"]["battery"] elif self._kind == SENSOR_KIND_CO2: self._attr_state = self.coordinator.data["measurements"].get("co2") elif self._kind == SENSOR_KIND_HUMIDITY: self._attr_state = self.coordinator.data["measurements"].get("humidity") elif self._kind == SENSOR_KIND_PM_0_1: self._attr_state = self.coordinator.data["measurements"].get("pm0_1") elif self._kind == SENSOR_KIND_PM_1_0: self._attr_state = self.coordinator.data["measurements"].get("pm1_0") elif self._kind == SENSOR_KIND_PM_2_5: self._attr_state = self.coordinator.data["measurements"].get("pm2_5") elif self._kind == SENSOR_KIND_TEMPERATURE: self._attr_state = self.coordinator.data["measurements"].get( "temperature_C" ) elif self._kind == SENSOR_KIND_VOC: self._attr_state = self.coordinator.data["measurements"].get("voc")
import logging from typing import List, NoReturn, OrderedDict, Union from django.db import transaction from hexbytes import HexBytes from gnosis.eth import EthereumClient, EthereumClientProvider from ..models import (EthereumBlock, EthereumTx, InternalTxDecoded, MultisigConfirmation, MultisigTransaction, SafeStatus) logger = logging.getLogger(__name__) class TransactionNotFoundException(Exception): pass class TransactionWithoutBlockException(Exception): pass class BlockNotFoundException(Exception): pass class EthereumBlockHashMismatch(Exception): pass class IndexServiceProvider: def __new__(cls): if not hasattr(cls, 'instance'): from django.conf import settings cls.instance = IndexService(EthereumClientProvider(), settings.ETH_REORG_BLOCKS) return cls.instance @classmethod def del_singleton(cls): if hasattr(cls, "instance"): del cls.instance # TODO Test IndexService class IndexService: def __init__(self, ethereum_client: EthereumClient, eth_reorg_blocks: int): self.ethereum_client = ethereum_client self.eth_reorg_blocks = eth_reorg_blocks def block_get_or_create_from_block_number(self, block_number: int): try: return EthereumBlock.get(number=block_number) except EthereumBlock.DoesNotExist: current_block_number = self.ethereum_client.current_block_number # For reorgs block = self.ethereum_client.get_block(block_number) confirmed = (current_block_number - block['number']) >= self.eth_reorg_blocks return EthereumBlock.objects.create_from_block(block, cofirmed=confirmed) def tx_create_or_update_from_tx_hash(self, tx_hash: str) -> 'EthereumTx': try: ethereum_tx = EthereumTx.objects.get(tx_hash=tx_hash) # For txs stored before being mined if ethereum_tx.block is None: tx_receipt = self.ethereum_client.get_transaction_receipt(tx_hash) ethereum_block = self.block_get_or_create_from_block_number(tx_receipt['blockNumber']) ethereum_tx.update_with_block_and_receipt(ethereum_block, tx_receipt) return ethereum_tx except EthereumTx.DoesNotExist: tx_receipt = self.ethereum_client.get_transaction_receipt(tx_hash) ethereum_block = self.block_get_or_create_from_block_number(tx_receipt['blockNumber']) tx = self.ethereum_client.get_transaction(tx_hash) return EthereumTx.objects.create_from_tx_dict(tx, tx_receipt=tx_receipt, ethereum_block=ethereum_block) def txs_create_or_update_from_tx_hashes(self, tx_hashes: List[Union[str, bytes]]) -> List['EthereumTx']: # Search first in database ethereum_txs_dict = OrderedDict.fromkeys([HexBytes(tx_hash).hex() for tx_hash in tx_hashes]) db_ethereum_txs = EthereumTx.objects.filter(tx_hash__in=tx_hashes).exclude(block=None) for db_ethereum_tx in db_ethereum_txs: ethereum_txs_dict[db_ethereum_tx.tx_hash] = db_ethereum_tx # Retrieve from the node the txs missing from database tx_hashes_not_in_db = [tx_hash for tx_hash, ethereum_tx in ethereum_txs_dict.items() if not ethereum_tx] if not tx_hashes_not_in_db: return list(ethereum_txs_dict.values()) self.ethereum_client = EthereumClientProvider() # Get receipts for hashes not in db tx_receipts = [] for tx_hash, tx_receipt in zip(tx_hashes_not_in_db, self.ethereum_client.get_transaction_receipts(tx_hashes_not_in_db)): tx_receipt = tx_receipt or self.ethereum_client.get_transaction_receipt(tx_hash) # Retry fetching if failed if not tx_receipt: raise TransactionNotFoundException(f'Cannot find tx-receipt with tx-hash={HexBytes(tx_hash).hex()}') elif tx_receipt.get('blockNumber') is None: raise TransactionWithoutBlockException(f'Cannot find blockNumber for tx-receipt with ' f'tx-hash={HexBytes(tx_hash).hex()}') else: tx_receipts.append(tx_receipt) # Get transactions for hashes not in db txs = self.ethereum_client.get_transactions(tx_hashes_not_in_db) block_numbers = set() for tx_hash, tx in zip(tx_hashes_not_in_db, txs): tx = tx or self.ethereum_client.get_transaction(tx_hash) # Retry fetching if failed if not tx: raise TransactionNotFoundException(f'Cannot find tx with tx-hash={HexBytes(tx_hash).hex()}') elif tx.get('blockNumber') is None: raise TransactionWithoutBlockException(f'Cannot find blockNumber for tx with ' f'tx-hash={HexBytes(tx_hash).hex()}') block_numbers.add(tx['blockNumber']) blocks = self.ethereum_client.get_blocks(block_numbers) block_dict = {} for block_number, block in zip(block_numbers, blocks): block = block or self.ethereum_client.get_block(block_number) # Retry fetching if failed if not block: raise BlockNotFoundException(f'Block with number={block_number} was not found') assert block_number == block['number'] block_dict[block['number']] = block # Create new transactions or update them if they have no receipt current_block_number = self.ethereum_client.current_block_number for tx, tx_receipt in zip(txs, tx_receipts): block = block_dict.get(tx['blockNumber']) confirmed = (current_block_number - block['number']) >= self.eth_reorg_blocks ethereum_block: EthereumBlock = EthereumBlock.objects.get_or_create_from_block(block, confirmed=confirmed) if HexBytes(ethereum_block.block_hash) != block['hash']: raise EthereumBlockHashMismatch(f'Stored block={ethereum_block.number} ' f'with hash={ethereum_block.block_hash} ' f'is not marching retrieved hash={block['hash'].hex()}') try: ethereum_tx = EthereumTx.objects.get(tx_hash=tx['hash']) # For txs stored before being mined ethereum_tx.update_with_block_and_receipt(ethereum_block, tx_receipt) ethereum_txs_dict[ethereum_tx.tx_hash] = ethereum_tx except EthereumTx.DoesNotExist: ethereum_tx = EthereumTx.objects.create_from_tx_dict(tx, tx_receipt=tx_receipt, ethereum_block=ethereum_block) ethereum_txs_dict[HexBytes(ethereum_tx.tx_hash).hex()] = ethereum_tx return list(ethereum_txs_dict.values()) @transaction.atomic def reindex_addresses(self, addresses: List[str]) -> NoReturn: """ Given a list of safe addresses it will delete all `SafeStatus`, conflicting `MultisigTxs` and will mark every `InternalTxDecoded` not processed to be processed again :param addresses: List of checksummed addresses or queryset :return: Number of `SafeStatus` deleted """ if not addresses: return SafeStatus.objects.filter(address__in=addresses).delete() MultisigTransaction.objects.exclude( ethereum_tx=None ).filter( safe__in=addresses ).delete() # Remove not indexed transactions InternalTxDecoded.objects.filter(internal_tx___from__in=addresses).update(processed=False) @transaction.atomic def reindex_all(self) -> NoReturn: MultisigConfirmation.objects.filter(signature=None).delete() # Remove onchain confirmations MultisigTransaction.objects.exclude(ethereum_tx=None).delete() # Remove not indexed transactions SafeStatus.objects.all().delete() InternalTxDecoded.objects.update(processed=False)
import logging from typing import List, NoReturn, OrderedDict, Union from django.db import transaction from hexbytes import HexBytes from gnosis.eth import EthereumClient, EthereumClientProvider from ..models import (EthereumBlock, EthereumTx, InternalTxDecoded, MultisigConfirmation, MultisigTransaction, SafeStatus) logger = logging.getLogger(__name__) class TransactionNotFoundException(Exception): pass class TransactionWithoutBlockException(Exception): pass class BlockNotFoundException(Exception): pass class EthereumBlockHashMismatch(Exception): pass class IndexServiceProvider: def __new__(cls): if not hasattr(cls, 'instance'): from django.conf import settings cls.instance = IndexService(EthereumClientProvider(), settings.ETH_REORG_BLOCKS) return cls.instance @classmethod def del_singleton(cls): if hasattr(cls, "instance"): del cls.instance # TODO Test IndexService class IndexService: def __init__(self, ethereum_client: EthereumClient, eth_reorg_blocks: int): self.ethereum_client = ethereum_client self.eth_reorg_blocks = eth_reorg_blocks def block_get_or_create_from_block_number(self, block_number: int): try: return EthereumBlock.get(number=block_number) except EthereumBlock.DoesNotExist: current_block_number = self.ethereum_client.current_block_number # For reorgs block = self.ethereum_client.get_block(block_number) confirmed = (current_block_number - block['number']) >= self.eth_reorg_blocks return EthereumBlock.objects.create_from_block(block, cofirmed=confirmed) def tx_create_or_update_from_tx_hash(self, tx_hash: str) -> 'EthereumTx': try: ethereum_tx = EthereumTx.objects.get(tx_hash=tx_hash) # For txs stored before being mined if ethereum_tx.block is None: tx_receipt = self.ethereum_client.get_transaction_receipt(tx_hash) ethereum_block = self.block_get_or_create_from_block_number(tx_receipt['blockNumber']) ethereum_tx.update_with_block_and_receipt(ethereum_block, tx_receipt) return ethereum_tx except EthereumTx.DoesNotExist: tx_receipt = self.ethereum_client.get_transaction_receipt(tx_hash) ethereum_block = self.block_get_or_create_from_block_number(tx_receipt['blockNumber']) tx = self.ethereum_client.get_transaction(tx_hash) return EthereumTx.objects.create_from_tx_dict(tx, tx_receipt=tx_receipt, ethereum_block=ethereum_block) def txs_create_or_update_from_tx_hashes(self, tx_hashes: List[Union[str, bytes]]) -> List['EthereumTx']: # Search first in database ethereum_txs_dict = OrderedDict.fromkeys([HexBytes(tx_hash).hex() for tx_hash in tx_hashes]) db_ethereum_txs = EthereumTx.objects.filter(tx_hash__in=tx_hashes).exclude(block=None) for db_ethereum_tx in db_ethereum_txs: ethereum_txs_dict[db_ethereum_tx.tx_hash] = db_ethereum_tx # Retrieve from the node the txs missing from database tx_hashes_not_in_db = [tx_hash for tx_hash, ethereum_tx in ethereum_txs_dict.items() if not ethereum_tx] if not tx_hashes_not_in_db: return list(ethereum_txs_dict.values()) self.ethereum_client = EthereumClientProvider() # Get receipts for hashes not in db tx_receipts = [] for tx_hash, tx_receipt in zip(tx_hashes_not_in_db, self.ethereum_client.get_transaction_receipts(tx_hashes_not_in_db)): tx_receipt = tx_receipt or self.ethereum_client.get_transaction_receipt(tx_hash) # Retry fetching if failed if not tx_receipt: raise TransactionNotFoundException(f'Cannot find tx-receipt with tx-hash={HexBytes(tx_hash).hex()}') elif tx_receipt.get('blockNumber') is None: raise TransactionWithoutBlockException(f'Cannot find blockNumber for tx-receipt with ' f'tx-hash={HexBytes(tx_hash).hex()}') else: tx_receipts.append(tx_receipt) # Get transactions for hashes not in db txs = self.ethereum_client.get_transactions(tx_hashes_not_in_db) block_numbers = set() for tx_hash, tx in zip(tx_hashes_not_in_db, txs): tx = tx or self.ethereum_client.get_transaction(tx_hash) # Retry fetching if failed if not tx: raise TransactionNotFoundException(f'Cannot find tx with tx-hash={HexBytes(tx_hash).hex()}') elif tx.get('blockNumber') is None: raise TransactionWithoutBlockException(f'Cannot find blockNumber for tx with ' f'tx-hash={HexBytes(tx_hash).hex()}') block_numbers.add(tx['blockNumber']) blocks = self.ethereum_client.get_blocks(block_numbers) block_dict = {} for block_number, block in zip(block_numbers, blocks): block = block or self.ethereum_client.get_block(block_number) # Retry fetching if failed if not block: raise BlockNotFoundException(f'Block with number={block_number} was not found') assert block_number == block['number'] block_dict[block['number']] = block # Create new transactions or update them if they have no receipt current_block_number = self.ethereum_client.current_block_number for tx, tx_receipt in zip(txs, tx_receipts): block = block_dict.get(tx['blockNumber']) confirmed = (current_block_number - block['number']) >= self.eth_reorg_blocks ethereum_block: EthereumBlock = EthereumBlock.objects.get_or_create_from_block(block, confirmed=confirmed) if HexBytes(ethereum_block.block_hash) != block['hash']: raise EthereumBlockHashMismatch(f'Stored block={ethereum_block.number} ' f'with hash={ethereum_block.block_hash} ' f'is not marching retrieved hash={block["hash"].hex()}') try: ethereum_tx = EthereumTx.objects.get(tx_hash=tx['hash']) # For txs stored before being mined ethereum_tx.update_with_block_and_receipt(ethereum_block, tx_receipt) ethereum_txs_dict[ethereum_tx.tx_hash] = ethereum_tx except EthereumTx.DoesNotExist: ethereum_tx = EthereumTx.objects.create_from_tx_dict(tx, tx_receipt=tx_receipt, ethereum_block=ethereum_block) ethereum_txs_dict[HexBytes(ethereum_tx.tx_hash).hex()] = ethereum_tx return list(ethereum_txs_dict.values()) @transaction.atomic def reindex_addresses(self, addresses: List[str]) -> NoReturn: """ Given a list of safe addresses it will delete all `SafeStatus`, conflicting `MultisigTxs` and will mark every `InternalTxDecoded` not processed to be processed again :param addresses: List of checksummed addresses or queryset :return: Number of `SafeStatus` deleted """ if not addresses: return SafeStatus.objects.filter(address__in=addresses).delete() MultisigTransaction.objects.exclude( ethereum_tx=None ).filter( safe__in=addresses ).delete() # Remove not indexed transactions InternalTxDecoded.objects.filter(internal_tx___from__in=addresses).update(processed=False) @transaction.atomic def reindex_all(self) -> NoReturn: MultisigConfirmation.objects.filter(signature=None).delete() # Remove onchain confirmations MultisigTransaction.objects.exclude(ethereum_tx=None).delete() # Remove not indexed transactions SafeStatus.objects.all().delete() InternalTxDecoded.objects.update(processed=False)
import os import json from pathlib import Path from jinja2 import Environment, FileSystemLoader from aids.app.settings import BASE_DIR class toHtml: def __init__(self): self.env = Environment(loader=FileSystemLoader(BASE_DIR / 'templates')) self.out_path = Path().cwd() self.scen_out_file = 'scenario.json' self.story_out_file = 'story.json' def new_dir(self, folder): if folder: try: os.mkdir(self.out_path / folder) except FileExistsError: pass with open(BASE_DIR / 'static/style.css', 'r') as file: style = file.read() with open(self.out_path / f'{folder}/style.css', 'w') as file: file.write(style) def story_to_html(self, infile: str=None): infile = infile or self.out_path / self.story_out_file self.new_dir('stories') with open(infile) as file: stories = json.load(file) story_templ = self.env.get_template('story.html') story_number = {} for story in reversed(stories): if story['title']: story['title'] = story['title'].replace('/', '-') try: story_number[story["title"]] except KeyError: # new story story_number = {story["title"]: ""} if not os.path.exists( self.out_path / f'stories/{story['title']}{story_number[story['title']]}.html' ): htmlfile = open(self.out_path / f'stories/{story['title']}.html', 'w') else: # story from same scenario if story_number[story["title"]]: story_number[story["title"]] += 1 htmlfile = open( self.out_path / f'stories/{story['title']}{story_number[story['title']]}.html', 'w' ) else: story_number[story["title"]] = 2 htmlfile = open( self.out_path / f'stories/{story['title']}{story_number[story['title']]}.html', 'w' ) htmlfile.write( story_templ.render({ 'story': story, 'story_number': story_number }) ) htmlfile.close() index = self.env.get_template('index.html') with open(self.out_path / 'story_index.html', 'w') as outfile: outfile.write( index.render( {'objects': stories, 'content_type': 'stories' }) ) print('Stories successfully formatted') def scenario_to_html(self, infile: str=None): infile = infile or self.out_path / self.scen_out_file self.new_dir('scenarios') with open(infile) as file: scenarios = json.load(file) subscen_paths = {} parent_scen = [] for scenario in reversed(scenarios): scenario['title'] = scenario['title'].replace('/', '-') if 'isOption' not in scenario or not scenario['isOption']: # base scenario, initializing the path scenario['path'] = 'scenarios/' with open( self.out_path / f'{scenario['path'] + scenario['title']}.html', 'w' ) as file: scen_templ = self.env.get_template('scenario.html') file.write( scen_templ.render({ 'scenario': scenario, 'content_type': 'scenario' }) ) parent_scen.append(scenario) else: scenario['path'] = subscen_paths[scenario['title']] with open( self.out_path / f'{scenario['path']}/{scenario['title']}.html', 'w' ) as file: scen_templ = self.env.get_template('scenario.html') file.write( scen_templ.render({ 'scenario': scenario, 'content_type': 'scenario' }) ) if "options" in scenario and any(scenario['options']): for subscen in scenario['options']: if subscen and "title" in subscen: subscen['title'] = subscen['title'].replace('/', '-') subscen['path'] = f'{scenario['path']}{scenario['title']}' subscen_paths[subscen['title']] = subscen['path'] + '/' self.new_dir(subscen['path']) index = self.env.get_template('index.html') with open(self.out_path / 'scen_index.html', 'w') as outfile: outfile.write( index.render( {'objects': parent_scen, 'content_type': 'scenarios' }) ) print('Scenarios successfully formatted')
import os import json from pathlib import Path from jinja2 import Environment, FileSystemLoader from aids.app.settings import BASE_DIR class toHtml: def __init__(self): self.env = Environment(loader=FileSystemLoader(BASE_DIR / 'templates')) self.out_path = Path().cwd() self.scen_out_file = 'scenario.json' self.story_out_file = 'story.json' def new_dir(self, folder): if folder: try: os.mkdir(self.out_path / folder) except FileExistsError: pass with open(BASE_DIR / 'static/style.css', 'r') as file: style = file.read() with open(self.out_path / f'{folder}/style.css', 'w') as file: file.write(style) def story_to_html(self, infile: str=None): infile = infile or self.out_path / self.story_out_file self.new_dir('stories') with open(infile) as file: stories = json.load(file) story_templ = self.env.get_template('story.html') story_number = {} for story in reversed(stories): if story['title']: story['title'] = story['title'].replace('/', '-') try: story_number[story["title"]] except KeyError: # new story story_number = {story["title"]: ""} if not os.path.exists( self.out_path / f'stories/{story["title"]}{story_number[story["title"]]}.html' ): htmlfile = open(self.out_path / f'stories/{story["title"]}.html', 'w') else: # story from same scenario if story_number[story["title"]]: story_number[story["title"]] += 1 htmlfile = open( self.out_path / f'stories/{story["title"]}{story_number[story["title"]]}.html', 'w' ) else: story_number[story["title"]] = 2 htmlfile = open( self.out_path / f'stories/{story["title"]}{story_number[story["title"]]}.html', 'w' ) htmlfile.write( story_templ.render({ 'story': story, 'story_number': story_number }) ) htmlfile.close() index = self.env.get_template('index.html') with open(self.out_path / 'story_index.html', 'w') as outfile: outfile.write( index.render( {'objects': stories, 'content_type': 'stories' }) ) print('Stories successfully formatted') def scenario_to_html(self, infile: str=None): infile = infile or self.out_path / self.scen_out_file self.new_dir('scenarios') with open(infile) as file: scenarios = json.load(file) subscen_paths = {} parent_scen = [] for scenario in reversed(scenarios): scenario['title'] = scenario['title'].replace('/', '-') if 'isOption' not in scenario or not scenario['isOption']: # base scenario, initializing the path scenario['path'] = 'scenarios/' with open( self.out_path / f'{scenario["path"] + scenario["title"]}.html', 'w' ) as file: scen_templ = self.env.get_template('scenario.html') file.write( scen_templ.render({ 'scenario': scenario, 'content_type': 'scenario' }) ) parent_scen.append(scenario) else: scenario['path'] = subscen_paths[scenario['title']] with open( self.out_path / f'{scenario["path"]}/{scenario["title"]}.html', 'w' ) as file: scen_templ = self.env.get_template('scenario.html') file.write( scen_templ.render({ 'scenario': scenario, 'content_type': 'scenario' }) ) if "options" in scenario and any(scenario['options']): for subscen in scenario['options']: if subscen and "title" in subscen: subscen['title'] = subscen['title'].replace('/', '-') subscen['path'] = f'{scenario["path"]}{scenario["title"]}' subscen_paths[subscen['title']] = subscen['path'] + '/' self.new_dir(subscen['path']) index = self.env.get_template('index.html') with open(self.out_path / 'scen_index.html', 'w') as outfile: outfile.write( index.render( {'objects': parent_scen, 'content_type': 'scenarios' }) ) print('Scenarios successfully formatted')
""" 提目:输入两个递增排序的链表,合并这两个链表并使新链表中的结点仍然是按照递增排序的。 例如输入图3.11中的链表1和链表2,则合并之后的升序链表如链表3所示。 总结:需要注意最后节点为 None 的情况,避免链表断裂(另可用递归的思想,代码更加整洁) """ import unittest class ListNode(object): def __init__(self, x): self.val = x self.next = None def __repr__(self): return f'<ListNode object val: {self.val} next_val: {getattr(self.next, 'val', None)}>' def get_node_val_list(n): r = [] while n: r.append(n.val) n = n.next return r def merge_sorted_nodes(n1: ListNode, n2: ListNode): if not n1 or not n2: return None # make minial node as n1 if n2.val < n1.val: n1, n2 = n2, n1 p1, p2 = n1, n2 while p1 and p2: # print(p1, p2) # link the end node if not p1.next: p1.next = p2 break next_p1 = p1.next next_p2 = p2.next if p2.val < p1.next.val: p1.next = p2 p2.next = next_p1 p1 = p1.next p2 = next_p2 elif p2.val >= p1.next.val: p1 = next_p1 return n1 class Test(unittest.TestCase): # n1: 1->3->5 # m2: 2->4->6 def test_1(self): n1 = ListNode(1) n2 = ListNode(3) n3 = ListNode(5) n1.next = n2 n2.next = n3 m1 = ListNode(2) m2 = ListNode(4) m3 = ListNode(6) m1.next = m2 m2.next = m3 r = merge_sorted_nodes(n1, m1) # print(r, r.next, r.next.next, r.next.next.next, r.next.next.next.next, r.next.next.next.next.next) self.assertEqual([1, 2, 3, 4, 5, 6], get_node_val_list(r)) # 两个链表中有重复的数字 # n1: 1->3->5 # m2: 1->3->5 def test_2(self): n1 = ListNode(1) n2 = ListNode(3) n3 = ListNode(5) n1.next = n2 n2.next = n3 m1 = ListNode(1) m2 = ListNode(3) m3 = ListNode(5) m1.next = m2 m2.next = m3 r = merge_sorted_nodes(n1, m1) # print(r, r.next, r.next.next, r.next.next.next, r.next.next.next.next, r.next.next.next.next.next) self.assertEqual([1, 1, 3, 3, 5, 5], get_node_val_list(r)) # 两个链表都只有一个数字 # list1: 1 # list2: 2 def test_3(self): n1 = ListNode(1) m1 = ListNode(2) r = merge_sorted_nodes(n1, m1) self.assertEqual([1, 2], get_node_val_list(r))
""" 提目:输入两个递增排序的链表,合并这两个链表并使新链表中的结点仍然是按照递增排序的。 例如输入图3.11中的链表1和链表2,则合并之后的升序链表如链表3所示。 总结:需要注意最后节点为 None 的情况,避免链表断裂(另可用递归的思想,代码更加整洁) """ import unittest class ListNode(object): def __init__(self, x): self.val = x self.next = None def __repr__(self): return f'<ListNode object val: {self.val} next_val: {getattr(self.next, "val", None)}>' def get_node_val_list(n): r = [] while n: r.append(n.val) n = n.next return r def merge_sorted_nodes(n1: ListNode, n2: ListNode): if not n1 or not n2: return None # make minial node as n1 if n2.val < n1.val: n1, n2 = n2, n1 p1, p2 = n1, n2 while p1 and p2: # print(p1, p2) # link the end node if not p1.next: p1.next = p2 break next_p1 = p1.next next_p2 = p2.next if p2.val < p1.next.val: p1.next = p2 p2.next = next_p1 p1 = p1.next p2 = next_p2 elif p2.val >= p1.next.val: p1 = next_p1 return n1 class Test(unittest.TestCase): # n1: 1->3->5 # m2: 2->4->6 def test_1(self): n1 = ListNode(1) n2 = ListNode(3) n3 = ListNode(5) n1.next = n2 n2.next = n3 m1 = ListNode(2) m2 = ListNode(4) m3 = ListNode(6) m1.next = m2 m2.next = m3 r = merge_sorted_nodes(n1, m1) # print(r, r.next, r.next.next, r.next.next.next, r.next.next.next.next, r.next.next.next.next.next) self.assertEqual([1, 2, 3, 4, 5, 6], get_node_val_list(r)) # 两个链表中有重复的数字 # n1: 1->3->5 # m2: 1->3->5 def test_2(self): n1 = ListNode(1) n2 = ListNode(3) n3 = ListNode(5) n1.next = n2 n2.next = n3 m1 = ListNode(1) m2 = ListNode(3) m3 = ListNode(5) m1.next = m2 m2.next = m3 r = merge_sorted_nodes(n1, m1) # print(r, r.next, r.next.next, r.next.next.next, r.next.next.next.next, r.next.next.next.next.next) self.assertEqual([1, 1, 3, 3, 5, 5], get_node_val_list(r)) # 两个链表都只有一个数字 # list1: 1 # list2: 2 def test_3(self): n1 = ListNode(1) m1 = ListNode(2) r = merge_sorted_nodes(n1, m1) self.assertEqual([1, 2], get_node_val_list(r))
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Unit tests for AWS Security Token Service (AWS STS) usage functions. """ import json import unittest.mock import pytest import requests import boto3 from botocore.exceptions import ClientError import assume_role def test_setup(make_stubber, monkeypatch, unique_names): iam_resource = boto3.resource('iam') iam_stubber = make_stubber(iam_resource.meta.client) user_arn = f'arn:aws:iam:123456789012::user/{unique_names['user']}' role_arn = f'arn:aws:iam:123456789012::role/{unique_names['role']}' policy_arn = f'arn:aws:iam:123456789012::policy/{unique_names['policy']}' monkeypatch.setattr(assume_role, 'unique_name', lambda x: unique_names[x]) monkeypatch.setattr(assume_role, 'progress_bar', lambda x: None) iam_stubber.stub_create_user(unique_names['user']) iam_stubber.stub_create_access_key(unique_names['user']) iam_stubber.stub_get_user(unique_names['user'], user_arn) iam_stubber.stub_create_role(unique_names['role']) iam_stubber.stub_create_policy(unique_names['policy'], policy_arn) iam_stubber.stub_attach_role_policy(unique_names['role'], policy_arn) iam_stubber.stub_get_policy(policy_arn) iam_stubber.stub_get_role(unique_names['role'], role_arn) iam_stubber.stub_put_user_policy(unique_names['user'], unique_names['user-policy']) user, user_key, role = assume_role.setup(iam_resource) assert user is not None assert user_key is not None assert role is not None @pytest.mark.parametrize('error_code', [None, 'AccessDenied', 'TestException']) def test_show_access_denied_without_role(make_stubber, monkeypatch, error_code): s3_resource = boto3.resource('s3') s3_stubber = make_stubber(s3_resource.meta.client) monkeypatch.setattr( boto3, 'resource', lambda x, aws_access_key_id, aws_secret_access_key: s3_resource) s3_stubber.stub_list_buckets([], error_code) if error_code is None: with pytest.raises(RuntimeError): assume_role.show_access_denied_without_role(unittest.mock.MagicMock()) elif error_code == 'AccessDenied': assume_role.show_access_denied_without_role(unittest.mock.MagicMock()) elif error_code == 'TestException': with pytest.raises(ClientError): assume_role.show_access_denied_without_role(unittest.mock.MagicMock()) def test_list_buckets_from_assumed_role(make_stubber, monkeypatch): sts = boto3.client('sts') sts_stubber = make_stubber(sts) s3 = boto3.resource('s3') s3_stubber = make_stubber(s3.meta.client) role_arn = 'arn:aws:iam::123456789012:role/test-role' session_name = 'test-session' buckets = [unittest.mock.MagicMock(), unittest.mock.MagicMock()] for b in buckets: b.name = 'test-bucket' monkeypatch.setattr( boto3, 'client', lambda x, aws_access_key_id, aws_secret_access_key: sts) monkeypatch.setattr( boto3, 'resource', lambda x, aws_access_key_id, aws_secret_access_key, aws_session_token: s3) sts_stubber.stub_assume_role(role_arn, session_name) s3_stubber.stub_list_buckets(buckets) assume_role.list_buckets_from_assumed_role( unittest.mock.MagicMock(), role_arn, session_name) def test_teardown(make_stubber): iam = boto3.resource('iam') iam_stubber = make_stubber(iam.meta.client) role_name = 'test-role' role_policies = [unittest.mock.MagicMock( policy_name='test-role-policy', arn='arn:aws:iam:123456789012::policy/test-role-policy')] user_name = 'test-user' user_policies = [unittest.mock.MagicMock(policy_name='test-user-policy')] user_key_ids = ['test-key-id-plus-more-characters'] iam_stubber.stub_list_attached_role_policies( unittest.mock.ANY, {pol.policy_name: pol.arn for pol in role_policies}) for pol in role_policies: iam_stubber.stub_get_policy(pol.arn) iam_stubber.stub_detach_role_policy(role_name, pol.arn) iam_stubber.stub_delete_policy(pol.arn) iam_stubber.stub_delete_role(role_name) iam_stubber.stub_list_user_policies( user_name, [pol.policy_name for pol in user_policies]) for pol in user_policies: iam_stubber.stub_delete_user_policy(user_name, pol.policy_name) iam_stubber.stub_list_access_keys(user_name, user_key_ids) for key_id in user_key_ids: iam_stubber.stub_delete_access_key(user_name, key_id) iam_stubber.stub_delete_user(user_name) assume_role.teardown(iam.User(user_name), iam.Role(role_name))
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Unit tests for AWS Security Token Service (AWS STS) usage functions. """ import json import unittest.mock import pytest import requests import boto3 from botocore.exceptions import ClientError import assume_role def test_setup(make_stubber, monkeypatch, unique_names): iam_resource = boto3.resource('iam') iam_stubber = make_stubber(iam_resource.meta.client) user_arn = f'arn:aws:iam:123456789012::user/{unique_names["user"]}' role_arn = f'arn:aws:iam:123456789012::role/{unique_names["role"]}' policy_arn = f'arn:aws:iam:123456789012::policy/{unique_names["policy"]}' monkeypatch.setattr(assume_role, 'unique_name', lambda x: unique_names[x]) monkeypatch.setattr(assume_role, 'progress_bar', lambda x: None) iam_stubber.stub_create_user(unique_names['user']) iam_stubber.stub_create_access_key(unique_names['user']) iam_stubber.stub_get_user(unique_names['user'], user_arn) iam_stubber.stub_create_role(unique_names['role']) iam_stubber.stub_create_policy(unique_names['policy'], policy_arn) iam_stubber.stub_attach_role_policy(unique_names['role'], policy_arn) iam_stubber.stub_get_policy(policy_arn) iam_stubber.stub_get_role(unique_names['role'], role_arn) iam_stubber.stub_put_user_policy(unique_names['user'], unique_names['user-policy']) user, user_key, role = assume_role.setup(iam_resource) assert user is not None assert user_key is not None assert role is not None @pytest.mark.parametrize('error_code', [None, 'AccessDenied', 'TestException']) def test_show_access_denied_without_role(make_stubber, monkeypatch, error_code): s3_resource = boto3.resource('s3') s3_stubber = make_stubber(s3_resource.meta.client) monkeypatch.setattr( boto3, 'resource', lambda x, aws_access_key_id, aws_secret_access_key: s3_resource) s3_stubber.stub_list_buckets([], error_code) if error_code is None: with pytest.raises(RuntimeError): assume_role.show_access_denied_without_role(unittest.mock.MagicMock()) elif error_code == 'AccessDenied': assume_role.show_access_denied_without_role(unittest.mock.MagicMock()) elif error_code == 'TestException': with pytest.raises(ClientError): assume_role.show_access_denied_without_role(unittest.mock.MagicMock()) def test_list_buckets_from_assumed_role(make_stubber, monkeypatch): sts = boto3.client('sts') sts_stubber = make_stubber(sts) s3 = boto3.resource('s3') s3_stubber = make_stubber(s3.meta.client) role_arn = 'arn:aws:iam::123456789012:role/test-role' session_name = 'test-session' buckets = [unittest.mock.MagicMock(), unittest.mock.MagicMock()] for b in buckets: b.name = 'test-bucket' monkeypatch.setattr( boto3, 'client', lambda x, aws_access_key_id, aws_secret_access_key: sts) monkeypatch.setattr( boto3, 'resource', lambda x, aws_access_key_id, aws_secret_access_key, aws_session_token: s3) sts_stubber.stub_assume_role(role_arn, session_name) s3_stubber.stub_list_buckets(buckets) assume_role.list_buckets_from_assumed_role( unittest.mock.MagicMock(), role_arn, session_name) def test_teardown(make_stubber): iam = boto3.resource('iam') iam_stubber = make_stubber(iam.meta.client) role_name = 'test-role' role_policies = [unittest.mock.MagicMock( policy_name='test-role-policy', arn='arn:aws:iam:123456789012::policy/test-role-policy')] user_name = 'test-user' user_policies = [unittest.mock.MagicMock(policy_name='test-user-policy')] user_key_ids = ['test-key-id-plus-more-characters'] iam_stubber.stub_list_attached_role_policies( unittest.mock.ANY, {pol.policy_name: pol.arn for pol in role_policies}) for pol in role_policies: iam_stubber.stub_get_policy(pol.arn) iam_stubber.stub_detach_role_policy(role_name, pol.arn) iam_stubber.stub_delete_policy(pol.arn) iam_stubber.stub_delete_role(role_name) iam_stubber.stub_list_user_policies( user_name, [pol.policy_name for pol in user_policies]) for pol in user_policies: iam_stubber.stub_delete_user_policy(user_name, pol.policy_name) iam_stubber.stub_list_access_keys(user_name, user_key_ids) for key_id in user_key_ids: iam_stubber.stub_delete_access_key(user_name, key_id) iam_stubber.stub_delete_user(user_name) assume_role.teardown(iam.User(user_name), iam.Role(role_name))
import torch from terminaltables import AsciiTable from copy import deepcopy import numpy as np import torch.nn.functional as F def get_sr_flag(epoch, sr): # return epoch >= 5 and sr return sr def parse_module_defs(module_defs): CBL_idx = [] Conv_idx = [] ignore_idx = set() for i, module_def in enumerate(module_defs): if module_def['type'] == 'convolutional': if module_def['batch_normalize'] == '1': CBL_idx.append(i) else: Conv_idx.append(i) if module_defs[i+1]['type'] == 'maxpool' and module_defs[i+2]['type'] == 'route': #spp前一个CBL不剪 区分tiny ignore_idx.add(i) if module_defs[i+1]['type'] == 'route' and 'groups' in module_defs[i+1]: ignore_idx.add(i) elif module_def['type'] == 'shortcut': ignore_idx.add(i-1) identity_idx = (i + int(module_def['from'])) if module_defs[identity_idx]['type'] == 'convolutional': ignore_idx.add(identity_idx) elif module_defs[identity_idx]['type'] == 'shortcut': ignore_idx.add(identity_idx - 1) elif module_def['type'] == 'upsample': #上采样层前的卷积层不裁剪 ignore_idx.add(i - 1) prune_idx = [idx for idx in CBL_idx if idx not in ignore_idx] return CBL_idx, Conv_idx, prune_idx def parse_module_defs2(module_defs): CBL_idx = [] Conv_idx = [] shortcut_idx=dict() shortcut_all=set() ignore_idx = set() for i, module_def in enumerate(module_defs): if module_def['type'] == 'convolutional': if module_def['batch_normalize'] == '1': CBL_idx.append(i) else: Conv_idx.append(i) if module_defs[i+1]['type'] == 'maxpool' and module_defs[i+2]['type'] == 'route': #spp前一个CBL不剪 区分spp和tiny ignore_idx.add(i) if module_defs[i+1]['type'] == 'route' and 'groups' in module_defs[i+1]: ignore_idx.add(i) elif module_def['type'] == 'upsample': #上采样层前的卷积层不裁剪 ignore_idx.add(i - 1) elif module_def['type'] == 'shortcut': identity_idx = (i + int(module_def['from'])) if module_defs[identity_idx]['type'] == 'convolutional': #ignore_idx.add(identity_idx) shortcut_idx[i-1]=identity_idx shortcut_all.add(identity_idx) elif module_defs[identity_idx]['type'] == 'shortcut': #ignore_idx.add(identity_idx - 1) shortcut_idx[i-1]=identity_idx-1 shortcut_all.add(identity_idx-1) shortcut_all.add(i-1) prune_idx = [idx for idx in CBL_idx if idx not in ignore_idx] return CBL_idx, Conv_idx, prune_idx,shortcut_idx,shortcut_all def parse_module_defs4(module_defs): CBL_idx = [] Conv_idx = [] shortcut_idx= [] for i, module_def in enumerate(module_defs): if module_def['type'] == 'convolutional': if module_def['batch_normalize'] == '1': CBL_idx.append(i) else: Conv_idx.append(i) elif module_def['type'] == 'shortcut': shortcut_idx.append(i-1) return CBL_idx, Conv_idx, shortcut_idx def gather_bn_weights(module_list, prune_idx): size_list = [module_list[idx][1].weight.data.shape[0] for idx in prune_idx] bn_weights = torch.zeros(sum(size_list)) index = 0 for idx, size in zip(prune_idx, size_list): bn_weights[index:(index + size)] = module_list[idx][1].weight.data.abs().clone() index += size return bn_weights def write_cfg(cfg_file, module_defs): with open(cfg_file, 'w') as f: for module_def in module_defs: f.write(f"[{module_def["type"]}]\n") for key, value in module_def.items(): if key == 'batch_normalize' and value == 0: continue if key != 'type': if key == 'anchors': value = ', '.join(','.join(str(int(i)) for i in j) for j in value) f.write(f"{key}={value}\n") f.write("\n") return cfg_file class BNOptimizer(): @staticmethod def updateBN(sr_flag, module_list, s, prune_idx, epoch, idx2mask=None, opt=None): if sr_flag: # s = s if epoch <= opt.epochs * 0.5 else s * 0.01 for idx in prune_idx: # Squential(Conv, BN, Lrelu) bn_module = module_list[idx][1] bn_module.weight.grad.data.add_(s * torch.sign(bn_module.weight.data)) # L1 if idx2mask: for idx in idx2mask: bn_module = module_list[idx][1] #bn_module.weight.grad.data.add_(0.5 * s * torch.sign(bn_module.weight.data) * (1 - idx2mask[idx].cuda())) bn_module.weight.grad.data.sub_(0.99 * s * torch.sign(bn_module.weight.data) * idx2mask[idx].cuda()) def obtain_quantiles(bn_weights, num_quantile=5): sorted_bn_weights, i = torch.sort(bn_weights) total = sorted_bn_weights.shape[0] quantiles = sorted_bn_weights.tolist()[-1::-total//num_quantile][::-1] print("\nBN weights quantile:") quantile_table = [ [f'{i}/{num_quantile}' for i in range(1, num_quantile+1)], ["%.3f" % quantile for quantile in quantiles] ] print(AsciiTable(quantile_table).table) return quantiles def get_input_mask(module_defs, idx, CBLidx2mask): if idx == 0: return np.ones(3) if module_defs[idx - 1]['type'] == 'convolutional': return CBLidx2mask[idx - 1] elif module_defs[idx - 1]['type'] == 'shortcut': return CBLidx2mask[idx - 2] elif module_defs[idx - 1]['type'] == 'route': route_in_idxs = [] for layer_i in module_defs[idx - 1]['layers'].split(","): if int(layer_i) < 0: route_in_idxs.append(idx - 1 + int(layer_i)) else: route_in_idxs.append(int(layer_i)) if len(route_in_idxs) == 1: mask = CBLidx2mask[route_in_idxs[0]] if 'groups' in module_defs[idx - 1]: return mask[(mask.shape[0]//2):] return mask elif len(route_in_idxs) == 2: # return np.concatenate([CBLidx2mask[in_idx - 1] for in_idx in route_in_idxs]) if module_defs[route_in_idxs[0]]['type'] == 'upsample': mask1 = CBLidx2mask[route_in_idxs[0] - 1] elif module_defs[route_in_idxs[0]]['type'] == 'convolutional': mask1 = CBLidx2mask[route_in_idxs[0]] if module_defs[route_in_idxs[1]]['type'] == 'convolutional': mask2 = CBLidx2mask[route_in_idxs[1]] else: mask2 = CBLidx2mask[route_in_idxs[1] - 1] return np.concatenate([mask1, mask2]) elif len(route_in_idxs) == 4: #spp结构中最后一个route mask = CBLidx2mask[route_in_idxs[-1]] return np.concatenate([mask, mask, mask, mask]) else: print("Something wrong with route module!") raise Exception elif module_defs[idx - 1]['type'] == 'maxpool': #tiny if module_defs[idx - 2]['type'] == 'route': #v4 tiny return get_input_mask(module_defs, idx - 1, CBLidx2mask) else: return CBLidx2mask[idx - 2] #v3 tiny def init_weights_from_loose_model(compact_model, loose_model, CBL_idx, Conv_idx, CBLidx2mask): for idx in CBL_idx: compact_CBL = compact_model.module_list[idx] loose_CBL = loose_model.module_list[idx] out_channel_idx = np.argwhere(CBLidx2mask[idx])[:, 0].tolist() compact_bn, loose_bn = compact_CBL[1], loose_CBL[1] compact_bn.weight.data = loose_bn.weight.data[out_channel_idx].clone() compact_bn.bias.data = loose_bn.bias.data[out_channel_idx].clone() compact_bn.running_mean.data = loose_bn.running_mean.data[out_channel_idx].clone() compact_bn.running_var.data = loose_bn.running_var.data[out_channel_idx].clone() input_mask = get_input_mask(loose_model.module_defs, idx, CBLidx2mask) in_channel_idx = np.argwhere(input_mask)[:, 0].tolist() compact_conv, loose_conv = compact_CBL[0], loose_CBL[0] tmp = loose_conv.weight.data[:, in_channel_idx, :, :].clone() compact_conv.weight.data = tmp[out_channel_idx, :, :, :].clone() for idx in Conv_idx: compact_conv = compact_model.module_list[idx][0] loose_conv = loose_model.module_list[idx][0] input_mask = get_input_mask(loose_model.module_defs, idx, CBLidx2mask) in_channel_idx = np.argwhere(input_mask)[:, 0].tolist() compact_conv.weight.data = loose_conv.weight.data[:, in_channel_idx, :, :].clone() compact_conv.bias.data = loose_conv.bias.data.clone() def prune_model_keep_size(model, prune_idx, CBL_idx, CBLidx2mask): pruned_model = deepcopy(model) for idx in prune_idx: mask = torch.from_numpy(CBLidx2mask[idx]).cuda() bn_module = pruned_model.module_list[idx][1] bn_module.weight.data.mul_(mask) activation = F.leaky_relu((1 - mask) * bn_module.bias.data, 0.1) # 两个上采样层前的卷积层 next_idx_list = [idx + 1] if idx == 79: next_idx_list.append(84) elif idx == 91: next_idx_list.append(96) for next_idx in next_idx_list: next_conv = pruned_model.module_list[next_idx][0] conv_sum = next_conv.weight.data.sum(dim=(2, 3)) offset = conv_sum.matmul(activation.reshape(-1, 1)).reshape(-1) if next_idx in CBL_idx: next_bn = pruned_model.module_list[next_idx][1] next_bn.running_mean.data.sub_(offset) else: next_conv.bias.data.add_(offset) bn_module.bias.data.mul_(mask) return pruned_model def obtain_bn_mask(bn_module, thre): thre = thre.cuda() mask = bn_module.weight.data.abs().ge(thre).float() return mask def update_activation(i, pruned_model, activation, CBL_idx): next_idx = i + 1 if pruned_model.module_defs[next_idx]['type'] == 'convolutional': next_conv = pruned_model.module_list[next_idx][0] conv_sum = next_conv.weight.data.sum(dim=(2, 3)) offset = conv_sum.matmul(activation.reshape(-1, 1)).reshape(-1) if next_idx in CBL_idx: next_bn = pruned_model.module_list[next_idx][1] next_bn.running_mean.data.sub_(offset) else: next_conv.bias.data.add_(offset) def prune_model_keep_size2(model, prune_idx, CBL_idx, CBLidx2mask): pruned_model = deepcopy(model) activations = [] for i, model_def in enumerate(model.module_defs): if model_def['type'] == 'convolutional': activation = torch.zeros(int(model_def['filters'])).cuda() if i in prune_idx: mask = torch.from_numpy(CBLidx2mask[i]).cuda() bn_module = pruned_model.module_list[i][1] bn_module.weight.data.mul_(mask) if model_def['activation'] == 'leaky': activation = F.leaky_relu((1 - mask) * bn_module.bias.data, 0.1) elif model_def['activation'] == 'mish': activation = (1 - mask) * bn_module.bias.data.mul(F.softplus(bn_module.bias.data).tanh()) update_activation(i, pruned_model, activation, CBL_idx) bn_module.bias.data.mul_(mask) activations.append(activation) elif model_def['type'] == 'shortcut': actv1 = activations[i - 1] from_layer = int(model_def['from']) actv2 = activations[i + from_layer] activation = actv1 + actv2 update_activation(i, pruned_model, activation, CBL_idx) activations.append(activation) elif model_def['type'] == 'route': #spp不参与剪枝,其中的route不用更新,仅占位 from_layers = [int(s) for s in model_def['layers'].split(',')] activation = None if len(from_layers) == 1: activation = activations[i + from_layers[0] if from_layers[0] < 0 else from_layers[0]] if 'groups' in model_def: activation = activation[(activation.shape[0]//2):] update_activation(i, pruned_model, activation, CBL_idx) elif len(from_layers) == 2: actv1 = activations[i + from_layers[0]] actv2 = activations[i + from_layers[1] if from_layers[1] < 0 else from_layers[1]] activation = torch.cat((actv1, actv2)) update_activation(i, pruned_model, activation, CBL_idx) activations.append(activation) elif model_def['type'] == 'upsample': # activation = torch.zeros(int(model.module_defs[i - 1]['filters'])).cuda() activations.append(activations[i-1]) elif model_def['type'] == 'yolo': activations.append(None) elif model_def['type'] == 'maxpool': #区分spp和tiny if model.module_defs[i + 1]['type'] == 'route': activations.append(None) else: activation = activations[i-1] update_activation(i, pruned_model, activation, CBL_idx) activations.append(activation) return pruned_model def get_mask(model, prune_idx, shortcut_idx): sort_prune_idx=[idx for idx in prune_idx if idx not in shortcut_idx] bn_weights = gather_bn_weights(model.module_list, sort_prune_idx) sorted_bn = torch.sort(bn_weights)[0] highest_thre = [] for idx in sort_prune_idx: #.item()可以得到张量里的元素值 highest_thre.append(model.module_list[idx][1].weight.data.abs().max().item()) highest_thre = min(highest_thre) filters_mask = [] idx_new=dict() #CBL_idx存储的是所有带BN的卷积层(YOLO层的前一层卷积层是不带BN的) for idx in prune_idx: bn_module = model.module_list[idx][1] if idx not in shortcut_idx: mask = obtain_bn_mask(bn_module, torch.tensor(highest_thre)).cpu() idx_new[idx]=mask else: mask=idx_new[shortcut_idx[idx]] idx_new[idx]=mask filters_mask.append(mask.clone()) prune2mask = {idx: mask for idx, mask in zip(prune_idx, filters_mask)} return prune2mask def get_mask2(model, prune_idx, percent): bn_weights = gather_bn_weights(model.module_list, prune_idx) sorted_bn = torch.sort(bn_weights)[0] thre_index = int(len(sorted_bn) * percent) thre = sorted_bn[thre_index] filters_mask = [] for idx in prune_idx: bn_module = model.module_list[idx][1] mask = obtain_bn_mask(bn_module, thre).cpu() filters_mask.append(mask.clone()) prune2mask = {idx: mask for idx, mask in zip(prune_idx, filters_mask)} return prune2mask def merge_mask(model, CBLidx2mask, CBLidx2filters): for i in range(len(model.module_defs) - 1, -1, -1): mtype = model.module_defs[i]['type'] if mtype == 'shortcut': if model.module_defs[i]['is_access']: continue Merge_masks = [] layer_i = i while mtype == 'shortcut': model.module_defs[layer_i]['is_access'] = True if model.module_defs[layer_i-1]['type'] == 'convolutional': bn = int(model.module_defs[layer_i-1]['batch_normalize']) if bn: Merge_masks.append(CBLidx2mask[layer_i-1].unsqueeze(0)) layer_i = int(model.module_defs[layer_i]['from'])+layer_i mtype = model.module_defs[layer_i]['type'] if mtype == 'convolutional': bn = int(model.module_defs[layer_i]['batch_normalize']) if bn: Merge_masks.append(CBLidx2mask[layer_i].unsqueeze(0)) if len(Merge_masks) > 1: Merge_masks = torch.cat(Merge_masks, 0) merge_mask = (torch.sum(Merge_masks, dim=0) > 0).float() else: merge_mask = Merge_masks[0].float() layer_i = i mtype = 'shortcut' while mtype == 'shortcut': if model.module_defs[layer_i-1]['type'] == 'convolutional': bn = int(model.module_defs[layer_i-1]['batch_normalize']) if bn: CBLidx2mask[layer_i-1] = merge_mask CBLidx2filters[layer_i-1] = int(torch.sum(merge_mask).item()) layer_i = int(model.module_defs[layer_i]['from'])+layer_i mtype = model.module_defs[layer_i]['type'] if mtype == 'convolutional': bn = int(model.module_defs[layer_i]['batch_normalize']) if bn: CBLidx2mask[layer_i] = merge_mask CBLidx2filters[layer_i] = int(torch.sum(merge_mask).item())
import torch from terminaltables import AsciiTable from copy import deepcopy import numpy as np import torch.nn.functional as F def get_sr_flag(epoch, sr): # return epoch >= 5 and sr return sr def parse_module_defs(module_defs): CBL_idx = [] Conv_idx = [] ignore_idx = set() for i, module_def in enumerate(module_defs): if module_def['type'] == 'convolutional': if module_def['batch_normalize'] == '1': CBL_idx.append(i) else: Conv_idx.append(i) if module_defs[i+1]['type'] == 'maxpool' and module_defs[i+2]['type'] == 'route': #spp前一个CBL不剪 区分tiny ignore_idx.add(i) if module_defs[i+1]['type'] == 'route' and 'groups' in module_defs[i+1]: ignore_idx.add(i) elif module_def['type'] == 'shortcut': ignore_idx.add(i-1) identity_idx = (i + int(module_def['from'])) if module_defs[identity_idx]['type'] == 'convolutional': ignore_idx.add(identity_idx) elif module_defs[identity_idx]['type'] == 'shortcut': ignore_idx.add(identity_idx - 1) elif module_def['type'] == 'upsample': #上采样层前的卷积层不裁剪 ignore_idx.add(i - 1) prune_idx = [idx for idx in CBL_idx if idx not in ignore_idx] return CBL_idx, Conv_idx, prune_idx def parse_module_defs2(module_defs): CBL_idx = [] Conv_idx = [] shortcut_idx=dict() shortcut_all=set() ignore_idx = set() for i, module_def in enumerate(module_defs): if module_def['type'] == 'convolutional': if module_def['batch_normalize'] == '1': CBL_idx.append(i) else: Conv_idx.append(i) if module_defs[i+1]['type'] == 'maxpool' and module_defs[i+2]['type'] == 'route': #spp前一个CBL不剪 区分spp和tiny ignore_idx.add(i) if module_defs[i+1]['type'] == 'route' and 'groups' in module_defs[i+1]: ignore_idx.add(i) elif module_def['type'] == 'upsample': #上采样层前的卷积层不裁剪 ignore_idx.add(i - 1) elif module_def['type'] == 'shortcut': identity_idx = (i + int(module_def['from'])) if module_defs[identity_idx]['type'] == 'convolutional': #ignore_idx.add(identity_idx) shortcut_idx[i-1]=identity_idx shortcut_all.add(identity_idx) elif module_defs[identity_idx]['type'] == 'shortcut': #ignore_idx.add(identity_idx - 1) shortcut_idx[i-1]=identity_idx-1 shortcut_all.add(identity_idx-1) shortcut_all.add(i-1) prune_idx = [idx for idx in CBL_idx if idx not in ignore_idx] return CBL_idx, Conv_idx, prune_idx,shortcut_idx,shortcut_all def parse_module_defs4(module_defs): CBL_idx = [] Conv_idx = [] shortcut_idx= [] for i, module_def in enumerate(module_defs): if module_def['type'] == 'convolutional': if module_def['batch_normalize'] == '1': CBL_idx.append(i) else: Conv_idx.append(i) elif module_def['type'] == 'shortcut': shortcut_idx.append(i-1) return CBL_idx, Conv_idx, shortcut_idx def gather_bn_weights(module_list, prune_idx): size_list = [module_list[idx][1].weight.data.shape[0] for idx in prune_idx] bn_weights = torch.zeros(sum(size_list)) index = 0 for idx, size in zip(prune_idx, size_list): bn_weights[index:(index + size)] = module_list[idx][1].weight.data.abs().clone() index += size return bn_weights def write_cfg(cfg_file, module_defs): with open(cfg_file, 'w') as f: for module_def in module_defs: f.write(f"[{module_def['type']}]\n") for key, value in module_def.items(): if key == 'batch_normalize' and value == 0: continue if key != 'type': if key == 'anchors': value = ', '.join(','.join(str(int(i)) for i in j) for j in value) f.write(f"{key}={value}\n") f.write("\n") return cfg_file class BNOptimizer(): @staticmethod def updateBN(sr_flag, module_list, s, prune_idx, epoch, idx2mask=None, opt=None): if sr_flag: # s = s if epoch <= opt.epochs * 0.5 else s * 0.01 for idx in prune_idx: # Squential(Conv, BN, Lrelu) bn_module = module_list[idx][1] bn_module.weight.grad.data.add_(s * torch.sign(bn_module.weight.data)) # L1 if idx2mask: for idx in idx2mask: bn_module = module_list[idx][1] #bn_module.weight.grad.data.add_(0.5 * s * torch.sign(bn_module.weight.data) * (1 - idx2mask[idx].cuda())) bn_module.weight.grad.data.sub_(0.99 * s * torch.sign(bn_module.weight.data) * idx2mask[idx].cuda()) def obtain_quantiles(bn_weights, num_quantile=5): sorted_bn_weights, i = torch.sort(bn_weights) total = sorted_bn_weights.shape[0] quantiles = sorted_bn_weights.tolist()[-1::-total//num_quantile][::-1] print("\nBN weights quantile:") quantile_table = [ [f'{i}/{num_quantile}' for i in range(1, num_quantile+1)], ["%.3f" % quantile for quantile in quantiles] ] print(AsciiTable(quantile_table).table) return quantiles def get_input_mask(module_defs, idx, CBLidx2mask): if idx == 0: return np.ones(3) if module_defs[idx - 1]['type'] == 'convolutional': return CBLidx2mask[idx - 1] elif module_defs[idx - 1]['type'] == 'shortcut': return CBLidx2mask[idx - 2] elif module_defs[idx - 1]['type'] == 'route': route_in_idxs = [] for layer_i in module_defs[idx - 1]['layers'].split(","): if int(layer_i) < 0: route_in_idxs.append(idx - 1 + int(layer_i)) else: route_in_idxs.append(int(layer_i)) if len(route_in_idxs) == 1: mask = CBLidx2mask[route_in_idxs[0]] if 'groups' in module_defs[idx - 1]: return mask[(mask.shape[0]//2):] return mask elif len(route_in_idxs) == 2: # return np.concatenate([CBLidx2mask[in_idx - 1] for in_idx in route_in_idxs]) if module_defs[route_in_idxs[0]]['type'] == 'upsample': mask1 = CBLidx2mask[route_in_idxs[0] - 1] elif module_defs[route_in_idxs[0]]['type'] == 'convolutional': mask1 = CBLidx2mask[route_in_idxs[0]] if module_defs[route_in_idxs[1]]['type'] == 'convolutional': mask2 = CBLidx2mask[route_in_idxs[1]] else: mask2 = CBLidx2mask[route_in_idxs[1] - 1] return np.concatenate([mask1, mask2]) elif len(route_in_idxs) == 4: #spp结构中最后一个route mask = CBLidx2mask[route_in_idxs[-1]] return np.concatenate([mask, mask, mask, mask]) else: print("Something wrong with route module!") raise Exception elif module_defs[idx - 1]['type'] == 'maxpool': #tiny if module_defs[idx - 2]['type'] == 'route': #v4 tiny return get_input_mask(module_defs, idx - 1, CBLidx2mask) else: return CBLidx2mask[idx - 2] #v3 tiny def init_weights_from_loose_model(compact_model, loose_model, CBL_idx, Conv_idx, CBLidx2mask): for idx in CBL_idx: compact_CBL = compact_model.module_list[idx] loose_CBL = loose_model.module_list[idx] out_channel_idx = np.argwhere(CBLidx2mask[idx])[:, 0].tolist() compact_bn, loose_bn = compact_CBL[1], loose_CBL[1] compact_bn.weight.data = loose_bn.weight.data[out_channel_idx].clone() compact_bn.bias.data = loose_bn.bias.data[out_channel_idx].clone() compact_bn.running_mean.data = loose_bn.running_mean.data[out_channel_idx].clone() compact_bn.running_var.data = loose_bn.running_var.data[out_channel_idx].clone() input_mask = get_input_mask(loose_model.module_defs, idx, CBLidx2mask) in_channel_idx = np.argwhere(input_mask)[:, 0].tolist() compact_conv, loose_conv = compact_CBL[0], loose_CBL[0] tmp = loose_conv.weight.data[:, in_channel_idx, :, :].clone() compact_conv.weight.data = tmp[out_channel_idx, :, :, :].clone() for idx in Conv_idx: compact_conv = compact_model.module_list[idx][0] loose_conv = loose_model.module_list[idx][0] input_mask = get_input_mask(loose_model.module_defs, idx, CBLidx2mask) in_channel_idx = np.argwhere(input_mask)[:, 0].tolist() compact_conv.weight.data = loose_conv.weight.data[:, in_channel_idx, :, :].clone() compact_conv.bias.data = loose_conv.bias.data.clone() def prune_model_keep_size(model, prune_idx, CBL_idx, CBLidx2mask): pruned_model = deepcopy(model) for idx in prune_idx: mask = torch.from_numpy(CBLidx2mask[idx]).cuda() bn_module = pruned_model.module_list[idx][1] bn_module.weight.data.mul_(mask) activation = F.leaky_relu((1 - mask) * bn_module.bias.data, 0.1) # 两个上采样层前的卷积层 next_idx_list = [idx + 1] if idx == 79: next_idx_list.append(84) elif idx == 91: next_idx_list.append(96) for next_idx in next_idx_list: next_conv = pruned_model.module_list[next_idx][0] conv_sum = next_conv.weight.data.sum(dim=(2, 3)) offset = conv_sum.matmul(activation.reshape(-1, 1)).reshape(-1) if next_idx in CBL_idx: next_bn = pruned_model.module_list[next_idx][1] next_bn.running_mean.data.sub_(offset) else: next_conv.bias.data.add_(offset) bn_module.bias.data.mul_(mask) return pruned_model def obtain_bn_mask(bn_module, thre): thre = thre.cuda() mask = bn_module.weight.data.abs().ge(thre).float() return mask def update_activation(i, pruned_model, activation, CBL_idx): next_idx = i + 1 if pruned_model.module_defs[next_idx]['type'] == 'convolutional': next_conv = pruned_model.module_list[next_idx][0] conv_sum = next_conv.weight.data.sum(dim=(2, 3)) offset = conv_sum.matmul(activation.reshape(-1, 1)).reshape(-1) if next_idx in CBL_idx: next_bn = pruned_model.module_list[next_idx][1] next_bn.running_mean.data.sub_(offset) else: next_conv.bias.data.add_(offset) def prune_model_keep_size2(model, prune_idx, CBL_idx, CBLidx2mask): pruned_model = deepcopy(model) activations = [] for i, model_def in enumerate(model.module_defs): if model_def['type'] == 'convolutional': activation = torch.zeros(int(model_def['filters'])).cuda() if i in prune_idx: mask = torch.from_numpy(CBLidx2mask[i]).cuda() bn_module = pruned_model.module_list[i][1] bn_module.weight.data.mul_(mask) if model_def['activation'] == 'leaky': activation = F.leaky_relu((1 - mask) * bn_module.bias.data, 0.1) elif model_def['activation'] == 'mish': activation = (1 - mask) * bn_module.bias.data.mul(F.softplus(bn_module.bias.data).tanh()) update_activation(i, pruned_model, activation, CBL_idx) bn_module.bias.data.mul_(mask) activations.append(activation) elif model_def['type'] == 'shortcut': actv1 = activations[i - 1] from_layer = int(model_def['from']) actv2 = activations[i + from_layer] activation = actv1 + actv2 update_activation(i, pruned_model, activation, CBL_idx) activations.append(activation) elif model_def['type'] == 'route': #spp不参与剪枝,其中的route不用更新,仅占位 from_layers = [int(s) for s in model_def['layers'].split(',')] activation = None if len(from_layers) == 1: activation = activations[i + from_layers[0] if from_layers[0] < 0 else from_layers[0]] if 'groups' in model_def: activation = activation[(activation.shape[0]//2):] update_activation(i, pruned_model, activation, CBL_idx) elif len(from_layers) == 2: actv1 = activations[i + from_layers[0]] actv2 = activations[i + from_layers[1] if from_layers[1] < 0 else from_layers[1]] activation = torch.cat((actv1, actv2)) update_activation(i, pruned_model, activation, CBL_idx) activations.append(activation) elif model_def['type'] == 'upsample': # activation = torch.zeros(int(model.module_defs[i - 1]['filters'])).cuda() activations.append(activations[i-1]) elif model_def['type'] == 'yolo': activations.append(None) elif model_def['type'] == 'maxpool': #区分spp和tiny if model.module_defs[i + 1]['type'] == 'route': activations.append(None) else: activation = activations[i-1] update_activation(i, pruned_model, activation, CBL_idx) activations.append(activation) return pruned_model def get_mask(model, prune_idx, shortcut_idx): sort_prune_idx=[idx for idx in prune_idx if idx not in shortcut_idx] bn_weights = gather_bn_weights(model.module_list, sort_prune_idx) sorted_bn = torch.sort(bn_weights)[0] highest_thre = [] for idx in sort_prune_idx: #.item()可以得到张量里的元素值 highest_thre.append(model.module_list[idx][1].weight.data.abs().max().item()) highest_thre = min(highest_thre) filters_mask = [] idx_new=dict() #CBL_idx存储的是所有带BN的卷积层(YOLO层的前一层卷积层是不带BN的) for idx in prune_idx: bn_module = model.module_list[idx][1] if idx not in shortcut_idx: mask = obtain_bn_mask(bn_module, torch.tensor(highest_thre)).cpu() idx_new[idx]=mask else: mask=idx_new[shortcut_idx[idx]] idx_new[idx]=mask filters_mask.append(mask.clone()) prune2mask = {idx: mask for idx, mask in zip(prune_idx, filters_mask)} return prune2mask def get_mask2(model, prune_idx, percent): bn_weights = gather_bn_weights(model.module_list, prune_idx) sorted_bn = torch.sort(bn_weights)[0] thre_index = int(len(sorted_bn) * percent) thre = sorted_bn[thre_index] filters_mask = [] for idx in prune_idx: bn_module = model.module_list[idx][1] mask = obtain_bn_mask(bn_module, thre).cpu() filters_mask.append(mask.clone()) prune2mask = {idx: mask for idx, mask in zip(prune_idx, filters_mask)} return prune2mask def merge_mask(model, CBLidx2mask, CBLidx2filters): for i in range(len(model.module_defs) - 1, -1, -1): mtype = model.module_defs[i]['type'] if mtype == 'shortcut': if model.module_defs[i]['is_access']: continue Merge_masks = [] layer_i = i while mtype == 'shortcut': model.module_defs[layer_i]['is_access'] = True if model.module_defs[layer_i-1]['type'] == 'convolutional': bn = int(model.module_defs[layer_i-1]['batch_normalize']) if bn: Merge_masks.append(CBLidx2mask[layer_i-1].unsqueeze(0)) layer_i = int(model.module_defs[layer_i]['from'])+layer_i mtype = model.module_defs[layer_i]['type'] if mtype == 'convolutional': bn = int(model.module_defs[layer_i]['batch_normalize']) if bn: Merge_masks.append(CBLidx2mask[layer_i].unsqueeze(0)) if len(Merge_masks) > 1: Merge_masks = torch.cat(Merge_masks, 0) merge_mask = (torch.sum(Merge_masks, dim=0) > 0).float() else: merge_mask = Merge_masks[0].float() layer_i = i mtype = 'shortcut' while mtype == 'shortcut': if model.module_defs[layer_i-1]['type'] == 'convolutional': bn = int(model.module_defs[layer_i-1]['batch_normalize']) if bn: CBLidx2mask[layer_i-1] = merge_mask CBLidx2filters[layer_i-1] = int(torch.sum(merge_mask).item()) layer_i = int(model.module_defs[layer_i]['from'])+layer_i mtype = model.module_defs[layer_i]['type'] if mtype == 'convolutional': bn = int(model.module_defs[layer_i]['batch_normalize']) if bn: CBLidx2mask[layer_i] = merge_mask CBLidx2filters[layer_i] = int(torch.sum(merge_mask).item())
import json from collections import defaultdict from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponseRedirect from django.urls import reverse from django.utils.http import urlencode from django.views.generic import FormView, TemplateView, CreateView from database.models.schedule_models import Section, Timeblock, SectionNote from database.models.structural_models import Preference from schedule.forms import CheckScheduleForm, ScheduleSectionEditForm, SectionNoteForm from schedule.functions import check_section_timeblock_preference, check_user_timeblock_preference, \ check_user_course_preference, check_user_section_preference class ScheduleRedirectView(LoginRequiredMixin, FormView): form_class = CheckScheduleForm def form_valid(self, form): return HttpResponseRedirect( reverse( 'schedule:schedule-table-view', kwargs={ 'schedule_id': form.cleaned_data['schedule'].id, 'preference_set_id': form.cleaned_data['preference_set'].id } ) ) class CheckScheduleView(LoginRequiredMixin, TemplateView): template_name = 'pages/check_schedule.html' def get_context_data(self, **kwargs): context_data = super().get_context_data(**kwargs) context_data.update({ 'check_schedule_form': CheckScheduleForm() }) return context_data class ScheduleView(LoginRequiredMixin, TemplateView): template_name = "pages/schedule_table_view.html" def get_context_data(self, **kwargs): context_data = super().get_context_data(**kwargs) sections = Section.objects.filter(schedule_id=kwargs.get('schedule_id')) preferences = Preference.objects.filter(sets__set__id=kwargs.get('preference_set_id')) course_course_preference = [] section_timeblock_preference = [] user_course_preference = [] user_section_preference = [] user_timeblock_preference = [] for preference in preferences: if preference.object_1_content_type.model == 'course': if preference.object_2_content_type.model == 'course': course_course_preference.append(preference) if preference.object_1_content_type.model == 'section': if preference.object_2_content_type.model == 'timeblock': section_timeblock_preference.append(preference) elif preference.object_1_content_type.model == 'baseuser': if preference.object_2_content_type.model == 'course': user_course_preference.append(preference) elif preference.object_2_content_type.model == 'timeblock': user_timeblock_preference.append(preference) elif preference.object_2_content_type.model == 'section': user_section_preference.append(preference) sections_dict = {} sections_without_timeblock = [] section_time_block_dict = defaultdict(list) for section in sections: if section.timeblock: section_time_block_dict[section.timeblock.id].append(section) else: sections_without_timeblock.append(section) sections_dict[section.id] = { 'section': section, 'color': '', 'positive_points': [], 'negative_points': [] } i = 0 new_list = [] while i < len(sections_without_timeblock): new_list.append(sections_without_timeblock[i:i + 5]) i += 5 sections_without_timeblock = new_list for idx, section1 in enumerate(sections): for section2 in sections[idx:]: for preference in course_course_preference: preference_courses = [preference.object_1, preference.object_2] section_courses = [section1.course, section2.course] if preference_courses == section_courses: color1 = sections_dict[section1.id].get('color') color2 = sections_dict[section2.id].get('color') if preference.weight: if section1.timeblock == section2.timeblock: # If two courses with a positive preference are at the same time, highlight both green. if color1 != 'red': sections_dict[section1.id]['color'] = 'green' if color2 != 'red': sections_dict[section2.id]['color'] = 'green' sections_dict[section1.id]['positive_points'].append( 'courses with a positive preference are at the same time' ) sections_dict[section2.id]['positive_points'].append( 'courses with a positive preference are at the same time' ) else: # If two courses with a positive preference are at different times, highlight both red. sections_dict[section1.id]['color'] = 'red' sections_dict[section1.id]['negative_points'].append( 'courses with a positive preference are at different times' ) sections_dict[section2.id]['color'] = 'red' sections_dict[section2.id]['negative_points'].append( 'courses with a positive preference are at different times' ) else: # If two courses with a negative preference are at the same time, highlight both red. if section1.timeblock == section2.timeblock: sections_dict[section1.id]['color'] = 'red' sections_dict[section1.id]['negative_points'].append( 'courses with a negative preference are at the same time' ) sections_dict[section2.id]['color'] = 'red' sections_dict[section2.id]['negative_points'].append( 'courses with a negative preference are at the same time' ) if section1.primary_instructor: check_user_course_preference(section1, user_course_preference, sections_dict) check_user_section_preference(section1, user_section_preference, sections_dict) if section1.timeblock: check_section_timeblock_preference(section1, section_timeblock_preference, sections_dict) if section1.timeblock and section1.primary_instructor: check_user_timeblock_preference(section1, user_timeblock_preference, sections_dict) timeblock_day_dict = defaultdict(dict) time_blocks = Timeblock.objects.all() for time_block in time_blocks: timeblock_day_dict[time_block.id] = self.generate_day_dict(section_time_block_dict[time_block.id]) context_data.update({ 'time_blocks': time_blocks, 'timeblock_day_dict': timeblock_day_dict, 'day_list': ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'], 'sections': sections_dict, 'schedule_id': kwargs.get('schedule_id'), 'preference_set_id': kwargs.get('preference_set_id'), 'sections_queryset': sections, 'sections_without_timeblock': sections_without_timeblock }) return context_data @classmethod def generate_day_dict(cls, sections): day_dict = defaultdict(list) for section in sections: if section.timeblock.weekdays.monday: day_dict['monday'].append(section) if section.timeblock.weekdays.tuesday: day_dict['tuesday'].append(section) if section.timeblock.weekdays.wednesday: day_dict['wednesday'].append(section) if section.timeblock.weekdays.thursday: day_dict['thursday'].append(section) if section.timeblock.weekdays.friday: day_dict['friday'].append(section) return day_dict class ScheduleSectionEditView(LoginRequiredMixin, FormView): template_name = 'pages/section_edit_form.html' def get_form(self, form_class=None): return ScheduleSectionEditForm( instance=Section.objects.get(id=self.kwargs['section_id']), **self.get_form_kwargs() ) def form_valid(self, form): form.save() return HttpResponseRedirect( reverse( 'schedule:schedule-table-view', kwargs={ 'schedule_id': self.kwargs['schedule_id'], 'preference_set_id': self.kwargs['preference_set_id'] } ) + f'?showsections={self.request.GET.get('showsections', '')}' ) class SectionNoteListView(LoginRequiredMixin, TemplateView): template_name = 'components/section_notes.html' def get_context_data(self, **kwargs): context_data = super().get_context_data(**kwargs) context_data.update({ 'notes': SectionNote.objects.filter( section__id=self.kwargs['section_id'], color='#' + self.kwargs['color'] ), 'color_type': '#' + self.kwargs['color'] }) return context_data class SectionNoteFormView(LoginRequiredMixin, FormView): template_name = 'pages/section_edit_form.html' form_class = SectionNoteForm def get_form_kwargs(self): kwargs = { 'initial': self.get_initial(), 'prefix': self.get_prefix(), } if self.request.method in ('POST', 'PUT'): kwargs.update({ 'data': json.loads(self.request.body), 'files': self.request.FILES, }) return kwargs def form_valid(self, form): note = form.save(commit=False) note.section = Section.objects.get(id=self.kwargs['section_id']) note.save() return HttpResponseRedirect(reverse( 'schedule:section-notes-list', kwargs={ 'section_id': self.kwargs['section_id'], 'color': form.cleaned_data['color'][1:] } ))
import json from collections import defaultdict from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponseRedirect from django.urls import reverse from django.utils.http import urlencode from django.views.generic import FormView, TemplateView, CreateView from database.models.schedule_models import Section, Timeblock, SectionNote from database.models.structural_models import Preference from schedule.forms import CheckScheduleForm, ScheduleSectionEditForm, SectionNoteForm from schedule.functions import check_section_timeblock_preference, check_user_timeblock_preference, \ check_user_course_preference, check_user_section_preference class ScheduleRedirectView(LoginRequiredMixin, FormView): form_class = CheckScheduleForm def form_valid(self, form): return HttpResponseRedirect( reverse( 'schedule:schedule-table-view', kwargs={ 'schedule_id': form.cleaned_data['schedule'].id, 'preference_set_id': form.cleaned_data['preference_set'].id } ) ) class CheckScheduleView(LoginRequiredMixin, TemplateView): template_name = 'pages/check_schedule.html' def get_context_data(self, **kwargs): context_data = super().get_context_data(**kwargs) context_data.update({ 'check_schedule_form': CheckScheduleForm() }) return context_data class ScheduleView(LoginRequiredMixin, TemplateView): template_name = "pages/schedule_table_view.html" def get_context_data(self, **kwargs): context_data = super().get_context_data(**kwargs) sections = Section.objects.filter(schedule_id=kwargs.get('schedule_id')) preferences = Preference.objects.filter(sets__set__id=kwargs.get('preference_set_id')) course_course_preference = [] section_timeblock_preference = [] user_course_preference = [] user_section_preference = [] user_timeblock_preference = [] for preference in preferences: if preference.object_1_content_type.model == 'course': if preference.object_2_content_type.model == 'course': course_course_preference.append(preference) if preference.object_1_content_type.model == 'section': if preference.object_2_content_type.model == 'timeblock': section_timeblock_preference.append(preference) elif preference.object_1_content_type.model == 'baseuser': if preference.object_2_content_type.model == 'course': user_course_preference.append(preference) elif preference.object_2_content_type.model == 'timeblock': user_timeblock_preference.append(preference) elif preference.object_2_content_type.model == 'section': user_section_preference.append(preference) sections_dict = {} sections_without_timeblock = [] section_time_block_dict = defaultdict(list) for section in sections: if section.timeblock: section_time_block_dict[section.timeblock.id].append(section) else: sections_without_timeblock.append(section) sections_dict[section.id] = { 'section': section, 'color': '', 'positive_points': [], 'negative_points': [] } i = 0 new_list = [] while i < len(sections_without_timeblock): new_list.append(sections_without_timeblock[i:i + 5]) i += 5 sections_without_timeblock = new_list for idx, section1 in enumerate(sections): for section2 in sections[idx:]: for preference in course_course_preference: preference_courses = [preference.object_1, preference.object_2] section_courses = [section1.course, section2.course] if preference_courses == section_courses: color1 = sections_dict[section1.id].get('color') color2 = sections_dict[section2.id].get('color') if preference.weight: if section1.timeblock == section2.timeblock: # If two courses with a positive preference are at the same time, highlight both green. if color1 != 'red': sections_dict[section1.id]['color'] = 'green' if color2 != 'red': sections_dict[section2.id]['color'] = 'green' sections_dict[section1.id]['positive_points'].append( 'courses with a positive preference are at the same time' ) sections_dict[section2.id]['positive_points'].append( 'courses with a positive preference are at the same time' ) else: # If two courses with a positive preference are at different times, highlight both red. sections_dict[section1.id]['color'] = 'red' sections_dict[section1.id]['negative_points'].append( 'courses with a positive preference are at different times' ) sections_dict[section2.id]['color'] = 'red' sections_dict[section2.id]['negative_points'].append( 'courses with a positive preference are at different times' ) else: # If two courses with a negative preference are at the same time, highlight both red. if section1.timeblock == section2.timeblock: sections_dict[section1.id]['color'] = 'red' sections_dict[section1.id]['negative_points'].append( 'courses with a negative preference are at the same time' ) sections_dict[section2.id]['color'] = 'red' sections_dict[section2.id]['negative_points'].append( 'courses with a negative preference are at the same time' ) if section1.primary_instructor: check_user_course_preference(section1, user_course_preference, sections_dict) check_user_section_preference(section1, user_section_preference, sections_dict) if section1.timeblock: check_section_timeblock_preference(section1, section_timeblock_preference, sections_dict) if section1.timeblock and section1.primary_instructor: check_user_timeblock_preference(section1, user_timeblock_preference, sections_dict) timeblock_day_dict = defaultdict(dict) time_blocks = Timeblock.objects.all() for time_block in time_blocks: timeblock_day_dict[time_block.id] = self.generate_day_dict(section_time_block_dict[time_block.id]) context_data.update({ 'time_blocks': time_blocks, 'timeblock_day_dict': timeblock_day_dict, 'day_list': ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'], 'sections': sections_dict, 'schedule_id': kwargs.get('schedule_id'), 'preference_set_id': kwargs.get('preference_set_id'), 'sections_queryset': sections, 'sections_without_timeblock': sections_without_timeblock }) return context_data @classmethod def generate_day_dict(cls, sections): day_dict = defaultdict(list) for section in sections: if section.timeblock.weekdays.monday: day_dict['monday'].append(section) if section.timeblock.weekdays.tuesday: day_dict['tuesday'].append(section) if section.timeblock.weekdays.wednesday: day_dict['wednesday'].append(section) if section.timeblock.weekdays.thursday: day_dict['thursday'].append(section) if section.timeblock.weekdays.friday: day_dict['friday'].append(section) return day_dict class ScheduleSectionEditView(LoginRequiredMixin, FormView): template_name = 'pages/section_edit_form.html' def get_form(self, form_class=None): return ScheduleSectionEditForm( instance=Section.objects.get(id=self.kwargs['section_id']), **self.get_form_kwargs() ) def form_valid(self, form): form.save() return HttpResponseRedirect( reverse( 'schedule:schedule-table-view', kwargs={ 'schedule_id': self.kwargs['schedule_id'], 'preference_set_id': self.kwargs['preference_set_id'] } ) + f'?showsections={self.request.GET.get("showsections", "")}' ) class SectionNoteListView(LoginRequiredMixin, TemplateView): template_name = 'components/section_notes.html' def get_context_data(self, **kwargs): context_data = super().get_context_data(**kwargs) context_data.update({ 'notes': SectionNote.objects.filter( section__id=self.kwargs['section_id'], color='#' + self.kwargs['color'] ), 'color_type': '#' + self.kwargs['color'] }) return context_data class SectionNoteFormView(LoginRequiredMixin, FormView): template_name = 'pages/section_edit_form.html' form_class = SectionNoteForm def get_form_kwargs(self): kwargs = { 'initial': self.get_initial(), 'prefix': self.get_prefix(), } if self.request.method in ('POST', 'PUT'): kwargs.update({ 'data': json.loads(self.request.body), 'files': self.request.FILES, }) return kwargs def form_valid(self, form): note = form.save(commit=False) note.section = Section.objects.get(id=self.kwargs['section_id']) note.save() return HttpResponseRedirect(reverse( 'schedule:section-notes-list', kwargs={ 'section_id': self.kwargs['section_id'], 'color': form.cleaned_data['color'][1:] } ))
import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm import pandas as pd import clean.clean_03 as southtrac import process.constants as c from matplotlib import gridspec from datetime import datetime import winsound duration = 1000 # milliseconds freq = 440 # Hz import plotly.io as pio import plotly.express as px pio.renderers.default='browser' def input_func(descrpt, psblt): while True: parameter = input(descrpt+':\n').upper() if parameter in psblt: break else: print(f'\nSorry, but {parameter} doesn\'t exist :O') return parameter ins_name = input_func('instrument name', ('MIPAS', 'ACE', 'AMICA')) species = input_func('atmospheric species', ('OCS', 'N2O')) target_button = input_func( 'all parameters(leave empty) or specific parameter (type name)', ('',)+c.ALL_AGEV_SOUTHTRAC+c.ALL_AGEV ) postfix = 'tagged' #DJF_LAT30Nplus_THETA430minus_PV2plus JJA_LAT30Sminus_THETA430minus_PV2plus print(f'\npostfix: {postfix}') if species == 'OCS': mrmin, mrmax, mrres = c.OCSMIN_MIPAS if ins_name == 'MIPAS' else c.OCSMIN_ACE, c.OCSMAX, c.OCSRES if species == 'N2O': mrmin, mrmax, mrres = c.N2OMIN_MIPAS if ins_name == 'MIPAS' else c.N2OMIN_ACE, c.N2OMAX, c.N2ORES mrrange = np.arange(mrmin, mrmax+mrres, mrres) dircInput1 = 'C:/Users/Chenxi/OneDrive/phd/age_and_fire/data/04_final/09_ENVISAT_MIPAS_with_AGEparams_final/' \ if ins_name == 'MIPAS' else 'C:/Users/Chenxi/OneDrive/phd/age_and_fire/data/04_final/07_ACE_FTS_with_AGEparams_final/' def group(df): df.index = pd.cut(df.index, vrange) df.rename_axis(target, inplace=True) df[species] = pd.cut(df[species], mrrange) count = df.pivot_table(index=target, columns=species, values='air', aggfunc='count') total_count = count.max(axis=1).rename("total_count") relative_count = count.div(total_count, axis=0) return relative_count, total_count def data2tiles_satellites(): frame_relative_count = [] frame_total_count = [] for i in vrange[:-1]: df = pd.read_pickle(dircInput1 + f'{ins_name}_{species}_{target}_({i}, {i+res}]_{postfix}.pkl') df.dropna(inplace=True) tag = 'stratospheric' df = df.loc[df['air']>=1].copy() if df.empty: print(f'{target}: ({i}, {i+res}] is empty') break relative_count, total_count = group(df) frame_relative_count.append(relative_count) frame_total_count.append(total_count) print(f'@{datetime.now().strftime('%H:%M:%S')} {target}: ({i}, {i+res}]') relative_count = pd.concat(frame_relative_count) total_count = pd.concat(frame_total_count) return relative_count, total_count, tag def data2tiles_southtrac(): tag = 'stratospheric' df = southtrac.read(strat=1).set_index(target).sort_index() relative_count, total_count = group(df) return relative_count, total_count, tag def plot_age(): camps = { 'MIPAS' : 'YlGn', 'ACE': 'OrRd', 'AMICA': 'BuPu' } cmap = cm.get_cmap(camps[ins_name]) barcolor = cmap(0.1) fig = plt.figure(figsize=(10, 50)) font = {'size': 18} plt.rc('font', **font) spec = gridspec.GridSpec(nrows=2, ncols=2,height_ratios=[15, 1],width_ratios=[9, 1])#,height_ratios=[15,1]) width_ratios=[9,1] ax1 = fig.add_subplot(spec[0, 0]) x = np.append([i.left for i in relative_count.columns], relative_count.columns[-1].right) y = np.append([i.left for i in relative_count.index], relative_count.index[-1].right) x, y = np.meshgrid(x, y) main = ax1.pcolormesh (x, y, relative_count, cmap=cmap, shading='flat') ax1.set( xlim=(mrmin, mrmax), ylim=(vmin,vmax), ) ax1.set_xlabel('OCS [ppt]' if species == 'OCS' else 'N2O [ppb]', fontweight='bold') ax1.set_ylabel(f'{target} [month]' if target in ('AGE', 'p50') else f'{target} [%]', fontweight='bold') plt.title(f'{ins_name}_{tag}') ax2 = fig.add_subplot(spec[0, 1], sharey=ax1) x = [i.left for i in total_count.index] y = total_count.values ax2.barh(x, y, res, align='edge', color=barcolor) ax2.set_xscale('log') ax2.set_xlabel('#') ax2.set_xlim(1, 1e3 if ins_name=='AMICA' else 1e8) ax2.axes.yaxis.set_visible(False) ax3 = fig.add_subplot(spec[1, 0]) cbar=plt.colorbar(main, cax=ax3, orientation='horizontal') cbar.set_label(f'% of # relative to the highest bin given {target}') if target_button != '': target = target_button vrange = c.VRANGE_AGE if target == 'AGE' else c.VRANGE vmin, vmax, res = c.VMIN, c.VMAX_AGE if target== 'AGE' else c.VMAX, c.VRES relative_count, total_count, tag = data2tiles_southtrac() if ins_name == 'AMICA' else data2tiles_satellites() plot_age() else: for target in c.ALL_AGEV_SOUTHTRAC if ins_name == 'AMICA' else c.ALL_AGEV: vrange = c.VRANGE_AGE if target == 'AGE' else c.VRANGE vmin, vmax, res = c.VMIN, c.VMAX_AGE if target== 'AGE' else c.VMAX, c.VRES relative_count, total_count, tag = data2tiles_southtrac() if ins_name == 'AMICA' else data2tiles_satellites() plot_age() winsound.Beep(freq, duration)
import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm import pandas as pd import clean.clean_03 as southtrac import process.constants as c from matplotlib import gridspec from datetime import datetime import winsound duration = 1000 # milliseconds freq = 440 # Hz import plotly.io as pio import plotly.express as px pio.renderers.default='browser' def input_func(descrpt, psblt): while True: parameter = input(descrpt+':\n').upper() if parameter in psblt: break else: print(f'\nSorry, but {parameter} doesn\'t exist :O') return parameter ins_name = input_func('instrument name', ('MIPAS', 'ACE', 'AMICA')) species = input_func('atmospheric species', ('OCS', 'N2O')) target_button = input_func( 'all parameters(leave empty) or specific parameter (type name)', ('',)+c.ALL_AGEV_SOUTHTRAC+c.ALL_AGEV ) postfix = 'tagged' #DJF_LAT30Nplus_THETA430minus_PV2plus JJA_LAT30Sminus_THETA430minus_PV2plus print(f'\npostfix: {postfix}') if species == 'OCS': mrmin, mrmax, mrres = c.OCSMIN_MIPAS if ins_name == 'MIPAS' else c.OCSMIN_ACE, c.OCSMAX, c.OCSRES if species == 'N2O': mrmin, mrmax, mrres = c.N2OMIN_MIPAS if ins_name == 'MIPAS' else c.N2OMIN_ACE, c.N2OMAX, c.N2ORES mrrange = np.arange(mrmin, mrmax+mrres, mrres) dircInput1 = 'C:/Users/Chenxi/OneDrive/phd/age_and_fire/data/04_final/09_ENVISAT_MIPAS_with_AGEparams_final/' \ if ins_name == 'MIPAS' else 'C:/Users/Chenxi/OneDrive/phd/age_and_fire/data/04_final/07_ACE_FTS_with_AGEparams_final/' def group(df): df.index = pd.cut(df.index, vrange) df.rename_axis(target, inplace=True) df[species] = pd.cut(df[species], mrrange) count = df.pivot_table(index=target, columns=species, values='air', aggfunc='count') total_count = count.max(axis=1).rename("total_count") relative_count = count.div(total_count, axis=0) return relative_count, total_count def data2tiles_satellites(): frame_relative_count = [] frame_total_count = [] for i in vrange[:-1]: df = pd.read_pickle(dircInput1 + f'{ins_name}_{species}_{target}_({i}, {i+res}]_{postfix}.pkl') df.dropna(inplace=True) tag = 'stratospheric' df = df.loc[df['air']>=1].copy() if df.empty: print(f'{target}: ({i}, {i+res}] is empty') break relative_count, total_count = group(df) frame_relative_count.append(relative_count) frame_total_count.append(total_count) print(f'@{datetime.now().strftime("%H:%M:%S")} {target}: ({i}, {i+res}]') relative_count = pd.concat(frame_relative_count) total_count = pd.concat(frame_total_count) return relative_count, total_count, tag def data2tiles_southtrac(): tag = 'stratospheric' df = southtrac.read(strat=1).set_index(target).sort_index() relative_count, total_count = group(df) return relative_count, total_count, tag def plot_age(): camps = { 'MIPAS' : 'YlGn', 'ACE': 'OrRd', 'AMICA': 'BuPu' } cmap = cm.get_cmap(camps[ins_name]) barcolor = cmap(0.1) fig = plt.figure(figsize=(10, 50)) font = {'size': 18} plt.rc('font', **font) spec = gridspec.GridSpec(nrows=2, ncols=2,height_ratios=[15, 1],width_ratios=[9, 1])#,height_ratios=[15,1]) width_ratios=[9,1] ax1 = fig.add_subplot(spec[0, 0]) x = np.append([i.left for i in relative_count.columns], relative_count.columns[-1].right) y = np.append([i.left for i in relative_count.index], relative_count.index[-1].right) x, y = np.meshgrid(x, y) main = ax1.pcolormesh (x, y, relative_count, cmap=cmap, shading='flat') ax1.set( xlim=(mrmin, mrmax), ylim=(vmin,vmax), ) ax1.set_xlabel('OCS [ppt]' if species == 'OCS' else 'N2O [ppb]', fontweight='bold') ax1.set_ylabel(f'{target} [month]' if target in ('AGE', 'p50') else f'{target} [%]', fontweight='bold') plt.title(f'{ins_name}_{tag}') ax2 = fig.add_subplot(spec[0, 1], sharey=ax1) x = [i.left for i in total_count.index] y = total_count.values ax2.barh(x, y, res, align='edge', color=barcolor) ax2.set_xscale('log') ax2.set_xlabel('#') ax2.set_xlim(1, 1e3 if ins_name=='AMICA' else 1e8) ax2.axes.yaxis.set_visible(False) ax3 = fig.add_subplot(spec[1, 0]) cbar=plt.colorbar(main, cax=ax3, orientation='horizontal') cbar.set_label(f'% of # relative to the highest bin given {target}') if target_button != '': target = target_button vrange = c.VRANGE_AGE if target == 'AGE' else c.VRANGE vmin, vmax, res = c.VMIN, c.VMAX_AGE if target== 'AGE' else c.VMAX, c.VRES relative_count, total_count, tag = data2tiles_southtrac() if ins_name == 'AMICA' else data2tiles_satellites() plot_age() else: for target in c.ALL_AGEV_SOUTHTRAC if ins_name == 'AMICA' else c.ALL_AGEV: vrange = c.VRANGE_AGE if target == 'AGE' else c.VRANGE vmin, vmax, res = c.VMIN, c.VMAX_AGE if target== 'AGE' else c.VMAX, c.VRES relative_count, total_count, tag = data2tiles_southtrac() if ins_name == 'AMICA' else data2tiles_satellites() plot_age() winsound.Beep(freq, duration)
import logging from typing import List, Dict, Text, Optional, Any, Set, TYPE_CHECKING, Union from tqdm import tqdm import numpy as np import json from rasa.shared.constants import DOCS_URL_RULES import rasa.shared.utils.io from rasa.shared.core.events import FormValidation, UserUttered, ActionExecuted from rasa.core.featurizers.tracker_featurizers import TrackerFeaturizer from rasa.shared.nlu.interpreter import NaturalLanguageInterpreter from rasa.core.policies.memoization import MemoizationPolicy from rasa.core.policies.policy import SupportedData from rasa.shared.core.trackers import ( DialogueStateTracker, get_active_loop_name, is_prev_action_listen_in_state, ) from rasa.shared.core.generator import TrackerWithCachedStates from rasa.core.constants import FORM_POLICY_PRIORITY from rasa.shared.core.constants import ( USER_INTENT_RESTART, USER_INTENT_BACK, USER_INTENT_SESSION_START, ACTION_LISTEN_NAME, ACTION_RESTART_NAME, ACTION_SESSION_START_NAME, ACTION_DEFAULT_FALLBACK_NAME, ACTION_BACK_NAME, RULE_SNIPPET_ACTION_NAME, SHOULD_NOT_BE_SET, PREVIOUS_ACTION, LOOP_REJECTED, ) from rasa.shared.core.domain import InvalidDomain, State, Domain from rasa.shared.nlu.constants import ACTION_NAME, INTENT_NAME_KEY import rasa.core.test if TYPE_CHECKING: from rasa.core.policies.ensemble import PolicyEnsemble # pytype: disable=pyi-error logger = logging.getLogger(__name__) # These are Rasa Open Source default actions and overrule everything at any time. DEFAULT_ACTION_MAPPINGS = { USER_INTENT_RESTART: ACTION_RESTART_NAME, USER_INTENT_BACK: ACTION_BACK_NAME, USER_INTENT_SESSION_START: ACTION_SESSION_START_NAME, } RULES = "rules" RULES_FOR_LOOP_UNHAPPY_PATH = "rules_for_loop_unhappy_path" DO_NOT_VALIDATE_LOOP = "do_not_validate_loop" DO_NOT_PREDICT_LOOP_ACTION = "do_not_predict_loop_action" class InvalidRule(Exception): """Exception that can be raised when rules are not valid.""" def __init__(self, message: Text) -> None: super().__init__() self.message = message + ( f"\nYou can find more information about the usage of " f"rules at {DOCS_URL_RULES}. " ) def __str__(self) -> Text: # return message in error colours return rasa.shared.utils.io.wrap_with_color( self.message, color=rasa.shared.utils.io.bcolors.FAIL ) class RulePolicy(MemoizationPolicy): """Policy which handles all the rules""" # rules use explicit json strings ENABLE_FEATURE_STRING_COMPRESSION = False # number of user inputs that is allowed in case rules are restricted ALLOWED_NUMBER_OF_USER_INPUTS = 1 @staticmethod def supported_data() -> SupportedData: """The type of data supported by this policy. Returns: The data type supported by this policy (ML and rule data). """ return SupportedData.ML_AND_RULE_DATA def __init__( self, featurizer: Optional[TrackerFeaturizer] = None, priority: int = FORM_POLICY_PRIORITY, lookup: Optional[Dict] = None, core_fallback_threshold: float = 0.3, core_fallback_action_name: Text = ACTION_DEFAULT_FALLBACK_NAME, enable_fallback_prediction: bool = True, restrict_rules: bool = True, check_for_contradictions: bool = True, ) -> None: """Create a `RulePolicy` object. Args: featurizer: `Featurizer` which is used to convert conversation states to features. priority: Priority of the policy which is used if multiple policies predict actions with the same confidence. lookup: Lookup table which is used to pick matching rules for a conversation state. core_fallback_threshold: Confidence of the prediction if no rule matched and de-facto threshold for a core fallback. core_fallback_action_name: Name of the action which should be predicted if no rule matched. enable_fallback_prediction: If `True` `core_fallback_action_name` is predicted in case no rule matched. """ self._core_fallback_threshold = core_fallback_threshold self._fallback_action_name = core_fallback_action_name self._enable_fallback_prediction = enable_fallback_prediction self._restrict_rules = restrict_rules self._check_for_contradictions = check_for_contradictions # max history is set to `None` in order to capture any lengths of rule stories super().__init__( featurizer=featurizer, priority=priority, max_history=None, lookup=lookup ) @classmethod def validate_against_domain( cls, ensemble: Optional["PolicyEnsemble"], domain: Optional[Domain] ) -> None: if ensemble is None: return rule_policy = next( (p for p in ensemble.policies if isinstance(p, RulePolicy)), None ) if not rule_policy or not rule_policy._enable_fallback_prediction: return if ( domain is None or rule_policy._fallback_action_name not in domain.action_names ): raise InvalidDomain( f"The fallback action '{rule_policy._fallback_action_name}' which was " f"configured for the {RulePolicy.__name__} must be present in the " f"domain." ) @staticmethod def _is_rule_snippet_state(state: State) -> bool: prev_action_name = state.get(PREVIOUS_ACTION, {}).get(ACTION_NAME) return prev_action_name == RULE_SNIPPET_ACTION_NAME def _create_feature_key(self, states: List[State]) -> Optional[Text]: new_states = [] for state in reversed(states): if self._is_rule_snippet_state(state): # remove all states before RULE_SNIPPET_ACTION_NAME break new_states.insert(0, state) if not new_states: return # we sort keys to make sure that the same states # represented as dictionaries have the same json strings return json.dumps(new_states, sort_keys=True) @staticmethod def _states_for_unhappy_loop_predictions(states: List[State]) -> List[State]: """Modifies the states to create feature keys for loop unhappy path conditions. Args: states: a representation of a tracker as a list of dictionaries containing features Returns: modified states """ # leave only last 2 dialogue turns to # - capture previous meaningful action before action_listen # - ignore previous intent if len(states) == 1 or not states[-2].get(PREVIOUS_ACTION): return [states[-1]] else: return [{PREVIOUS_ACTION: states[-2][PREVIOUS_ACTION]}, states[-1]] @staticmethod def _remove_rule_snippet_predictions(lookup: Dict[Text, Text]) -> Dict[Text, Text]: # Delete rules if it would predict the RULE_SNIPPET_ACTION_NAME action return { feature_key: action for feature_key, action in lookup.items() if action != RULE_SNIPPET_ACTION_NAME } def _create_loop_unhappy_lookup_from_states( self, trackers_as_states: List[List[State]], trackers_as_actions: List[List[Text]], ) -> Dict[Text, Text]: """Creates lookup dictionary from the tracker represented as states. Args: trackers_as_states: representation of the trackers as a list of states trackers_as_actions: representation of the trackers as a list of actions Returns: lookup dictionary """ lookup = {} for states, actions in zip(trackers_as_states, trackers_as_actions): action = actions[0] active_loop = get_active_loop_name(states[-1]) # even if there are two identical feature keys # their loop will be the same if not active_loop: continue states = self._states_for_unhappy_loop_predictions(states) feature_key = self._create_feature_key(states) if not feature_key: continue # Since rule snippets and stories inside the loop contain # only unhappy paths, notify the loop that # it was predicted after an answer to a different question and # therefore it should not validate user input if ( # loop is predicted after action_listen in unhappy path, # therefore no validation is needed is_prev_action_listen_in_state(states[-1]) and action == active_loop ): lookup[feature_key] = DO_NOT_VALIDATE_LOOP elif ( # some action other than active_loop is predicted in unhappy path, # therefore active_loop shouldn't be predicted by the rule not is_prev_action_listen_in_state(states[-1]) and action != active_loop ): lookup[feature_key] = DO_NOT_PREDICT_LOOP_ACTION return lookup def _check_rule_restriction( self, rule_trackers: List[TrackerWithCachedStates] ) -> None: rules_exceeding_max_user_turns = [] for tracker in rule_trackers: number_of_user_uttered = sum( isinstance(event, UserUttered) for event in tracker.events ) if number_of_user_uttered > self.ALLOWED_NUMBER_OF_USER_INPUTS: rules_exceeding_max_user_turns.append(tracker.sender_id) if rules_exceeding_max_user_turns: raise InvalidRule( f"Found rules '{", ".join(rules_exceeding_max_user_turns)}' " f"that contain more than {self.ALLOWED_NUMBER_OF_USER_INPUTS} " f"user message. Rules are not meant to hardcode a state machine. " f"Please use stories for these cases." ) def _predict_next_action( self, tracker: TrackerWithCachedStates, domain: Domain, interpreter: NaturalLanguageInterpreter, ) -> Optional[Text]: probabilities = self.predict_action_probabilities(tracker, domain, interpreter) # do not raise an error if RulePolicy didn't predict anything for stories; # however for rules RulePolicy should always predict an action predicted_action_name = None if ( probabilities != self._default_predictions(domain) or tracker.is_rule_tracker ): predicted_action_name = domain.action_names[np.argmax(probabilities)] return predicted_action_name def _check_prediction( self, tracker: TrackerWithCachedStates, domain: Domain, interpreter: NaturalLanguageInterpreter, gold_action_name: Text, ) -> Optional[Text]: predicted_action_name = self._predict_next_action(tracker, domain, interpreter) if not predicted_action_name or predicted_action_name == gold_action_name: return None # RulePolicy will always predict active_loop first, # but inside loop unhappy path there might be another action if predicted_action_name == tracker.active_loop_name: rasa.core.test.emulate_loop_rejection(tracker) predicted_action_name = self._predict_next_action( tracker, domain, interpreter ) if not predicted_action_name or predicted_action_name == gold_action_name: return None tracker_type = "rule" if tracker.is_rule_tracker else "story" return ( f"- the prediction of the action '{gold_action_name}' in {tracker_type} " f"'{tracker.sender_id}' is contradicting with another rule or story." ) def _find_contradicting_rules( self, trackers: List[TrackerWithCachedStates], domain: Domain, interpreter: NaturalLanguageInterpreter, ) -> None: logger.debug("Started checking rules and stories for contradictions.") # during training we run `predict_action_probabilities` to check for # contradicting rules. # We silent prediction debug to avoid too many logs during these checks. logger_level = logger.level logger.setLevel(logging.WARNING) error_messages = [] pbar = tqdm( trackers, desc="Processed trackers", disable=rasa.shared.utils.io.is_logging_disabled(), ) for tracker in pbar: running_tracker = tracker.init_copy() running_tracker.sender_id = tracker.sender_id # the first action is always unpredictable next_action_is_unpredictable = True for event in tracker.applied_events(): if not isinstance(event, ActionExecuted): running_tracker.update(event) continue if event.action_name == RULE_SNIPPET_ACTION_NAME: # notify that we shouldn't check that the action after # RULE_SNIPPET_ACTION_NAME is unpredictable next_action_is_unpredictable = True # do not add RULE_SNIPPET_ACTION_NAME event continue # do not run prediction on unpredictable actions if next_action_is_unpredictable or event.unpredictable: next_action_is_unpredictable = False # reset unpredictability running_tracker.update(event) continue gold_action_name = event.action_name or event.action_text error_message = self._check_prediction( running_tracker, domain, interpreter, gold_action_name ) if error_message: error_messages.append(error_message) running_tracker.update(event) logger.setLevel(logger_level) # reset logger level if error_messages: error_messages = "\n".join(error_messages) raise InvalidRule( f"\nContradicting rules or stories found🚨\n\n{error_messages}\n" f"Please update your stories and rules so that they don't contradict " f"each other." ) logger.debug("Found no contradicting rules.") def train( self, training_trackers: List[TrackerWithCachedStates], domain: Domain, interpreter: NaturalLanguageInterpreter, **kwargs: Any, ) -> None: # only consider original trackers (no augmented ones) training_trackers = [ t for t in training_trackers if not hasattr(t, "is_augmented") or not t.is_augmented ] # only use trackers from rule-based training data rule_trackers = [t for t in training_trackers if t.is_rule_tracker] if self._restrict_rules: self._check_rule_restriction(rule_trackers) ( rule_trackers_as_states, rule_trackers_as_actions, ) = self.featurizer.training_states_and_actions(rule_trackers, domain) rules_lookup = self._create_lookup_from_states( rule_trackers_as_states, rule_trackers_as_actions ) self.lookup[RULES] = self._remove_rule_snippet_predictions(rules_lookup) story_trackers = [t for t in training_trackers if not t.is_rule_tracker] ( story_trackers_as_states, story_trackers_as_actions, ) = self.featurizer.training_states_and_actions(story_trackers, domain) # use all trackers to find negative rules in unhappy paths trackers_as_states = rule_trackers_as_states + story_trackers_as_states trackers_as_actions = rule_trackers_as_actions + story_trackers_as_actions # negative rules are not anti-rules, they are auxiliary to actual rules self.lookup[ RULES_FOR_LOOP_UNHAPPY_PATH ] = self._create_loop_unhappy_lookup_from_states( trackers_as_states, trackers_as_actions ) # make this configurable because checking might take a lot of time if self._check_for_contradictions: # using trackers here might not be the most efficient way, however # it allows us to directly test `predict_action_probabilities` method self._find_contradicting_rules(training_trackers, domain, interpreter) logger.debug(f"Memorized '{len(self.lookup[RULES])}' unique rules.") @staticmethod def _does_rule_match_state(rule_state: State, conversation_state: State) -> bool: for state_type, rule_sub_state in rule_state.items(): conversation_sub_state = conversation_state.get(state_type, {}) for key, value in rule_sub_state.items(): if isinstance(value, list): # json dumps and loads tuples as lists, # so we need to convert them back value = tuple(value) if ( # value should be set, therefore # check whether it is the same as in the state value and value != SHOULD_NOT_BE_SET and conversation_sub_state.get(key) != value ) or ( # value shouldn't be set, therefore # it should be None or non existent in the state value == SHOULD_NOT_BE_SET and conversation_sub_state.get(key) # during training `SHOULD_NOT_BE_SET` is provided. Hence, we also # have to check for the value of the slot state and conversation_sub_state.get(key) != SHOULD_NOT_BE_SET ): return False return True @staticmethod def _rule_key_to_state(rule_key: Text) -> List[State]: return json.loads(rule_key) def _is_rule_applicable( self, rule_key: Text, turn_index: int, conversation_state: State ) -> bool: """Check if rule is satisfied with current state at turn.""" # turn_index goes back in time reversed_rule_states = list(reversed(self._rule_key_to_state(rule_key))) return bool( # rule is shorter than current turn index turn_index >= len(reversed_rule_states) # current rule and state turns are empty or (not reversed_rule_states[turn_index] and not conversation_state) # check that current rule turn features are present in current state turn or ( reversed_rule_states[turn_index] and conversation_state and self._does_rule_match_state( reversed_rule_states[turn_index], conversation_state ) ) ) def _get_possible_keys( self, lookup: Dict[Text, Text], states: List[State] ) -> Set[Text]: possible_keys = set(lookup.keys()) for i, state in enumerate(reversed(states)): # find rule keys that correspond to current state possible_keys = set( filter( lambda _key: self._is_rule_applicable(_key, i, state), possible_keys ) ) return possible_keys @staticmethod def _find_action_from_default_actions( tracker: DialogueStateTracker, ) -> Optional[Text]: if ( not tracker.latest_action_name == ACTION_LISTEN_NAME or not tracker.latest_message ): return None default_action_name = DEFAULT_ACTION_MAPPINGS.get( tracker.latest_message.intent.get(INTENT_NAME_KEY) ) if default_action_name: logger.debug(f"Predicted default action '{default_action_name}'.") return default_action_name @staticmethod def _find_action_from_loop_happy_path( tracker: DialogueStateTracker, ) -> Optional[Text]: active_loop_name = tracker.active_loop_name active_loop_rejected = tracker.active_loop.get(LOOP_REJECTED) should_predict_loop = ( active_loop_name and not active_loop_rejected and tracker.latest_action.get(ACTION_NAME) != active_loop_name ) should_predict_listen = ( active_loop_name and not active_loop_rejected and tracker.latest_action_name == active_loop_name ) if should_predict_loop: logger.debug(f"Predicted loop '{active_loop_name}'.") return active_loop_name # predict `action_listen` if loop action was run successfully if should_predict_listen: logger.debug( f"Predicted '{ACTION_LISTEN_NAME}' after loop '{active_loop_name}'." ) return ACTION_LISTEN_NAME def _find_action_from_rules( self, tracker: DialogueStateTracker, domain: Domain ) -> Optional[Text]: tracker_as_states = self.featurizer.prediction_states([tracker], domain) states = tracker_as_states[0] logger.debug(f"Current tracker state: {states}") rule_keys = self._get_possible_keys(self.lookup[RULES], states) predicted_action_name = None best_rule_key = "" if rule_keys: # if there are several rules, # it should mean that some rule is a subset of another rule # therefore we pick a rule of maximum length best_rule_key = max(rule_keys, key=len) predicted_action_name = self.lookup[RULES].get(best_rule_key) active_loop_name = tracker.active_loop_name if active_loop_name: # find rules for unhappy path of the loop loop_unhappy_keys = self._get_possible_keys( self.lookup[RULES_FOR_LOOP_UNHAPPY_PATH], states ) # there could be several unhappy path conditions unhappy_path_conditions = [ self.lookup[RULES_FOR_LOOP_UNHAPPY_PATH].get(key) for key in loop_unhappy_keys ] # Check if a rule that predicted action_listen # was applied inside the loop. # Rules might not explicitly switch back to the loop. # Hence, we have to take care of that. predicted_listen_from_general_rule = ( predicted_action_name == ACTION_LISTEN_NAME and not get_active_loop_name(self._rule_key_to_state(best_rule_key)[-1]) ) if predicted_listen_from_general_rule: if DO_NOT_PREDICT_LOOP_ACTION not in unhappy_path_conditions: # negative rules don't contain a key that corresponds to # the fact that active_loop shouldn't be predicted logger.debug( f"Predicted loop '{active_loop_name}' by overwriting " f"'{ACTION_LISTEN_NAME}' predicted by general rule." ) return active_loop_name # do not predict anything predicted_action_name = None if DO_NOT_VALIDATE_LOOP in unhappy_path_conditions: logger.debug("Added `FormValidation(False)` event.") tracker.update(FormValidation(False)) if predicted_action_name is not None: logger.debug( f"There is a rule for the next action '{predicted_action_name}'." ) else: logger.debug("There is no applicable rule.") return predicted_action_name def predict_action_probabilities( self, tracker: DialogueStateTracker, domain: Domain, interpreter: NaturalLanguageInterpreter, **kwargs: Any, ) -> List[float]: result = self._default_predictions(domain) # Rasa Open Source default actions overrule anything. If users want to achieve # the same, they need to write a rule or make sure that their loop rejects # accordingly. default_action_name = self._find_action_from_default_actions(tracker) if default_action_name: return self._prediction_result(default_action_name, tracker, domain) # A loop has priority over any other rule. # The rules or any other prediction will be applied only if a loop was rejected. # If we are in a loop, and the loop didn't run previously or rejected, we can # simply force predict the loop. loop_happy_path_action_name = self._find_action_from_loop_happy_path(tracker) if loop_happy_path_action_name: return self._prediction_result(loop_happy_path_action_name, tracker, domain) rules_action_name = self._find_action_from_rules(tracker, domain) if rules_action_name: return self._prediction_result(rules_action_name, tracker, domain) return result def _default_predictions(self, domain: Domain) -> List[float]: result = super()._default_predictions(domain) if self._enable_fallback_prediction: result[ domain.index_for_action(self._fallback_action_name) ] = self._core_fallback_threshold return result def _metadata(self) -> Dict[Text, Any]: return { "priority": self.priority, "lookup": self.lookup, "core_fallback_threshold": self._core_fallback_threshold, "core_fallback_action_name": self._fallback_action_name, "enable_fallback_prediction": self._enable_fallback_prediction, } @classmethod def _metadata_filename(cls) -> Text: return "rule_policy.json"
import logging from typing import List, Dict, Text, Optional, Any, Set, TYPE_CHECKING, Union from tqdm import tqdm import numpy as np import json from rasa.shared.constants import DOCS_URL_RULES import rasa.shared.utils.io from rasa.shared.core.events import FormValidation, UserUttered, ActionExecuted from rasa.core.featurizers.tracker_featurizers import TrackerFeaturizer from rasa.shared.nlu.interpreter import NaturalLanguageInterpreter from rasa.core.policies.memoization import MemoizationPolicy from rasa.core.policies.policy import SupportedData from rasa.shared.core.trackers import ( DialogueStateTracker, get_active_loop_name, is_prev_action_listen_in_state, ) from rasa.shared.core.generator import TrackerWithCachedStates from rasa.core.constants import FORM_POLICY_PRIORITY from rasa.shared.core.constants import ( USER_INTENT_RESTART, USER_INTENT_BACK, USER_INTENT_SESSION_START, ACTION_LISTEN_NAME, ACTION_RESTART_NAME, ACTION_SESSION_START_NAME, ACTION_DEFAULT_FALLBACK_NAME, ACTION_BACK_NAME, RULE_SNIPPET_ACTION_NAME, SHOULD_NOT_BE_SET, PREVIOUS_ACTION, LOOP_REJECTED, ) from rasa.shared.core.domain import InvalidDomain, State, Domain from rasa.shared.nlu.constants import ACTION_NAME, INTENT_NAME_KEY import rasa.core.test if TYPE_CHECKING: from rasa.core.policies.ensemble import PolicyEnsemble # pytype: disable=pyi-error logger = logging.getLogger(__name__) # These are Rasa Open Source default actions and overrule everything at any time. DEFAULT_ACTION_MAPPINGS = { USER_INTENT_RESTART: ACTION_RESTART_NAME, USER_INTENT_BACK: ACTION_BACK_NAME, USER_INTENT_SESSION_START: ACTION_SESSION_START_NAME, } RULES = "rules" RULES_FOR_LOOP_UNHAPPY_PATH = "rules_for_loop_unhappy_path" DO_NOT_VALIDATE_LOOP = "do_not_validate_loop" DO_NOT_PREDICT_LOOP_ACTION = "do_not_predict_loop_action" class InvalidRule(Exception): """Exception that can be raised when rules are not valid.""" def __init__(self, message: Text) -> None: super().__init__() self.message = message + ( f"\nYou can find more information about the usage of " f"rules at {DOCS_URL_RULES}. " ) def __str__(self) -> Text: # return message in error colours return rasa.shared.utils.io.wrap_with_color( self.message, color=rasa.shared.utils.io.bcolors.FAIL ) class RulePolicy(MemoizationPolicy): """Policy which handles all the rules""" # rules use explicit json strings ENABLE_FEATURE_STRING_COMPRESSION = False # number of user inputs that is allowed in case rules are restricted ALLOWED_NUMBER_OF_USER_INPUTS = 1 @staticmethod def supported_data() -> SupportedData: """The type of data supported by this policy. Returns: The data type supported by this policy (ML and rule data). """ return SupportedData.ML_AND_RULE_DATA def __init__( self, featurizer: Optional[TrackerFeaturizer] = None, priority: int = FORM_POLICY_PRIORITY, lookup: Optional[Dict] = None, core_fallback_threshold: float = 0.3, core_fallback_action_name: Text = ACTION_DEFAULT_FALLBACK_NAME, enable_fallback_prediction: bool = True, restrict_rules: bool = True, check_for_contradictions: bool = True, ) -> None: """Create a `RulePolicy` object. Args: featurizer: `Featurizer` which is used to convert conversation states to features. priority: Priority of the policy which is used if multiple policies predict actions with the same confidence. lookup: Lookup table which is used to pick matching rules for a conversation state. core_fallback_threshold: Confidence of the prediction if no rule matched and de-facto threshold for a core fallback. core_fallback_action_name: Name of the action which should be predicted if no rule matched. enable_fallback_prediction: If `True` `core_fallback_action_name` is predicted in case no rule matched. """ self._core_fallback_threshold = core_fallback_threshold self._fallback_action_name = core_fallback_action_name self._enable_fallback_prediction = enable_fallback_prediction self._restrict_rules = restrict_rules self._check_for_contradictions = check_for_contradictions # max history is set to `None` in order to capture any lengths of rule stories super().__init__( featurizer=featurizer, priority=priority, max_history=None, lookup=lookup ) @classmethod def validate_against_domain( cls, ensemble: Optional["PolicyEnsemble"], domain: Optional[Domain] ) -> None: if ensemble is None: return rule_policy = next( (p for p in ensemble.policies if isinstance(p, RulePolicy)), None ) if not rule_policy or not rule_policy._enable_fallback_prediction: return if ( domain is None or rule_policy._fallback_action_name not in domain.action_names ): raise InvalidDomain( f"The fallback action '{rule_policy._fallback_action_name}' which was " f"configured for the {RulePolicy.__name__} must be present in the " f"domain." ) @staticmethod def _is_rule_snippet_state(state: State) -> bool: prev_action_name = state.get(PREVIOUS_ACTION, {}).get(ACTION_NAME) return prev_action_name == RULE_SNIPPET_ACTION_NAME def _create_feature_key(self, states: List[State]) -> Optional[Text]: new_states = [] for state in reversed(states): if self._is_rule_snippet_state(state): # remove all states before RULE_SNIPPET_ACTION_NAME break new_states.insert(0, state) if not new_states: return # we sort keys to make sure that the same states # represented as dictionaries have the same json strings return json.dumps(new_states, sort_keys=True) @staticmethod def _states_for_unhappy_loop_predictions(states: List[State]) -> List[State]: """Modifies the states to create feature keys for loop unhappy path conditions. Args: states: a representation of a tracker as a list of dictionaries containing features Returns: modified states """ # leave only last 2 dialogue turns to # - capture previous meaningful action before action_listen # - ignore previous intent if len(states) == 1 or not states[-2].get(PREVIOUS_ACTION): return [states[-1]] else: return [{PREVIOUS_ACTION: states[-2][PREVIOUS_ACTION]}, states[-1]] @staticmethod def _remove_rule_snippet_predictions(lookup: Dict[Text, Text]) -> Dict[Text, Text]: # Delete rules if it would predict the RULE_SNIPPET_ACTION_NAME action return { feature_key: action for feature_key, action in lookup.items() if action != RULE_SNIPPET_ACTION_NAME } def _create_loop_unhappy_lookup_from_states( self, trackers_as_states: List[List[State]], trackers_as_actions: List[List[Text]], ) -> Dict[Text, Text]: """Creates lookup dictionary from the tracker represented as states. Args: trackers_as_states: representation of the trackers as a list of states trackers_as_actions: representation of the trackers as a list of actions Returns: lookup dictionary """ lookup = {} for states, actions in zip(trackers_as_states, trackers_as_actions): action = actions[0] active_loop = get_active_loop_name(states[-1]) # even if there are two identical feature keys # their loop will be the same if not active_loop: continue states = self._states_for_unhappy_loop_predictions(states) feature_key = self._create_feature_key(states) if not feature_key: continue # Since rule snippets and stories inside the loop contain # only unhappy paths, notify the loop that # it was predicted after an answer to a different question and # therefore it should not validate user input if ( # loop is predicted after action_listen in unhappy path, # therefore no validation is needed is_prev_action_listen_in_state(states[-1]) and action == active_loop ): lookup[feature_key] = DO_NOT_VALIDATE_LOOP elif ( # some action other than active_loop is predicted in unhappy path, # therefore active_loop shouldn't be predicted by the rule not is_prev_action_listen_in_state(states[-1]) and action != active_loop ): lookup[feature_key] = DO_NOT_PREDICT_LOOP_ACTION return lookup def _check_rule_restriction( self, rule_trackers: List[TrackerWithCachedStates] ) -> None: rules_exceeding_max_user_turns = [] for tracker in rule_trackers: number_of_user_uttered = sum( isinstance(event, UserUttered) for event in tracker.events ) if number_of_user_uttered > self.ALLOWED_NUMBER_OF_USER_INPUTS: rules_exceeding_max_user_turns.append(tracker.sender_id) if rules_exceeding_max_user_turns: raise InvalidRule( f"Found rules '{', '.join(rules_exceeding_max_user_turns)}' " f"that contain more than {self.ALLOWED_NUMBER_OF_USER_INPUTS} " f"user message. Rules are not meant to hardcode a state machine. " f"Please use stories for these cases." ) def _predict_next_action( self, tracker: TrackerWithCachedStates, domain: Domain, interpreter: NaturalLanguageInterpreter, ) -> Optional[Text]: probabilities = self.predict_action_probabilities(tracker, domain, interpreter) # do not raise an error if RulePolicy didn't predict anything for stories; # however for rules RulePolicy should always predict an action predicted_action_name = None if ( probabilities != self._default_predictions(domain) or tracker.is_rule_tracker ): predicted_action_name = domain.action_names[np.argmax(probabilities)] return predicted_action_name def _check_prediction( self, tracker: TrackerWithCachedStates, domain: Domain, interpreter: NaturalLanguageInterpreter, gold_action_name: Text, ) -> Optional[Text]: predicted_action_name = self._predict_next_action(tracker, domain, interpreter) if not predicted_action_name or predicted_action_name == gold_action_name: return None # RulePolicy will always predict active_loop first, # but inside loop unhappy path there might be another action if predicted_action_name == tracker.active_loop_name: rasa.core.test.emulate_loop_rejection(tracker) predicted_action_name = self._predict_next_action( tracker, domain, interpreter ) if not predicted_action_name or predicted_action_name == gold_action_name: return None tracker_type = "rule" if tracker.is_rule_tracker else "story" return ( f"- the prediction of the action '{gold_action_name}' in {tracker_type} " f"'{tracker.sender_id}' is contradicting with another rule or story." ) def _find_contradicting_rules( self, trackers: List[TrackerWithCachedStates], domain: Domain, interpreter: NaturalLanguageInterpreter, ) -> None: logger.debug("Started checking rules and stories for contradictions.") # during training we run `predict_action_probabilities` to check for # contradicting rules. # We silent prediction debug to avoid too many logs during these checks. logger_level = logger.level logger.setLevel(logging.WARNING) error_messages = [] pbar = tqdm( trackers, desc="Processed trackers", disable=rasa.shared.utils.io.is_logging_disabled(), ) for tracker in pbar: running_tracker = tracker.init_copy() running_tracker.sender_id = tracker.sender_id # the first action is always unpredictable next_action_is_unpredictable = True for event in tracker.applied_events(): if not isinstance(event, ActionExecuted): running_tracker.update(event) continue if event.action_name == RULE_SNIPPET_ACTION_NAME: # notify that we shouldn't check that the action after # RULE_SNIPPET_ACTION_NAME is unpredictable next_action_is_unpredictable = True # do not add RULE_SNIPPET_ACTION_NAME event continue # do not run prediction on unpredictable actions if next_action_is_unpredictable or event.unpredictable: next_action_is_unpredictable = False # reset unpredictability running_tracker.update(event) continue gold_action_name = event.action_name or event.action_text error_message = self._check_prediction( running_tracker, domain, interpreter, gold_action_name ) if error_message: error_messages.append(error_message) running_tracker.update(event) logger.setLevel(logger_level) # reset logger level if error_messages: error_messages = "\n".join(error_messages) raise InvalidRule( f"\nContradicting rules or stories found🚨\n\n{error_messages}\n" f"Please update your stories and rules so that they don't contradict " f"each other." ) logger.debug("Found no contradicting rules.") def train( self, training_trackers: List[TrackerWithCachedStates], domain: Domain, interpreter: NaturalLanguageInterpreter, **kwargs: Any, ) -> None: # only consider original trackers (no augmented ones) training_trackers = [ t for t in training_trackers if not hasattr(t, "is_augmented") or not t.is_augmented ] # only use trackers from rule-based training data rule_trackers = [t for t in training_trackers if t.is_rule_tracker] if self._restrict_rules: self._check_rule_restriction(rule_trackers) ( rule_trackers_as_states, rule_trackers_as_actions, ) = self.featurizer.training_states_and_actions(rule_trackers, domain) rules_lookup = self._create_lookup_from_states( rule_trackers_as_states, rule_trackers_as_actions ) self.lookup[RULES] = self._remove_rule_snippet_predictions(rules_lookup) story_trackers = [t for t in training_trackers if not t.is_rule_tracker] ( story_trackers_as_states, story_trackers_as_actions, ) = self.featurizer.training_states_and_actions(story_trackers, domain) # use all trackers to find negative rules in unhappy paths trackers_as_states = rule_trackers_as_states + story_trackers_as_states trackers_as_actions = rule_trackers_as_actions + story_trackers_as_actions # negative rules are not anti-rules, they are auxiliary to actual rules self.lookup[ RULES_FOR_LOOP_UNHAPPY_PATH ] = self._create_loop_unhappy_lookup_from_states( trackers_as_states, trackers_as_actions ) # make this configurable because checking might take a lot of time if self._check_for_contradictions: # using trackers here might not be the most efficient way, however # it allows us to directly test `predict_action_probabilities` method self._find_contradicting_rules(training_trackers, domain, interpreter) logger.debug(f"Memorized '{len(self.lookup[RULES])}' unique rules.") @staticmethod def _does_rule_match_state(rule_state: State, conversation_state: State) -> bool: for state_type, rule_sub_state in rule_state.items(): conversation_sub_state = conversation_state.get(state_type, {}) for key, value in rule_sub_state.items(): if isinstance(value, list): # json dumps and loads tuples as lists, # so we need to convert them back value = tuple(value) if ( # value should be set, therefore # check whether it is the same as in the state value and value != SHOULD_NOT_BE_SET and conversation_sub_state.get(key) != value ) or ( # value shouldn't be set, therefore # it should be None or non existent in the state value == SHOULD_NOT_BE_SET and conversation_sub_state.get(key) # during training `SHOULD_NOT_BE_SET` is provided. Hence, we also # have to check for the value of the slot state and conversation_sub_state.get(key) != SHOULD_NOT_BE_SET ): return False return True @staticmethod def _rule_key_to_state(rule_key: Text) -> List[State]: return json.loads(rule_key) def _is_rule_applicable( self, rule_key: Text, turn_index: int, conversation_state: State ) -> bool: """Check if rule is satisfied with current state at turn.""" # turn_index goes back in time reversed_rule_states = list(reversed(self._rule_key_to_state(rule_key))) return bool( # rule is shorter than current turn index turn_index >= len(reversed_rule_states) # current rule and state turns are empty or (not reversed_rule_states[turn_index] and not conversation_state) # check that current rule turn features are present in current state turn or ( reversed_rule_states[turn_index] and conversation_state and self._does_rule_match_state( reversed_rule_states[turn_index], conversation_state ) ) ) def _get_possible_keys( self, lookup: Dict[Text, Text], states: List[State] ) -> Set[Text]: possible_keys = set(lookup.keys()) for i, state in enumerate(reversed(states)): # find rule keys that correspond to current state possible_keys = set( filter( lambda _key: self._is_rule_applicable(_key, i, state), possible_keys ) ) return possible_keys @staticmethod def _find_action_from_default_actions( tracker: DialogueStateTracker, ) -> Optional[Text]: if ( not tracker.latest_action_name == ACTION_LISTEN_NAME or not tracker.latest_message ): return None default_action_name = DEFAULT_ACTION_MAPPINGS.get( tracker.latest_message.intent.get(INTENT_NAME_KEY) ) if default_action_name: logger.debug(f"Predicted default action '{default_action_name}'.") return default_action_name @staticmethod def _find_action_from_loop_happy_path( tracker: DialogueStateTracker, ) -> Optional[Text]: active_loop_name = tracker.active_loop_name active_loop_rejected = tracker.active_loop.get(LOOP_REJECTED) should_predict_loop = ( active_loop_name and not active_loop_rejected and tracker.latest_action.get(ACTION_NAME) != active_loop_name ) should_predict_listen = ( active_loop_name and not active_loop_rejected and tracker.latest_action_name == active_loop_name ) if should_predict_loop: logger.debug(f"Predicted loop '{active_loop_name}'.") return active_loop_name # predict `action_listen` if loop action was run successfully if should_predict_listen: logger.debug( f"Predicted '{ACTION_LISTEN_NAME}' after loop '{active_loop_name}'." ) return ACTION_LISTEN_NAME def _find_action_from_rules( self, tracker: DialogueStateTracker, domain: Domain ) -> Optional[Text]: tracker_as_states = self.featurizer.prediction_states([tracker], domain) states = tracker_as_states[0] logger.debug(f"Current tracker state: {states}") rule_keys = self._get_possible_keys(self.lookup[RULES], states) predicted_action_name = None best_rule_key = "" if rule_keys: # if there are several rules, # it should mean that some rule is a subset of another rule # therefore we pick a rule of maximum length best_rule_key = max(rule_keys, key=len) predicted_action_name = self.lookup[RULES].get(best_rule_key) active_loop_name = tracker.active_loop_name if active_loop_name: # find rules for unhappy path of the loop loop_unhappy_keys = self._get_possible_keys( self.lookup[RULES_FOR_LOOP_UNHAPPY_PATH], states ) # there could be several unhappy path conditions unhappy_path_conditions = [ self.lookup[RULES_FOR_LOOP_UNHAPPY_PATH].get(key) for key in loop_unhappy_keys ] # Check if a rule that predicted action_listen # was applied inside the loop. # Rules might not explicitly switch back to the loop. # Hence, we have to take care of that. predicted_listen_from_general_rule = ( predicted_action_name == ACTION_LISTEN_NAME and not get_active_loop_name(self._rule_key_to_state(best_rule_key)[-1]) ) if predicted_listen_from_general_rule: if DO_NOT_PREDICT_LOOP_ACTION not in unhappy_path_conditions: # negative rules don't contain a key that corresponds to # the fact that active_loop shouldn't be predicted logger.debug( f"Predicted loop '{active_loop_name}' by overwriting " f"'{ACTION_LISTEN_NAME}' predicted by general rule." ) return active_loop_name # do not predict anything predicted_action_name = None if DO_NOT_VALIDATE_LOOP in unhappy_path_conditions: logger.debug("Added `FormValidation(False)` event.") tracker.update(FormValidation(False)) if predicted_action_name is not None: logger.debug( f"There is a rule for the next action '{predicted_action_name}'." ) else: logger.debug("There is no applicable rule.") return predicted_action_name def predict_action_probabilities( self, tracker: DialogueStateTracker, domain: Domain, interpreter: NaturalLanguageInterpreter, **kwargs: Any, ) -> List[float]: result = self._default_predictions(domain) # Rasa Open Source default actions overrule anything. If users want to achieve # the same, they need to write a rule or make sure that their loop rejects # accordingly. default_action_name = self._find_action_from_default_actions(tracker) if default_action_name: return self._prediction_result(default_action_name, tracker, domain) # A loop has priority over any other rule. # The rules or any other prediction will be applied only if a loop was rejected. # If we are in a loop, and the loop didn't run previously or rejected, we can # simply force predict the loop. loop_happy_path_action_name = self._find_action_from_loop_happy_path(tracker) if loop_happy_path_action_name: return self._prediction_result(loop_happy_path_action_name, tracker, domain) rules_action_name = self._find_action_from_rules(tracker, domain) if rules_action_name: return self._prediction_result(rules_action_name, tracker, domain) return result def _default_predictions(self, domain: Domain) -> List[float]: result = super()._default_predictions(domain) if self._enable_fallback_prediction: result[ domain.index_for_action(self._fallback_action_name) ] = self._core_fallback_threshold return result def _metadata(self) -> Dict[Text, Any]: return { "priority": self.priority, "lookup": self.lookup, "core_fallback_threshold": self._core_fallback_threshold, "core_fallback_action_name": self._fallback_action_name, "enable_fallback_prediction": self._enable_fallback_prediction, } @classmethod def _metadata_filename(cls) -> Text: return "rule_policy.json"
# Copyright © 2021 CloudBlue. All rights reserved. import json import os import sys import inspect import importlib import tempfile import shutil from cookiecutter import generate from cookiecutter.main import cookiecutter from cookiecutter.config import get_user_config from cookiecutter.exceptions import OutputDirExistsException from cookiecutter.generate import generate_context, generate_files from cookiecutter.repository import determine_repo_dir from cookiecutter.utils import rmtree, work_in import click from click import ClickException from connect.cli.core.utils import is_bundle from connect.cli.plugins.project.constants import ( PROJECT_REPORT_BOILERPLATE_URL, ) from connect.cli.plugins.project import utils from connect.reports.validator import ( validate, validate_with_schema, ) from connect.reports.parser import parse def bootstrap_report_project(data_dir: str): click.secho('Bootstraping report project...\n', fg='blue') utils.purge_cookiecutters_dir() answers = utils.general_report_questions() try: if is_bundle(): method_name = '_run_hook_from_repo_dir' setattr(generate, method_name, getattr(utils, method_name)) with work_in(data_dir): utils.pre_gen_cookiecutter_report_hook(answers) project_dir = cookiecutter( PROJECT_REPORT_BOILERPLATE_URL, no_input=True, extra_context=answers, output_dir=data_dir, ) utils.post_gen_cookiecutter_report_hook(answers, project_dir) else: project_dir = cookiecutter( PROJECT_REPORT_BOILERPLATE_URL, no_input=True, extra_context=answers, output_dir=data_dir, ) click.secho(f'\nReports Project location: {project_dir}', fg='blue') except OutputDirExistsException as error: project_path = str(error).split('"')[1] raise ClickException( f'\nThe directory "{project_path}" already exists, ' '\nif you would like to use that name, please delete ' 'the directory or use another location.', ) def validate_report_project(project_dir): click.secho(f'Validating project {project_dir}...\n', fg='blue') data = _file_descriptor_validations(project_dir) errors = validate_with_schema(data) if errors: raise ClickException(f'Invalid `reports.json`: {errors}') report_project = parse(project_dir, data) errors = validate(report_project) if errors: raise ClickException(f'Invalid `reports.json`: {','.join(errors)}') for report in report_project.reports: _entrypoint_validations(project_dir, report.entrypoint, report.report_spec) click.secho(f'Report Project {project_dir} has been successfully validated.', fg='green') def add_report(project_dir, package_name): if not os.path.isdir(f'{project_dir}/{package_name}'): raise ClickException( f'The directory package called `{package_name}` does not exist,' '\nPlease, create it or choose an existing one using `-n` option.', ) # Required: check if the project descriptor is valid project_desc = _file_descriptor_validations(project_dir) errors = validate_with_schema(project_desc) if errors: raise ClickException(f'Invalid `reports.json`: {errors}') click.secho(f'Adding new report to project {project_dir}...\n', fg='blue') with tempfile.TemporaryDirectory() as add_report_tmpdir: # Instead of using cookiecutter use the internals report_dir, report_slug = _custom_cookiecutter( PROJECT_REPORT_BOILERPLATE_URL, output_dir=add_report_tmpdir, package_slug=package_name, ) if os.path.isdir(f'{project_dir}/{package_name}/{report_slug}'): raise ClickException( f'\nThe report directory called `{project_dir}/{package_name}/{report_slug}` already exists, ' '\nplease, choose other report name or delete the existing one.', ) shutil.move( f'{report_dir}/{package_name}/{report_slug}', f'{project_dir}/{package_name}/', ) _add_report_to_descriptor(project_dir, report_dir, package_name) click.secho('\nReport has been successfully created.', fg='blue') def _custom_cookiecutter(template, output_dir, package_slug): config_dict = get_user_config( config_file=None, default_config=False, ) template_name = os.path.splitext(os.path.basename(template))[0] repo_dir = os.path.join(config_dict['cookiecutters_dir'], template_name) if os.path.isdir(repo_dir): rmtree(repo_dir) repo_dir, _ = determine_repo_dir( template=template, abbreviations=config_dict['abbreviations'], clone_to_dir=config_dict['cookiecutters_dir'], checkout=None, no_input=False, password=None, directory=None, ) context_file = os.path.join(repo_dir, 'cookiecutter.json') context = generate_context( context_file=context_file, default_context=config_dict['default_context'], extra_context=None, ) answers = utils.add_report_questions() context['cookiecutter']['_template'] = template context['cookiecutter']['project_slug'] = utils._slugify(context['cookiecutter']['project_name']) context['cookiecutter']['package_name'] = package_slug context['cookiecutter']['package_slug'] = package_slug context['cookiecutter']['initial_report_name'] = answers['initial_report_name'] context['cookiecutter']['initial_report_slug'] = utils._slugify(answers['initial_report_name']) context['cookiecutter']['initial_report_description'] = answers['initial_report_description'] context['cookiecutter']['initial_report_renderer'] = answers['initial_report_renderer'] context['cookiecutter']['author'] = answers['author'] result = _generate_files(context, output_dir, repo_dir) return result, context['cookiecutter']['initial_report_slug'] def _generate_files(context, output_dir, repo_dir): if is_bundle(): method_name = '_run_hook_from_repo_dir' setattr(generate, method_name, getattr(utils, method_name)) with work_in(output_dir): utils.pre_gen_cookiecutter_report_hook(context['cookiecutter']) result = generate_files( repo_dir=repo_dir, context=context, overwrite_if_exists=False, skip_if_file_exists=False, output_dir=output_dir, ) utils._create_renderer_templates(context['cookiecutter']) else: result = generate_files( repo_dir=repo_dir, context=context, overwrite_if_exists=False, skip_if_file_exists=False, output_dir=output_dir, ) return result def _add_report_to_descriptor(project_dir, report_dir, package_slug): project_descriptor = os.path.join(project_dir, 'reports.json') project_desc = json.load(open(project_descriptor, 'r')) temporal_descriptor = os.path.join(report_dir, 'reports.json') temporal_desc = json.load(open(temporal_descriptor, 'r')) report_dict = temporal_desc['reports'][0] project_desc['reports'].append(report_dict) json.dump( project_desc, open(f'{project_dir}/reports.json', 'w'), indent=4, ) def _file_descriptor_validations(project_dir): descriptor_file = os.path.join(project_dir, 'reports.json') if not os.path.isfile(descriptor_file): raise ClickException( f'The directory `{project_dir}` does not look like a report project directory, ' 'the mandatory `reports.json` file descriptor is not present.', ) try: data = json.load(open(descriptor_file, 'r')) except json.JSONDecodeError: raise ClickException( 'The report project descriptor `reports.json` is not a valid json file.', ) return data def _entrypoint_validations(project_dir, entrypoint, report_spec): # Package validation sys.path.append(os.path.join(os.getcwd(), project_dir)) package = entrypoint.rsplit('.', 1)[0] try: entrypoint_module = importlib.import_module(package) except ImportError as error: raise ClickException(f'\nErrors detected on entrypoint module: {error}') # Function validation if report_spec == '1' and len(inspect.signature(entrypoint_module.generate).parameters) != 3: raise ClickException( 'Wrong arguments on `generate` function. The signature must be:' '\n>> def generate(client, parameters, progress_callback) <<', ) if report_spec == '2' and len(inspect.signature(entrypoint_module.generate).parameters) != 5: raise ClickException( 'Wrong arguments on `generate` function. The signature must be:' '\n>> def generate(client=None, input_data=None, progress_callback=None, ' 'renderer_type=None, extra_context_callback=None) <<', )
# Copyright © 2021 CloudBlue. All rights reserved. import json import os import sys import inspect import importlib import tempfile import shutil from cookiecutter import generate from cookiecutter.main import cookiecutter from cookiecutter.config import get_user_config from cookiecutter.exceptions import OutputDirExistsException from cookiecutter.generate import generate_context, generate_files from cookiecutter.repository import determine_repo_dir from cookiecutter.utils import rmtree, work_in import click from click import ClickException from connect.cli.core.utils import is_bundle from connect.cli.plugins.project.constants import ( PROJECT_REPORT_BOILERPLATE_URL, ) from connect.cli.plugins.project import utils from connect.reports.validator import ( validate, validate_with_schema, ) from connect.reports.parser import parse def bootstrap_report_project(data_dir: str): click.secho('Bootstraping report project...\n', fg='blue') utils.purge_cookiecutters_dir() answers = utils.general_report_questions() try: if is_bundle(): method_name = '_run_hook_from_repo_dir' setattr(generate, method_name, getattr(utils, method_name)) with work_in(data_dir): utils.pre_gen_cookiecutter_report_hook(answers) project_dir = cookiecutter( PROJECT_REPORT_BOILERPLATE_URL, no_input=True, extra_context=answers, output_dir=data_dir, ) utils.post_gen_cookiecutter_report_hook(answers, project_dir) else: project_dir = cookiecutter( PROJECT_REPORT_BOILERPLATE_URL, no_input=True, extra_context=answers, output_dir=data_dir, ) click.secho(f'\nReports Project location: {project_dir}', fg='blue') except OutputDirExistsException as error: project_path = str(error).split('"')[1] raise ClickException( f'\nThe directory "{project_path}" already exists, ' '\nif you would like to use that name, please delete ' 'the directory or use another location.', ) def validate_report_project(project_dir): click.secho(f'Validating project {project_dir}...\n', fg='blue') data = _file_descriptor_validations(project_dir) errors = validate_with_schema(data) if errors: raise ClickException(f'Invalid `reports.json`: {errors}') report_project = parse(project_dir, data) errors = validate(report_project) if errors: raise ClickException(f'Invalid `reports.json`: {",".join(errors)}') for report in report_project.reports: _entrypoint_validations(project_dir, report.entrypoint, report.report_spec) click.secho(f'Report Project {project_dir} has been successfully validated.', fg='green') def add_report(project_dir, package_name): if not os.path.isdir(f'{project_dir}/{package_name}'): raise ClickException( f'The directory package called `{package_name}` does not exist,' '\nPlease, create it or choose an existing one using `-n` option.', ) # Required: check if the project descriptor is valid project_desc = _file_descriptor_validations(project_dir) errors = validate_with_schema(project_desc) if errors: raise ClickException(f'Invalid `reports.json`: {errors}') click.secho(f'Adding new report to project {project_dir}...\n', fg='blue') with tempfile.TemporaryDirectory() as add_report_tmpdir: # Instead of using cookiecutter use the internals report_dir, report_slug = _custom_cookiecutter( PROJECT_REPORT_BOILERPLATE_URL, output_dir=add_report_tmpdir, package_slug=package_name, ) if os.path.isdir(f'{project_dir}/{package_name}/{report_slug}'): raise ClickException( f'\nThe report directory called `{project_dir}/{package_name}/{report_slug}` already exists, ' '\nplease, choose other report name or delete the existing one.', ) shutil.move( f'{report_dir}/{package_name}/{report_slug}', f'{project_dir}/{package_name}/', ) _add_report_to_descriptor(project_dir, report_dir, package_name) click.secho('\nReport has been successfully created.', fg='blue') def _custom_cookiecutter(template, output_dir, package_slug): config_dict = get_user_config( config_file=None, default_config=False, ) template_name = os.path.splitext(os.path.basename(template))[0] repo_dir = os.path.join(config_dict['cookiecutters_dir'], template_name) if os.path.isdir(repo_dir): rmtree(repo_dir) repo_dir, _ = determine_repo_dir( template=template, abbreviations=config_dict['abbreviations'], clone_to_dir=config_dict['cookiecutters_dir'], checkout=None, no_input=False, password=None, directory=None, ) context_file = os.path.join(repo_dir, 'cookiecutter.json') context = generate_context( context_file=context_file, default_context=config_dict['default_context'], extra_context=None, ) answers = utils.add_report_questions() context['cookiecutter']['_template'] = template context['cookiecutter']['project_slug'] = utils._slugify(context['cookiecutter']['project_name']) context['cookiecutter']['package_name'] = package_slug context['cookiecutter']['package_slug'] = package_slug context['cookiecutter']['initial_report_name'] = answers['initial_report_name'] context['cookiecutter']['initial_report_slug'] = utils._slugify(answers['initial_report_name']) context['cookiecutter']['initial_report_description'] = answers['initial_report_description'] context['cookiecutter']['initial_report_renderer'] = answers['initial_report_renderer'] context['cookiecutter']['author'] = answers['author'] result = _generate_files(context, output_dir, repo_dir) return result, context['cookiecutter']['initial_report_slug'] def _generate_files(context, output_dir, repo_dir): if is_bundle(): method_name = '_run_hook_from_repo_dir' setattr(generate, method_name, getattr(utils, method_name)) with work_in(output_dir): utils.pre_gen_cookiecutter_report_hook(context['cookiecutter']) result = generate_files( repo_dir=repo_dir, context=context, overwrite_if_exists=False, skip_if_file_exists=False, output_dir=output_dir, ) utils._create_renderer_templates(context['cookiecutter']) else: result = generate_files( repo_dir=repo_dir, context=context, overwrite_if_exists=False, skip_if_file_exists=False, output_dir=output_dir, ) return result def _add_report_to_descriptor(project_dir, report_dir, package_slug): project_descriptor = os.path.join(project_dir, 'reports.json') project_desc = json.load(open(project_descriptor, 'r')) temporal_descriptor = os.path.join(report_dir, 'reports.json') temporal_desc = json.load(open(temporal_descriptor, 'r')) report_dict = temporal_desc['reports'][0] project_desc['reports'].append(report_dict) json.dump( project_desc, open(f'{project_dir}/reports.json', 'w'), indent=4, ) def _file_descriptor_validations(project_dir): descriptor_file = os.path.join(project_dir, 'reports.json') if not os.path.isfile(descriptor_file): raise ClickException( f'The directory `{project_dir}` does not look like a report project directory, ' 'the mandatory `reports.json` file descriptor is not present.', ) try: data = json.load(open(descriptor_file, 'r')) except json.JSONDecodeError: raise ClickException( 'The report project descriptor `reports.json` is not a valid json file.', ) return data def _entrypoint_validations(project_dir, entrypoint, report_spec): # Package validation sys.path.append(os.path.join(os.getcwd(), project_dir)) package = entrypoint.rsplit('.', 1)[0] try: entrypoint_module = importlib.import_module(package) except ImportError as error: raise ClickException(f'\nErrors detected on entrypoint module: {error}') # Function validation if report_spec == '1' and len(inspect.signature(entrypoint_module.generate).parameters) != 3: raise ClickException( 'Wrong arguments on `generate` function. The signature must be:' '\n>> def generate(client, parameters, progress_callback) <<', ) if report_spec == '2' and len(inspect.signature(entrypoint_module.generate).parameters) != 5: raise ClickException( 'Wrong arguments on `generate` function. The signature must be:' '\n>> def generate(client=None, input_data=None, progress_callback=None, ' 'renderer_type=None, extra_context_callback=None) <<', )
# This file is part of sner4 project governed by MIT license, see the LICENSE.txt file. """ parsers to import from agent outputs to storage """ import json import re import sys from datetime import datetime from pathlib import Path from pprint import pprint from time import time from zipfile import ZipFile import libnmap.parser from sner.lib import file_from_zip, is_zip from sner.server.parser import ParsedHost, ParsedItemsDb, ParsedNote, ParsedService, ParserBase class ParserModule(ParserBase): # pylint: disable=too-few-public-methods """nmap xml output parser""" ARCHIVE_PATHS = r'output\.xml|output6\.xml' @classmethod def parse_path(cls, path): """parse data from path""" if is_zip(path): pidb = ParsedItemsDb() with ZipFile(path) as fzip: for fname in filter(lambda x: re.match(cls.ARCHIVE_PATHS, x), fzip.namelist()): pidb += cls._parse_data(file_from_zip(path, fname).decode('utf-8')) return pidb return cls._parse_data(Path(path).read_text()) @classmethod def _parse_data(cls, data): """parse raw string data""" report = libnmap.parser.NmapParser.parse_fromstring(data) pidb = ParsedItemsDb() for ihost in report.hosts: host, cpe_note = cls._parse_host(ihost) via_target = ihost.user_target_hostname or host.address import_time = datetime.fromtimestamp(int(ihost.starttime or time())) pidb.hosts.upsert(host) if cpe_note: pidb.notes.upsert(cpe_note) for iscript in ihost.scripts_results: note = cls._parse_note(iscript, host.handle, None, via_target, import_time) pidb.notes.upsert(note) for iservice in ihost.services: service = cls._parse_service(iservice, host.handle, import_time) pidb.services.upsert(service) if iservice.cpelist: note = ParsedNote( host_handle=host.handle, service_handle=service.handle, via_target=via_target, xtype='cpe', data=json.dumps([x.cpestring for x in iservice.cpelist]), import_time=import_time ) pidb.notes.upsert(note) for iscript in iservice.scripts_results: note = cls._parse_note(iscript, host.handle, service.handle, via_target, import_time) pidb.notes.upsert(note) return pidb @staticmethod def _parse_host(ihost): """parse host""" host = ParsedHost(address=ihost.address) cpe_note = None if ihost.hostnames: host.hostnames = list(set(ihost.hostnames)) if not host.hostname: host.hostname = host.hostnames[0] for osmatch in ihost.os_match_probabilities(): if osmatch.accuracy == 100: host.os = osmatch.name cpe_note = ParsedNote(host_handle=host.handle, xtype='cpe', data=json.dumps(osmatch.get_cpe())) return host, cpe_note @staticmethod def _parse_service(iservice, host_handle, import_time): """parse service""" service = ParsedService( host_handle=host_handle, proto=iservice.protocol, port=iservice.port, state=f'{iservice.state}:{iservice.reason}', import_time=import_time ) if iservice.service: service.name = iservice.service if iservice.banner: service.info = iservice.banner return service @staticmethod def _parse_note(iscript, host_handle, service_handle, via_target, import_time): """parse note""" return ParsedNote( host_handle=host_handle, service_handle=service_handle, via_target=via_target, xtype=f'nmap.{iscript['id']}', data=json.dumps(iscript), import_time=import_time ) if __name__ == '__main__': # pragma: no cover pprint(ParserModule.parse_path(sys.argv[1]).__dict__)
# This file is part of sner4 project governed by MIT license, see the LICENSE.txt file. """ parsers to import from agent outputs to storage """ import json import re import sys from datetime import datetime from pathlib import Path from pprint import pprint from time import time from zipfile import ZipFile import libnmap.parser from sner.lib import file_from_zip, is_zip from sner.server.parser import ParsedHost, ParsedItemsDb, ParsedNote, ParsedService, ParserBase class ParserModule(ParserBase): # pylint: disable=too-few-public-methods """nmap xml output parser""" ARCHIVE_PATHS = r'output\.xml|output6\.xml' @classmethod def parse_path(cls, path): """parse data from path""" if is_zip(path): pidb = ParsedItemsDb() with ZipFile(path) as fzip: for fname in filter(lambda x: re.match(cls.ARCHIVE_PATHS, x), fzip.namelist()): pidb += cls._parse_data(file_from_zip(path, fname).decode('utf-8')) return pidb return cls._parse_data(Path(path).read_text()) @classmethod def _parse_data(cls, data): """parse raw string data""" report = libnmap.parser.NmapParser.parse_fromstring(data) pidb = ParsedItemsDb() for ihost in report.hosts: host, cpe_note = cls._parse_host(ihost) via_target = ihost.user_target_hostname or host.address import_time = datetime.fromtimestamp(int(ihost.starttime or time())) pidb.hosts.upsert(host) if cpe_note: pidb.notes.upsert(cpe_note) for iscript in ihost.scripts_results: note = cls._parse_note(iscript, host.handle, None, via_target, import_time) pidb.notes.upsert(note) for iservice in ihost.services: service = cls._parse_service(iservice, host.handle, import_time) pidb.services.upsert(service) if iservice.cpelist: note = ParsedNote( host_handle=host.handle, service_handle=service.handle, via_target=via_target, xtype='cpe', data=json.dumps([x.cpestring for x in iservice.cpelist]), import_time=import_time ) pidb.notes.upsert(note) for iscript in iservice.scripts_results: note = cls._parse_note(iscript, host.handle, service.handle, via_target, import_time) pidb.notes.upsert(note) return pidb @staticmethod def _parse_host(ihost): """parse host""" host = ParsedHost(address=ihost.address) cpe_note = None if ihost.hostnames: host.hostnames = list(set(ihost.hostnames)) if not host.hostname: host.hostname = host.hostnames[0] for osmatch in ihost.os_match_probabilities(): if osmatch.accuracy == 100: host.os = osmatch.name cpe_note = ParsedNote(host_handle=host.handle, xtype='cpe', data=json.dumps(osmatch.get_cpe())) return host, cpe_note @staticmethod def _parse_service(iservice, host_handle, import_time): """parse service""" service = ParsedService( host_handle=host_handle, proto=iservice.protocol, port=iservice.port, state=f'{iservice.state}:{iservice.reason}', import_time=import_time ) if iservice.service: service.name = iservice.service if iservice.banner: service.info = iservice.banner return service @staticmethod def _parse_note(iscript, host_handle, service_handle, via_target, import_time): """parse note""" return ParsedNote( host_handle=host_handle, service_handle=service_handle, via_target=via_target, xtype=f'nmap.{iscript["id"]}', data=json.dumps(iscript), import_time=import_time ) if __name__ == '__main__': # pragma: no cover pprint(ParserModule.parse_path(sys.argv[1]).__dict__)
import re from typing import List, \ Union, \ Set from common.file_reader import FileReader def _find_bags_colors(color: str, in_bag: Union[str, None], rules: dict, path: List[str] = []) -> Union[int, Set]: if in_bag is None: total = set() for bag_option in set(rules): path_new = path + [bag_option] find = _find_bags_colors(color=color, in_bag=bag_option, path=path_new, rules=rules) total = total.union(find) return len(total) if in_bag in rules: direct_colors = set(rules[in_bag]) if len(direct_colors): total = set() for bag_option in direct_colors: path_new = path + [bag_option] result = _find_bags_colors(color=color, in_bag=bag_option, path=path_new, rules=rules) total = total.union(result) return total else: if color in path: return set(path[0:path.index(color)]) else: return set() else: if color in path: return set(path[0:path.index(color)]) else: return set() def count_bags_options(my_color: str, rules: List[str]) -> int: parsed_rules = parse_rules(rules) return _find_bags_colors(color=my_color, in_bag=None, rules=parsed_rules) def _count_required_bags(my_color: str, rules: dict): if my_color not in rules: return 1 result = 0 for (key,value) in rules[my_color].items(): count = _count_required_bags(key, rules) result += (value + value * count) return result def count_required_bags(my_color: str, rules: List[str]) -> int: parsed_rules = parse_rules(rules) return _count_required_bags(my_color=my_color, rules=parsed_rules) def parse_rules(rules: List[str]) -> dict: parsed_rules = {} for rule in rules: bags_under_condition, rules_for_bag = _parse_rule(rule) parsed_rules[bags_under_condition] = rules_for_bag return parsed_rules def _parse_rule(rule) -> (str, dict): bag_color_regex = '[a-zA-Z]+ [a-zA-Z]+' bags_under_condition = re.search(f"({bag_color_regex})", rule).group(1) no_rules_for_bag = re.search('contain no other bags.$', rule) rules_for_bag = {} if no_rules_for_bag: pass else: bag_rules = re.findall(f"([0-9]) ({bag_color_regex})", rule) for bag_rule in bag_rules: quantity = int(bag_rule[0]) color = bag_rule[1] rules_for_bag[color] = quantity return bags_under_condition, rules_for_bag if __name__ == '__main__': file_reader = FileReader('./input') rules = file_reader.to_str_list() print(rules) print(f"Nombre de sacs possibles 💼 - {count_bags_options("shiny gold", rules)}") print(f"Nombre de sacs nécessaires 💼 - {count_required_bags("shiny gold", rules)}")
import re from typing import List, \ Union, \ Set from common.file_reader import FileReader def _find_bags_colors(color: str, in_bag: Union[str, None], rules: dict, path: List[str] = []) -> Union[int, Set]: if in_bag is None: total = set() for bag_option in set(rules): path_new = path + [bag_option] find = _find_bags_colors(color=color, in_bag=bag_option, path=path_new, rules=rules) total = total.union(find) return len(total) if in_bag in rules: direct_colors = set(rules[in_bag]) if len(direct_colors): total = set() for bag_option in direct_colors: path_new = path + [bag_option] result = _find_bags_colors(color=color, in_bag=bag_option, path=path_new, rules=rules) total = total.union(result) return total else: if color in path: return set(path[0:path.index(color)]) else: return set() else: if color in path: return set(path[0:path.index(color)]) else: return set() def count_bags_options(my_color: str, rules: List[str]) -> int: parsed_rules = parse_rules(rules) return _find_bags_colors(color=my_color, in_bag=None, rules=parsed_rules) def _count_required_bags(my_color: str, rules: dict): if my_color not in rules: return 1 result = 0 for (key,value) in rules[my_color].items(): count = _count_required_bags(key, rules) result += (value + value * count) return result def count_required_bags(my_color: str, rules: List[str]) -> int: parsed_rules = parse_rules(rules) return _count_required_bags(my_color=my_color, rules=parsed_rules) def parse_rules(rules: List[str]) -> dict: parsed_rules = {} for rule in rules: bags_under_condition, rules_for_bag = _parse_rule(rule) parsed_rules[bags_under_condition] = rules_for_bag return parsed_rules def _parse_rule(rule) -> (str, dict): bag_color_regex = '[a-zA-Z]+ [a-zA-Z]+' bags_under_condition = re.search(f"({bag_color_regex})", rule).group(1) no_rules_for_bag = re.search('contain no other bags.$', rule) rules_for_bag = {} if no_rules_for_bag: pass else: bag_rules = re.findall(f"([0-9]) ({bag_color_regex})", rule) for bag_rule in bag_rules: quantity = int(bag_rule[0]) color = bag_rule[1] rules_for_bag[color] = quantity return bags_under_condition, rules_for_bag if __name__ == '__main__': file_reader = FileReader('./input') rules = file_reader.to_str_list() print(rules) print(f"Nombre de sacs possibles 💼 - {count_bags_options('shiny gold', rules)}") print(f"Nombre de sacs nécessaires 💼 - {count_required_bags('shiny gold', rules)}")
# A python class for the Delcom USBLMP 904x multi-color visual signal indicator. This # has been tested with the 904007-SB but should work with most of the other # indicators. # # Requires the Signal 11 HIDAPI and cython-hidapi. # # Copyright (c) 2019 Aaron Linville <aaron@linville.org> import hid vendor_id = 0x0FC5 product_id = 0xB080 green = 1 red = 2 blue = 4 def list(): """Lists all the Delcom USBLMP 904x devices""" for d in hid.enumerate(vendor_id, product_id): for key in sorted(d.keys()): print(f"{key} : {d[key]}") print() class DelcomMultiColorIndicator: """A python class for the Delcom USBLMP 904x Multi-color Visual Signal Indicators.""" # Command Packet Format: # Byte 0 - Major Command # Byte 1 - Minor Command # Byte 2 - Data LSB # Byte 3 - Data MSB # Bytes 4-8 - Data HID # Bytes 8-16 - Data External (Optional) def __init__(self): """Constructs and attempts to attach to any available Delcom 904x Multi-Color Visual Indicator.""" try: self.h = hid.device() self.h.open(vendor_id, product_id) # Vendor Id, Product Id self.reset() except OSError as e: print(f"Failed: {e}") raise def info(self): """Prints out all the USB, firmware and current configuration on the attached multi-color indicator.""" print(f"USB Manufacturer Id: {self.h.get_manufacturer_string()}") print(f"USB Product Id: {self.h.get_product_string()}") print(f"USB Serial Id: {self.h.get_serial_number_string()}") data = self.h.get_feature_report(10, 8) print("Serial: %s" % (data[3] << 32 | data[2] << 16 | data[1] << 8 | data[0])) print(f"Firmware version: {data[5]}") print(f"Firmware date: {data[7] + 2000}, {data[6]}, {data[5]}") data = self.h.get_feature_report(100, 4) print("Port 0:", data[0]) print("Port 1:", data[1]) str = [] if ~data[1] & green: str.append("Green") if ~data[1] & red: str.append("Red") if ~data[1] & blue: str.append("Blue/Yellow") if data[1] == 255: str.append("None") print(f" Enabled colors: {",".join(str)}") print("Port 1 Clock Enable Status:", data[2]) print("Port 2:", data[3]) def reset(self): """Turns off all the LEDs and Buzzers.""" self.set_color(0) self.disable_buzzer() def set_color(self, colors, flashing=False, cycle_time=0): """Enables the colors with optional flashing or color cycling.""" self.h.write([101, 12, colors, 0xFF]) # If flash is not enabled, ensure it's disabled. if flashing or cycle_time > 0: self.h.write([101, 20, ~colors & 0xFF, colors]) else: self.h.write([101, 20, 0xF, 0x0]) if cycle_time > 0: # Syncronize clock generation delay = 0 off_time = bin(colors).count("1") * cycle_time - cycle_time if colors & green: # print(f"Cycle green: {cycle_time}, {delay}, {off_time}") self.__set_duty_cycle(0, cycle_time, off_time) self.__set_phase_delay(0, delay) delay += cycle_time if colors & red: # print(f"Cycle red: {cycle_time}, {delay}, {off_time}") self.__set_duty_cycle(1, cycle_time, off_time) self.__set_phase_delay(1, delay) delay += cycle_time if colors & blue: # print(f"Cycle blue: {cycle_time}, {delay}, {off_time}") self.__set_duty_cycle(2, cycle_time, off_time) self.__set_phase_delay(2, delay) delay += cycle_time self.h.write( [101, 25, colors, 0] # Selected on pins ) # No initial phase delay else: self.h.write([101, 25, 0xF, 0]) # All pins # No initial phase delay def __set_duty_cycle(self, color_pin, on_time, off_time): """Internal method to set the duty cycle on a pin, used for color cycling.""" self.h.write( [ 101, 21 + color_pin, # Pin to set duty cycle on off_time, # High duty cycle on_time, ] ) # Low duty cycle def __set_phase_delay(self, color_pin, delay_time): """Internal method to set the initial delay on a pin, used for color cycling.""" self.h.write( [ 101, 26 + color_pin, # Pin to delay turning on delay_time, # High duty cycle 0x0, ] ) def set_intensity(self, intensity, colors): """Sets the intensity of a color using pulse-width modulation (0-100 %).""" self.h.write([101, 34, colors, intensity]) def disable_buzzer(self): """Disables the buzzer.""" self.h.write( [ 102, 70, 0x0, # Disable Buzzer 0x0, # Frequency 0x0, 0x0, 0x0, 0x0, 0, 0, # Duty cycle (on), 50 ms units 0, # Duty cycle (off), 50 ms units 0x0, 0x0, 0x0, 0x0, 0x0, ] ) def enable_buzzer(self, freq, duty_on, duty_off, repeat): """Enables the buzzer with a duty cycle and repetition. Frequency is currently hardcoded.""" self.h.write( [ 102, 70, 0x1, # Enable Buzzer 0x4, # Frequency 0x0, 0x0, 0x0, 0x0, repeat, int(duty_on / 50), # Duty cycle (on), 50 ms units int(duty_off / 50), # Duty cycle (off), 50 ms units 0x0, 0x0, 0x0, 0x0, 0x0, ] )
# A python class for the Delcom USBLMP 904x multi-color visual signal indicator. This # has been tested with the 904007-SB but should work with most of the other # indicators. # # Requires the Signal 11 HIDAPI and cython-hidapi. # # Copyright (c) 2019 Aaron Linville <aaron@linville.org> import hid vendor_id = 0x0FC5 product_id = 0xB080 green = 1 red = 2 blue = 4 def list(): """Lists all the Delcom USBLMP 904x devices""" for d in hid.enumerate(vendor_id, product_id): for key in sorted(d.keys()): print(f"{key} : {d[key]}") print() class DelcomMultiColorIndicator: """A python class for the Delcom USBLMP 904x Multi-color Visual Signal Indicators.""" # Command Packet Format: # Byte 0 - Major Command # Byte 1 - Minor Command # Byte 2 - Data LSB # Byte 3 - Data MSB # Bytes 4-8 - Data HID # Bytes 8-16 - Data External (Optional) def __init__(self): """Constructs and attempts to attach to any available Delcom 904x Multi-Color Visual Indicator.""" try: self.h = hid.device() self.h.open(vendor_id, product_id) # Vendor Id, Product Id self.reset() except OSError as e: print(f"Failed: {e}") raise def info(self): """Prints out all the USB, firmware and current configuration on the attached multi-color indicator.""" print(f"USB Manufacturer Id: {self.h.get_manufacturer_string()}") print(f"USB Product Id: {self.h.get_product_string()}") print(f"USB Serial Id: {self.h.get_serial_number_string()}") data = self.h.get_feature_report(10, 8) print("Serial: %s" % (data[3] << 32 | data[2] << 16 | data[1] << 8 | data[0])) print(f"Firmware version: {data[5]}") print(f"Firmware date: {data[7] + 2000}, {data[6]}, {data[5]}") data = self.h.get_feature_report(100, 4) print("Port 0:", data[0]) print("Port 1:", data[1]) str = [] if ~data[1] & green: str.append("Green") if ~data[1] & red: str.append("Red") if ~data[1] & blue: str.append("Blue/Yellow") if data[1] == 255: str.append("None") print(f" Enabled colors: {','.join(str)}") print("Port 1 Clock Enable Status:", data[2]) print("Port 2:", data[3]) def reset(self): """Turns off all the LEDs and Buzzers.""" self.set_color(0) self.disable_buzzer() def set_color(self, colors, flashing=False, cycle_time=0): """Enables the colors with optional flashing or color cycling.""" self.h.write([101, 12, colors, 0xFF]) # If flash is not enabled, ensure it's disabled. if flashing or cycle_time > 0: self.h.write([101, 20, ~colors & 0xFF, colors]) else: self.h.write([101, 20, 0xF, 0x0]) if cycle_time > 0: # Syncronize clock generation delay = 0 off_time = bin(colors).count("1") * cycle_time - cycle_time if colors & green: # print(f"Cycle green: {cycle_time}, {delay}, {off_time}") self.__set_duty_cycle(0, cycle_time, off_time) self.__set_phase_delay(0, delay) delay += cycle_time if colors & red: # print(f"Cycle red: {cycle_time}, {delay}, {off_time}") self.__set_duty_cycle(1, cycle_time, off_time) self.__set_phase_delay(1, delay) delay += cycle_time if colors & blue: # print(f"Cycle blue: {cycle_time}, {delay}, {off_time}") self.__set_duty_cycle(2, cycle_time, off_time) self.__set_phase_delay(2, delay) delay += cycle_time self.h.write( [101, 25, colors, 0] # Selected on pins ) # No initial phase delay else: self.h.write([101, 25, 0xF, 0]) # All pins # No initial phase delay def __set_duty_cycle(self, color_pin, on_time, off_time): """Internal method to set the duty cycle on a pin, used for color cycling.""" self.h.write( [ 101, 21 + color_pin, # Pin to set duty cycle on off_time, # High duty cycle on_time, ] ) # Low duty cycle def __set_phase_delay(self, color_pin, delay_time): """Internal method to set the initial delay on a pin, used for color cycling.""" self.h.write( [ 101, 26 + color_pin, # Pin to delay turning on delay_time, # High duty cycle 0x0, ] ) def set_intensity(self, intensity, colors): """Sets the intensity of a color using pulse-width modulation (0-100 %).""" self.h.write([101, 34, colors, intensity]) def disable_buzzer(self): """Disables the buzzer.""" self.h.write( [ 102, 70, 0x0, # Disable Buzzer 0x0, # Frequency 0x0, 0x0, 0x0, 0x0, 0, 0, # Duty cycle (on), 50 ms units 0, # Duty cycle (off), 50 ms units 0x0, 0x0, 0x0, 0x0, 0x0, ] ) def enable_buzzer(self, freq, duty_on, duty_off, repeat): """Enables the buzzer with a duty cycle and repetition. Frequency is currently hardcoded.""" self.h.write( [ 102, 70, 0x1, # Enable Buzzer 0x4, # Frequency 0x0, 0x0, 0x0, 0x0, repeat, int(duty_on / 50), # Duty cycle (on), 50 ms units int(duty_off / 50), # Duty cycle (off), 50 ms units 0x0, 0x0, 0x0, 0x0, 0x0, ] )
""" This script directly applies our method to video, finding dense correspondences across time in an input video. This works by applying GANgealing per-frame without using any temporal information. """ import torch import numpy as np import math from datasets import img_dataloader from prepare_data import nchw_center_crop from models import SpatialTransformer from utils.vis_tools.helpers import images2grid, save_video, save_image, load_dense_label, load_cluster_dense_labels, load_pil, splat_points, get_plotly_colors, get_colorscale from utils.distributed import setup_distributed, primary, all_gather from applications import base_eval_argparse, load_stn, determine_flips from tqdm import tqdm from glob import glob import os def grid2vid(list_of_grids): # Takes a list of (H, W, C) images (or image grids), runs an all_gather to collect across GPUs and then # prepares the images to be saved as a video by the save_video function. frames = torch.tensor(np.stack(list_of_grids), device='cuda') frames = gather_and_permute(frames) frames = [frame for frame in frames.cpu().numpy()] return frames def gather_and_permute(x): # This function does all_gather but takes into account the stride of the data created by the distributed # data sampler in PyTorch. x = all_gather(x, cat=False).transpose(1, 0) x = x.reshape(-1, *x.size()[2:]) return x def create_output_folder(args, clustering=False): video_path = f'{args.out}/video_{os.path.basename(os.path.normpath(args.real_data_path))}' if clustering: if isinstance(args.cluster, list): # visualize multiple clusters simultaneously video_path = f'{video_path}_{''.join([str(ix) for ix in args.cluster])}' elif isinstance(args.cluster, int): # visualize just one cluster video_path = f'{video_path}_{args.cluster}' if primary() and args.save_frames: os.makedirs(f'{video_path}/frames', exist_ok=True) os.makedirs(f'{video_path}/congealing_frames', exist_ok=True) elif primary(): os.makedirs(f'{video_path}', exist_ok=True) return video_path def create_average_image_vis(args, points_per_cluster, video_path, nrow): labeled_average_images = [] for cluster in range(args.num_heads): # expects average images are named, e.g., "cat_average_cluster0.png", "cat_average_cluster1.png", etc. args.average_path = args.average_path.replace(f'cluster{max(cluster - 1, 0)}', f'cluster{cluster}') average_image = load_pil(args.average_path, resolution=args.resolution) labeled_average_image = splat_points(average_image, points_per_cluster[cluster].float(), sigma=args.sigma, opacity=args.opacity, colorscale=get_colorscale(cluster)) labeled_average_images.append(labeled_average_image) labeled_average_images = torch.cat(labeled_average_images, 0) # (K, C, H, W) save_image(labeled_average_images, f'{video_path}/labeled_averages.png', normalize=True, range=(-1, 1), nrow=nrow) return labeled_average_images def number_of_clusters_annotated(path): # This function checks how many clusters have average congealed images saved to disk. path = path.rstrip('/') filename, extension = os.path.splitext(path) if not filename.endswith(f'cluster0'): num_annos = 1 else: num_annos = len(glob(f'{filename[:-1]}*{extension}')) return num_annos @torch.inference_mode() def run_gangealing_on_video(args, t, classifier): # Step (0): Set some visualization hyperparameters and create results directory: alpha = 0.2 clustering = args.clustering video_path = create_output_folder(args, clustering) # Construct dataloader: loader = img_dataloader(args.real_data_path, resolution=args.real_size, shuffle=False, batch_size=args.batch, distributed=args.distributed, infinite=False, drop_last=False, return_indices=True) num_total = len(loader.dataset) num_clusters = args.num_heads if clustering else 1 nrow = int(math.sqrt(num_clusters)) # Step (1): Load the points (and optionally colors) that we want to propagate to the input video: if clustering: points_per_cluster, colors_per_cluster, alpha_channels_per_cluster = \ load_cluster_dense_labels(args.label_path, args.num_heads, args.resolution, args.objects) if args.average_path is not None: # Optionally create a visualization of all the clusters' dense labels: labeled_average_images = create_average_image_vis(args, points_per_cluster, video_path, nrow) labeled_average_images = labeled_average_images.unsqueeze(0) # (1, K, C, H, W) inactive_averages = labeled_average_images * alpha - (1 - alpha) # This can be used later to visualize cluster selection C, H, W = labeled_average_images.size()[2:] points_per_cluster = [SpatialTransformer.normalize(points, args.real_size, args.resolution) for points in points_per_cluster] else: # unimodal GANgealing: points, colors, alpha_channels = load_dense_label(args.label_path, args.resolution, args.objects) points = SpatialTransformer.normalize(points, args.real_size, args.resolution) # Step (2): Pre-process the RGB colors and alpha-channel values that we want to propagate to the input video: if clustering and args.cluster is not None: mode = 'fixed_cluster' # clustering, always propagate from the specified cluster(s) if not args.objects: colors_per_cluster = [get_plotly_colors(points_per_cluster[cluster].size(1), get_colorscale(cluster)) for cluster in range(args.num_heads)] colors = [colors_per_cluster[cluster] for cluster in args.cluster] colors = torch.cat(colors, 1) alpha_channels = [alpha_channels_per_cluster[cluster] for cluster in args.cluster] alpha_channels = torch.cat(alpha_channels, 1) elif clustering: mode = 'predict_cluster' # clustering, but only propagate based on the current predicted cluster if not args.objects: colors = colors_per_cluster = [get_plotly_colors(points.size(1), get_colorscale(cluster)) for cluster, points in enumerate(points_per_cluster)] alpha_channels = alpha_channels_per_cluster else: mode = 'unimodal' # no clustering (num_heads == 1) if not args.objects: colors = get_plotly_colors(points.size(1), get_colorscale(None)) # Step (3): Prepare some variables if we want to display the label we're propagating over the congealed video if args.overlay_congealed: if clustering: congealed_points = [SpatialTransformer.unnormalize(points, args.real_size, args.real_size) for points in points_per_cluster] congealed_colors = colors_per_cluster congealed_alpha_channels = alpha_channels_per_cluster else: congealed_points = [SpatialTransformer.unnormalize(points, args.real_size, args.real_size)] congealed_colors = [colors] congealed_alpha_channels = [alpha_channels] # Step (4): Start processing the input video. # video_frames will be a list of (N, C, H, W) frames: the augmented reality video with objects/points displayed # congealing_frames will be a list of (N, C, H, W) frames: the congealed video (i.e., STN(video)) # [clustering only] average_frames will be a list of (N, C, H, W) frames: a video that shows which cluster(s) is/are active at each frame video_frames, congealing_frames, average_frames = [], [], [] pbar = tqdm(loader) if primary() else loader for (batch, batch_indices) in pbar: N = batch.size(0) batch = batch.to('cuda') # Handle cropping if needed: frames_are_non_square = batch.size(2) != batch.size(3) original_batch = batch if frames_are_non_square: batch, (y_start, x_start) = nchw_center_crop(batch) # perform a center crop to make frames square # Step (4.1) Propagate correspondences to the next batch of video frames: if mode == 'unimodal' or mode == 'predict_cluster': batch_flipped, flip_indices, warp_policy, active_cluster_ix = \ determine_flips(args, t, classifier, batch, cluster=args.cluster, return_cluster_assignments=True) if clustering: points_in = points_per_cluster[active_cluster_ix.item()] else: # mode == 'unimodal' points_in = points.repeat(N, 1, 1) # Perform the actual propagation: propagated_points = t.uncongeal_points(batch_flipped, points_in, normalize_input_points=False, # already normalized above warp_policy=warp_policy, padding_mode=args.padding_mode, iters=args.iters) # Flip points where necessary: propagated_points[:, :, 0] = torch.where(flip_indices.view(-1, 1), args.real_size - 1 - propagated_points[:, :, 0], propagated_points[:, :, 0]) else: # mode == 'fixed_cluster' # Here we need to iterate over every cluster we want to visualize so we can propagate points # from each individual cluster to the video frame(s): propagated_points, active_cluster_ix = [], [] for cluster in args.cluster: batch_flipped, flip_indices, warp_policy, active_cluster_c = \ determine_flips(args, t, classifier, batch, cluster=cluster, return_cluster_assignments=True) # Perform the actual propagation: points_in_c = points_per_cluster[cluster].repeat(N, 1, 1) propagated_points_c = t.uncongeal_points(batch_flipped, points_in_c, normalize_input_points=False, # already normalized above warp_policy=warp_policy, padding_mode=args.padding_mode, iters=args.iters) # Flip points where necessary: propagated_points_c[:, :, 0] = torch.where(flip_indices.view(-1, 1), args.real_size - 1 - propagated_points_c[:, :, 0], propagated_points_c[:, :, 0]) propagated_points.append(propagated_points_c) active_cluster_ix.append(active_cluster_c) propagated_points = torch.cat(propagated_points, 1) active_cluster_ix = torch.cat(active_cluster_ix, 0) # If cropping was performed, we need to adjust our coordinate system to overlay points correctly # in the original, uncropped video: if frames_are_non_square: propagated_points[:, :, 0] += x_start propagated_points[:, :, 1] += y_start # Select the colorscale for visualization: if mode == 'unimodal' or mode == 'fixed_cluster': colors_in = colors.repeat(N, 1, 1) alpha_channels_in = alpha_channels.repeat(N, 1, 1) else: # predict_cluster code path assumes batch size is 1 assert active_cluster_ix.size(0) == 1 colors_in = colors[active_cluster_ix.item()] alpha_channels_in = alpha_channels[active_cluster_ix.item()] video_frame = splat_points(original_batch, propagated_points, sigma=args.sigma, opacity=args.opacity, colors=colors_in, alpha_channel=alpha_channels_in, blend_alg=args.blend_alg) if args.save_frames: for frame, index in zip(video_frame, batch_indices): fn = f'{video_path}/frames/{index.item()}.png' save_image(frame, fn, normalize=True, range=(-1, 1), padding=0) else: video_frames.append(video_frame) # Step (4.2) Visualize the congealed video (STN(video)): if clustering: batch_flipped, warp_policy = classifier.run_flip_cartesian(batch) congealed = t(batch_flipped, output_resolution=args.real_size, warp_policy=warp_policy, unfold=clustering, padding_mode=args.padding_mode, iters=args.iters) # (N, K, C, H, W) or (N, C, H, W) if not clustering: congealed = congealed.unsqueeze(1) # (N, 1, C, H, W) if args.overlay_congealed: # Optionally overlay points on the congealed video frames: for cluster in range(num_clusters): congealed[:, cluster] = splat_points(congealed[:, cluster], congealed_points[cluster].repeat(N, 1, 1), sigma=args.sigma, opacity=args.opacity, colors=congealed_colors[cluster].repeat(N, 1, 1), alpha_channel=congealed_alpha_channels[cluster].repeat(N, 1, 1)) # This inactive_clusters stuff below is only relevant for clustering models (highlights the currently active cluster(s)): inactive_clusters = congealed * alpha - (1 - alpha) # -1 corresponds to black active_cluster_ix = active_cluster_ix.clamp(max=num_clusters - 1) one_hot_cluster = torch.eye(num_clusters, device='cuda')[active_cluster_ix].view(N, -1, num_clusters, 1, 1, 1).transpose(1, 0).sum(dim=0).bool() congealed = torch.where(one_hot_cluster, congealed, inactive_clusters) if args.save_frames: for frame, index in zip(congealed, batch_indices): fn = f'{video_path}/congealing_frames/{index.item()}.png' save_image(frame, fn, normalize=True, range=(-1, 1), pad_value=-1, nrow=nrow) else: congealed = [ images2grid(congealed_i, normalize=True, range=(-1, 1), pad_value=-1, nrow=nrow) for congealed_i in congealed] congealing_frames.extend(congealed) # Step (4.3) For clustering models, show which cluster(s) is/are currently active: if clustering and args.average_path is not None: current_cluster_average = torch.where(one_hot_cluster, labeled_average_images.expand(N, args.num_heads, C, H, W), inactive_averages.expand(N, args.num_heads, C, H, W)) average = [ images2grid(average_i, normalize=True, range=(-1, 1), pad_value=-1, nrow=nrow) for average_i in current_cluster_average] average_frames.extend(average) # Step (5): Save the final mp4 videos: if primary() and args.save_frames: # Load saved frames from disk: video_frames = [f'{video_path}/frames/{i}.png' for i in range(num_total)] congealing_frames = [f'{video_path}/congealing_frames/{i}.png' for i in range(num_total)] save_video(video_frames, args.fps, f'{video_path}/propagated.mp4', filenames=True) save_video(congealing_frames, args.fps, f'{video_path}/congealed.mp4', filenames=True) elif not args.save_frames: video_frames = gather_and_permute(torch.cat(video_frames, 0))[:num_total] if primary(): save_video(video_frames, args.fps, f'{video_path}/propagated.mp4', input_is_tensor=True) congealed_frames = grid2vid(congealing_frames)[:num_total] if primary(): save_video(congealed_frames, args.fps, f'{video_path}/congealed.mp4', input_is_tensor=False) if len(average_frames) > 0: average_frames = grid2vid(average_frames)[:num_total] if primary(): save_video(average_frames, args.fps, f'{video_path}/average.mp4') if primary(): print('Done.') if __name__ == '__main__': parser = base_eval_argparse() # Visualization hyperparameters: parser.add_argument("--cluster", default=None, type=int, nargs='+', help='If using a clustering model, OPTIONALLY select the cluster(s) to create visualizations ' 'for. If more than one is specified, tracks will be created for all specified clusters. ' 'If you leave this as None, the cluster will be predicted dynamically for each frame.') parser.add_argument("--label_path", type=str, help='Path to a dense label in congealed space, formatted as ' 'an RGBA image', required=True) parser.add_argument("--average_path", type=str, default=None, help='Path to an average image for clustering models. ' 'This should end in "cluster0.png" if specified.') parser.add_argument("--save_frames", action='store_true', help='If specified, saves individual frames to disk as pngs ' 'in addition to making an mp4. This takes much less ' 'GPU memory but is slower.') parser.add_argument("--resolution", type=int, default=128, help='Resolution at which to load label_path. Making this ' 'larger will propagate more pixels (i.e., find ' 'denser correspondences)') parser.add_argument("--blend_alg", type=str, choices=['alpha', 'laplacian', 'laplacian_light'], default='alpha', help='The blending algorithm to use.') parser.add_argument("--fps", type=int, default=60, help='FPS of saved videos') parser.add_argument("--overlay_congealed", action='store_true', help='If specified, overlays the input dense label ' 'on the congealed mp4 video') parser.add_argument("--objects", action='store_true', help='If specified, loads RGB values from the label ' '(object propagation). Otherwise, an RGB colorscale will ' 'be created.') parser.add_argument("--sigma", type=float, default=1.2, help='Size of the propagated points overlaid on the video') parser.add_argument("--opacity", type=float, default=0.7, help='Opacity of the propagated points overlaid on the video') parser.add_argument("--out", type=str, default='visuals', help='directory where created videos will be saved') args = parser.parse_args() os.makedirs(args.out, exist_ok=True) args.distributed = setup_distributed() # The classifier is optional and only used with clustering models: t_ema, classifier = load_stn(args, load_classifier=True) if args.num_heads == 1: args.clustering = False else: # Only applies to clustering models: if args.average_path is not None: assert 'cluster0' in args.average_path, 'if supplying an average_image for clustering models, only select ' \ 'the path ending in "cluster0". The other average images will be ' \ 'automatically loaded.' assert number_of_clusters_annotated(args.average_path) == args.num_heads if number_of_clusters_annotated(args.label_path) == 1: # This is a special code path that allows you to do augmented reality from just a single cluster. # Usually, the clustering models require that all clusters have annotated average congealed # images, but this path requires only a single cluster to be annotated. args.clustering = False assert args.average_path is None assert args.cluster is not None and len(args.cluster) == 1 args.cluster = args.cluster[0] else: # The usual clustering code path: args.clustering = True args.batch = 1 # Different clusters may propagate different numbers of points so batch size has to be 1 run_gangealing_on_video(args, t_ema, classifier)
""" This script directly applies our method to video, finding dense correspondences across time in an input video. This works by applying GANgealing per-frame without using any temporal information. """ import torch import numpy as np import math from datasets import img_dataloader from prepare_data import nchw_center_crop from models import SpatialTransformer from utils.vis_tools.helpers import images2grid, save_video, save_image, load_dense_label, load_cluster_dense_labels, load_pil, splat_points, get_plotly_colors, get_colorscale from utils.distributed import setup_distributed, primary, all_gather from applications import base_eval_argparse, load_stn, determine_flips from tqdm import tqdm from glob import glob import os def grid2vid(list_of_grids): # Takes a list of (H, W, C) images (or image grids), runs an all_gather to collect across GPUs and then # prepares the images to be saved as a video by the save_video function. frames = torch.tensor(np.stack(list_of_grids), device='cuda') frames = gather_and_permute(frames) frames = [frame for frame in frames.cpu().numpy()] return frames def gather_and_permute(x): # This function does all_gather but takes into account the stride of the data created by the distributed # data sampler in PyTorch. x = all_gather(x, cat=False).transpose(1, 0) x = x.reshape(-1, *x.size()[2:]) return x def create_output_folder(args, clustering=False): video_path = f'{args.out}/video_{os.path.basename(os.path.normpath(args.real_data_path))}' if clustering: if isinstance(args.cluster, list): # visualize multiple clusters simultaneously video_path = f'{video_path}_{"".join([str(ix) for ix in args.cluster])}' elif isinstance(args.cluster, int): # visualize just one cluster video_path = f'{video_path}_{args.cluster}' if primary() and args.save_frames: os.makedirs(f'{video_path}/frames', exist_ok=True) os.makedirs(f'{video_path}/congealing_frames', exist_ok=True) elif primary(): os.makedirs(f'{video_path}', exist_ok=True) return video_path def create_average_image_vis(args, points_per_cluster, video_path, nrow): labeled_average_images = [] for cluster in range(args.num_heads): # expects average images are named, e.g., "cat_average_cluster0.png", "cat_average_cluster1.png", etc. args.average_path = args.average_path.replace(f'cluster{max(cluster - 1, 0)}', f'cluster{cluster}') average_image = load_pil(args.average_path, resolution=args.resolution) labeled_average_image = splat_points(average_image, points_per_cluster[cluster].float(), sigma=args.sigma, opacity=args.opacity, colorscale=get_colorscale(cluster)) labeled_average_images.append(labeled_average_image) labeled_average_images = torch.cat(labeled_average_images, 0) # (K, C, H, W) save_image(labeled_average_images, f'{video_path}/labeled_averages.png', normalize=True, range=(-1, 1), nrow=nrow) return labeled_average_images def number_of_clusters_annotated(path): # This function checks how many clusters have average congealed images saved to disk. path = path.rstrip('/') filename, extension = os.path.splitext(path) if not filename.endswith(f'cluster0'): num_annos = 1 else: num_annos = len(glob(f'{filename[:-1]}*{extension}')) return num_annos @torch.inference_mode() def run_gangealing_on_video(args, t, classifier): # Step (0): Set some visualization hyperparameters and create results directory: alpha = 0.2 clustering = args.clustering video_path = create_output_folder(args, clustering) # Construct dataloader: loader = img_dataloader(args.real_data_path, resolution=args.real_size, shuffle=False, batch_size=args.batch, distributed=args.distributed, infinite=False, drop_last=False, return_indices=True) num_total = len(loader.dataset) num_clusters = args.num_heads if clustering else 1 nrow = int(math.sqrt(num_clusters)) # Step (1): Load the points (and optionally colors) that we want to propagate to the input video: if clustering: points_per_cluster, colors_per_cluster, alpha_channels_per_cluster = \ load_cluster_dense_labels(args.label_path, args.num_heads, args.resolution, args.objects) if args.average_path is not None: # Optionally create a visualization of all the clusters' dense labels: labeled_average_images = create_average_image_vis(args, points_per_cluster, video_path, nrow) labeled_average_images = labeled_average_images.unsqueeze(0) # (1, K, C, H, W) inactive_averages = labeled_average_images * alpha - (1 - alpha) # This can be used later to visualize cluster selection C, H, W = labeled_average_images.size()[2:] points_per_cluster = [SpatialTransformer.normalize(points, args.real_size, args.resolution) for points in points_per_cluster] else: # unimodal GANgealing: points, colors, alpha_channels = load_dense_label(args.label_path, args.resolution, args.objects) points = SpatialTransformer.normalize(points, args.real_size, args.resolution) # Step (2): Pre-process the RGB colors and alpha-channel values that we want to propagate to the input video: if clustering and args.cluster is not None: mode = 'fixed_cluster' # clustering, always propagate from the specified cluster(s) if not args.objects: colors_per_cluster = [get_plotly_colors(points_per_cluster[cluster].size(1), get_colorscale(cluster)) for cluster in range(args.num_heads)] colors = [colors_per_cluster[cluster] for cluster in args.cluster] colors = torch.cat(colors, 1) alpha_channels = [alpha_channels_per_cluster[cluster] for cluster in args.cluster] alpha_channels = torch.cat(alpha_channels, 1) elif clustering: mode = 'predict_cluster' # clustering, but only propagate based on the current predicted cluster if not args.objects: colors = colors_per_cluster = [get_plotly_colors(points.size(1), get_colorscale(cluster)) for cluster, points in enumerate(points_per_cluster)] alpha_channels = alpha_channels_per_cluster else: mode = 'unimodal' # no clustering (num_heads == 1) if not args.objects: colors = get_plotly_colors(points.size(1), get_colorscale(None)) # Step (3): Prepare some variables if we want to display the label we're propagating over the congealed video if args.overlay_congealed: if clustering: congealed_points = [SpatialTransformer.unnormalize(points, args.real_size, args.real_size) for points in points_per_cluster] congealed_colors = colors_per_cluster congealed_alpha_channels = alpha_channels_per_cluster else: congealed_points = [SpatialTransformer.unnormalize(points, args.real_size, args.real_size)] congealed_colors = [colors] congealed_alpha_channels = [alpha_channels] # Step (4): Start processing the input video. # video_frames will be a list of (N, C, H, W) frames: the augmented reality video with objects/points displayed # congealing_frames will be a list of (N, C, H, W) frames: the congealed video (i.e., STN(video)) # [clustering only] average_frames will be a list of (N, C, H, W) frames: a video that shows which cluster(s) is/are active at each frame video_frames, congealing_frames, average_frames = [], [], [] pbar = tqdm(loader) if primary() else loader for (batch, batch_indices) in pbar: N = batch.size(0) batch = batch.to('cuda') # Handle cropping if needed: frames_are_non_square = batch.size(2) != batch.size(3) original_batch = batch if frames_are_non_square: batch, (y_start, x_start) = nchw_center_crop(batch) # perform a center crop to make frames square # Step (4.1) Propagate correspondences to the next batch of video frames: if mode == 'unimodal' or mode == 'predict_cluster': batch_flipped, flip_indices, warp_policy, active_cluster_ix = \ determine_flips(args, t, classifier, batch, cluster=args.cluster, return_cluster_assignments=True) if clustering: points_in = points_per_cluster[active_cluster_ix.item()] else: # mode == 'unimodal' points_in = points.repeat(N, 1, 1) # Perform the actual propagation: propagated_points = t.uncongeal_points(batch_flipped, points_in, normalize_input_points=False, # already normalized above warp_policy=warp_policy, padding_mode=args.padding_mode, iters=args.iters) # Flip points where necessary: propagated_points[:, :, 0] = torch.where(flip_indices.view(-1, 1), args.real_size - 1 - propagated_points[:, :, 0], propagated_points[:, :, 0]) else: # mode == 'fixed_cluster' # Here we need to iterate over every cluster we want to visualize so we can propagate points # from each individual cluster to the video frame(s): propagated_points, active_cluster_ix = [], [] for cluster in args.cluster: batch_flipped, flip_indices, warp_policy, active_cluster_c = \ determine_flips(args, t, classifier, batch, cluster=cluster, return_cluster_assignments=True) # Perform the actual propagation: points_in_c = points_per_cluster[cluster].repeat(N, 1, 1) propagated_points_c = t.uncongeal_points(batch_flipped, points_in_c, normalize_input_points=False, # already normalized above warp_policy=warp_policy, padding_mode=args.padding_mode, iters=args.iters) # Flip points where necessary: propagated_points_c[:, :, 0] = torch.where(flip_indices.view(-1, 1), args.real_size - 1 - propagated_points_c[:, :, 0], propagated_points_c[:, :, 0]) propagated_points.append(propagated_points_c) active_cluster_ix.append(active_cluster_c) propagated_points = torch.cat(propagated_points, 1) active_cluster_ix = torch.cat(active_cluster_ix, 0) # If cropping was performed, we need to adjust our coordinate system to overlay points correctly # in the original, uncropped video: if frames_are_non_square: propagated_points[:, :, 0] += x_start propagated_points[:, :, 1] += y_start # Select the colorscale for visualization: if mode == 'unimodal' or mode == 'fixed_cluster': colors_in = colors.repeat(N, 1, 1) alpha_channels_in = alpha_channels.repeat(N, 1, 1) else: # predict_cluster code path assumes batch size is 1 assert active_cluster_ix.size(0) == 1 colors_in = colors[active_cluster_ix.item()] alpha_channels_in = alpha_channels[active_cluster_ix.item()] video_frame = splat_points(original_batch, propagated_points, sigma=args.sigma, opacity=args.opacity, colors=colors_in, alpha_channel=alpha_channels_in, blend_alg=args.blend_alg) if args.save_frames: for frame, index in zip(video_frame, batch_indices): fn = f'{video_path}/frames/{index.item()}.png' save_image(frame, fn, normalize=True, range=(-1, 1), padding=0) else: video_frames.append(video_frame) # Step (4.2) Visualize the congealed video (STN(video)): if clustering: batch_flipped, warp_policy = classifier.run_flip_cartesian(batch) congealed = t(batch_flipped, output_resolution=args.real_size, warp_policy=warp_policy, unfold=clustering, padding_mode=args.padding_mode, iters=args.iters) # (N, K, C, H, W) or (N, C, H, W) if not clustering: congealed = congealed.unsqueeze(1) # (N, 1, C, H, W) if args.overlay_congealed: # Optionally overlay points on the congealed video frames: for cluster in range(num_clusters): congealed[:, cluster] = splat_points(congealed[:, cluster], congealed_points[cluster].repeat(N, 1, 1), sigma=args.sigma, opacity=args.opacity, colors=congealed_colors[cluster].repeat(N, 1, 1), alpha_channel=congealed_alpha_channels[cluster].repeat(N, 1, 1)) # This inactive_clusters stuff below is only relevant for clustering models (highlights the currently active cluster(s)): inactive_clusters = congealed * alpha - (1 - alpha) # -1 corresponds to black active_cluster_ix = active_cluster_ix.clamp(max=num_clusters - 1) one_hot_cluster = torch.eye(num_clusters, device='cuda')[active_cluster_ix].view(N, -1, num_clusters, 1, 1, 1).transpose(1, 0).sum(dim=0).bool() congealed = torch.where(one_hot_cluster, congealed, inactive_clusters) if args.save_frames: for frame, index in zip(congealed, batch_indices): fn = f'{video_path}/congealing_frames/{index.item()}.png' save_image(frame, fn, normalize=True, range=(-1, 1), pad_value=-1, nrow=nrow) else: congealed = [ images2grid(congealed_i, normalize=True, range=(-1, 1), pad_value=-1, nrow=nrow) for congealed_i in congealed] congealing_frames.extend(congealed) # Step (4.3) For clustering models, show which cluster(s) is/are currently active: if clustering and args.average_path is not None: current_cluster_average = torch.where(one_hot_cluster, labeled_average_images.expand(N, args.num_heads, C, H, W), inactive_averages.expand(N, args.num_heads, C, H, W)) average = [ images2grid(average_i, normalize=True, range=(-1, 1), pad_value=-1, nrow=nrow) for average_i in current_cluster_average] average_frames.extend(average) # Step (5): Save the final mp4 videos: if primary() and args.save_frames: # Load saved frames from disk: video_frames = [f'{video_path}/frames/{i}.png' for i in range(num_total)] congealing_frames = [f'{video_path}/congealing_frames/{i}.png' for i in range(num_total)] save_video(video_frames, args.fps, f'{video_path}/propagated.mp4', filenames=True) save_video(congealing_frames, args.fps, f'{video_path}/congealed.mp4', filenames=True) elif not args.save_frames: video_frames = gather_and_permute(torch.cat(video_frames, 0))[:num_total] if primary(): save_video(video_frames, args.fps, f'{video_path}/propagated.mp4', input_is_tensor=True) congealed_frames = grid2vid(congealing_frames)[:num_total] if primary(): save_video(congealed_frames, args.fps, f'{video_path}/congealed.mp4', input_is_tensor=False) if len(average_frames) > 0: average_frames = grid2vid(average_frames)[:num_total] if primary(): save_video(average_frames, args.fps, f'{video_path}/average.mp4') if primary(): print('Done.') if __name__ == '__main__': parser = base_eval_argparse() # Visualization hyperparameters: parser.add_argument("--cluster", default=None, type=int, nargs='+', help='If using a clustering model, OPTIONALLY select the cluster(s) to create visualizations ' 'for. If more than one is specified, tracks will be created for all specified clusters. ' 'If you leave this as None, the cluster will be predicted dynamically for each frame.') parser.add_argument("--label_path", type=str, help='Path to a dense label in congealed space, formatted as ' 'an RGBA image', required=True) parser.add_argument("--average_path", type=str, default=None, help='Path to an average image for clustering models. ' 'This should end in "cluster0.png" if specified.') parser.add_argument("--save_frames", action='store_true', help='If specified, saves individual frames to disk as pngs ' 'in addition to making an mp4. This takes much less ' 'GPU memory but is slower.') parser.add_argument("--resolution", type=int, default=128, help='Resolution at which to load label_path. Making this ' 'larger will propagate more pixels (i.e., find ' 'denser correspondences)') parser.add_argument("--blend_alg", type=str, choices=['alpha', 'laplacian', 'laplacian_light'], default='alpha', help='The blending algorithm to use.') parser.add_argument("--fps", type=int, default=60, help='FPS of saved videos') parser.add_argument("--overlay_congealed", action='store_true', help='If specified, overlays the input dense label ' 'on the congealed mp4 video') parser.add_argument("--objects", action='store_true', help='If specified, loads RGB values from the label ' '(object propagation). Otherwise, an RGB colorscale will ' 'be created.') parser.add_argument("--sigma", type=float, default=1.2, help='Size of the propagated points overlaid on the video') parser.add_argument("--opacity", type=float, default=0.7, help='Opacity of the propagated points overlaid on the video') parser.add_argument("--out", type=str, default='visuals', help='directory where created videos will be saved') args = parser.parse_args() os.makedirs(args.out, exist_ok=True) args.distributed = setup_distributed() # The classifier is optional and only used with clustering models: t_ema, classifier = load_stn(args, load_classifier=True) if args.num_heads == 1: args.clustering = False else: # Only applies to clustering models: if args.average_path is not None: assert 'cluster0' in args.average_path, 'if supplying an average_image for clustering models, only select ' \ 'the path ending in "cluster0". The other average images will be ' \ 'automatically loaded.' assert number_of_clusters_annotated(args.average_path) == args.num_heads if number_of_clusters_annotated(args.label_path) == 1: # This is a special code path that allows you to do augmented reality from just a single cluster. # Usually, the clustering models require that all clusters have annotated average congealed # images, but this path requires only a single cluster to be annotated. args.clustering = False assert args.average_path is None assert args.cluster is not None and len(args.cluster) == 1 args.cluster = args.cluster[0] else: # The usual clustering code path: args.clustering = True args.batch = 1 # Different clusters may propagate different numbers of points so batch size has to be 1 run_gangealing_on_video(args, t_ema, classifier)
from abc import ( ABCMeta, ) from concurrent.futures.thread import ( ThreadPoolExecutor, ) from contextlib import ( contextmanager, ) import csv import gzip from io import ( BytesIO, TextIOWrapper, ) from itertools import ( chain, ) import json import logging import os import random import re import sys import threading import time from typing import ( AbstractSet, Any, BinaryIO, Dict, IO, List, Mapping, Optional, Sequence, Tuple, ) import unittest from unittest import ( mock, ) import uuid from zipfile import ( ZipFile, ) import attr import chalice.cli from furl import ( furl, ) from google.cloud import ( storage, ) from google.oauth2 import ( service_account, ) from hca.dss import ( DSSClient, ) from hca.util import ( SwaggerAPIException, ) from humancellatlas.data.metadata.helpers.dss import ( download_bundle_metadata, ) from more_itertools import ( first, grouper, one, ) from openapi_spec_validator import ( validate_spec, ) import requests from azul import ( CatalogName, cache, cached_property, config, drs, ) from azul.azulclient import ( AzulClient, AzulClientNotificationError, ) from azul.drs import ( AccessMethod, ) import azul.dss from azul.es import ( ESClientFactory, ) from azul.indexer import ( BundleFQID, SourcedBundleFQID, ) from azul.indexer.index_service import ( IndexService, ) from azul.logging import ( configure_test_logging, ) from azul.modules import ( load_app_module, ) from azul.portal_service import ( PortalService, ) from azul.requests import ( requests_session_with_retry_after, ) from azul.types import ( JSON, ) from azul_test_case import ( AlwaysTearDownTestCase, AzulTestCase, ) log = logging.getLogger(__name__) # noinspection PyPep8Naming def setUpModule(): configure_test_logging(log) class IntegrationTestCase(AzulTestCase, metaclass=ABCMeta): @cached_property def azul_client(self): return AzulClient() class IndexingIntegrationTest(IntegrationTestCase, AlwaysTearDownTestCase): max_bundles = 64 num_fastq_bytes = 1024 * 1024 def setUp(self) -> None: super().setUp() self.pruning_seed = random.randint(0, sys.maxsize) @contextmanager def subTest(self, msg: Any = None, **params: Any): log.info('Beginning sub-test [%s] %r', msg, params) with super().subTest(msg, **params): try: yield except BaseException: log.info('Failed sub-test [%s] %r', msg, params) raise else: log.info('Successful sub-test [%s] %r', msg, params) def test_catalog_listing(self): response = self._check_endpoint(config.service_endpoint(), '/index/catalogs') response = json.loads(response) self.assertEqual(config.default_catalog, response['default_catalog']) self.assertIn(config.default_catalog, response['catalogs']) # Test the classification of catalogs as internal or not, other # response properties are covered by unit tests. expected = { catalog.name: catalog.is_internal for catalog in config.catalogs.values() } actual = { catalog_name: catalog['internal'] for catalog_name, catalog in response['catalogs'].items() } self.assertEqual(expected, actual) def test_indexing(self): @attr.s(auto_attribs=True, kw_only=True) class Catalog: name: CatalogName notifications: Mapping[SourcedBundleFQID, JSON] @property def num_bundles(self): return len(self.notifications) @property def bundle_fqids(self) -> AbstractSet[SourcedBundleFQID]: return self.notifications.keys() def notifications_with_duplicates(self) -> List[JSON]: num_duplicates = self.num_bundles // 2 notifications = list(self.notifications.values()) # Index some bundles again to test that we handle duplicate additions. # Note: random.choices() may pick the same element multiple times so # some notifications will end up being sent three or more times. notifications.extend(random.choices(notifications, k=num_duplicates)) return notifications def _wait_for_indexer(): self.azul_client.wait_for_indexer() # For faster modify-deploy-test cycles, set `delete` to False and run # test once. Then also set `index` to False. Subsequent runs will use # catalogs from first run. Don't commit changes to these two lines. index = True delete = True if index: self._reset_indexer() catalogs: List[Catalog] = [ Catalog(name=catalog, notifications=self._prepare_notifications(catalog) if index else {}) for catalog in config.integration_test_catalogs ] if index: for catalog in catalogs: self.azul_client.index(catalog=catalog.name, notifications=catalog.notifications_with_duplicates()) _wait_for_indexer() for catalog in catalogs: self._assert_catalog_complete(catalog=catalog.name, entity_type='files', bundle_fqids=catalog.bundle_fqids) for catalog in catalogs: self._test_manifest(catalog.name) self._test_dos_and_drs(catalog.name) self._test_repository_files(catalog.name) if index and delete: for catalog in catalogs: self.azul_client.index(catalog=catalog.name, notifications=catalog.notifications_with_duplicates(), delete=True) _wait_for_indexer() for catalog in catalogs: self._assert_catalog_empty(catalog.name) self._test_other_endpoints() def _reset_indexer(self): # While it's OK to erase the integration test catalog, the queues are # shared by all catalogs and we can't afford to trash them in a stable # deployment like production. self.azul_client.reset_indexer(catalogs=config.integration_test_catalogs, # Can't purge the queues in stable deployment as # they may contain work for non-IT catalogs. purge_queues=not config.is_stable_deployment(), delete_indices=True, create_indices=True) def _test_other_endpoints(self): service_paths = ( '/', '/openapi', '/version', '/index/summary', '/index/files/order', ) service_routes = ( (config.service_endpoint(), path) for path in service_paths ) health_endpoints = ( config.service_endpoint(), config.indexer_endpoint() ) health_paths = ( '', # default keys for lambda '/', # all keys '/basic', '/elasticsearch', '/queues', '/progress', '/api_endpoints', '/other_lambdas' ) health_routes = ( (endpoint, '/health' + path) for endpoint in health_endpoints for path in health_paths ) for endpoint, path in (*service_routes, *health_routes): with self.subTest('other_endpoints', endpoint=endpoint, path=path): self._check_endpoint(endpoint, path) def _test_manifest(self, catalog: CatalogName): for format_, validator, attempts in [ (None, self._check_manifest, 1), ('compact', self._check_manifest, 1), ('full', self._check_manifest, 3), ('terra.bdbag', self._check_terra_bdbag, 1), ('curl', self._check_curl_manifest, 1), ]: with self.subTest('manifest', catalog=catalog, format=format_, attempts=attempts): assert attempts > 0 params = dict(catalog=catalog) if format_ is not None: params['format'] = format_ for attempt in range(attempts): start = time.time() response = self._check_endpoint(config.service_endpoint(), '/manifest/files', params) log.info('Request %i/%i took %.3fs to execute.', attempt + 1, attempts, time.time() - start) validator(catalog, response) @cache def _get_one_file_uuid(self, catalog: CatalogName) -> str: filters = {'fileFormat': {'is': ['fastq.gz', 'fastq']}} response = self._check_endpoint(endpoint=config.service_endpoint(), path='/index/files', query=dict(catalog=catalog, filters=json.dumps(filters), size=1, order='asc', sort='fileSize')) hits = json.loads(response) return one(one(hits['hits'])['files'])['uuid'] def _test_dos_and_drs(self, catalog: CatalogName): if config.is_dss_enabled(catalog) and config.dss_direct_access: file_uuid = self._get_one_file_uuid(catalog) self._test_dos(catalog, file_uuid) self._test_drs(catalog, file_uuid) @cached_property def _requests(self) -> requests.Session: return requests_session_with_retry_after() def _check_endpoint(self, endpoint: str, path: str, query: Optional[Mapping[str, Any]] = None) -> bytes: query = {} if query is None else {k: str(v) for k, v in query.items()} url = furl(endpoint, path=path, query=query) return self._get_url_content(url.url) def _get_url_content(self, url: str) -> bytes: return self._get_url(url).content def _get_url(self, url: str, allow_redirects: bool = True, stream: bool = False ) -> requests.Response: log.info('GET %s', url) response = self._requests.get(url, allow_redirects=allow_redirects, stream=stream) expected_statuses = (200,) if allow_redirects else (200, 301, 302) self._assertResponseStatus(response, expected_statuses) return response def _assertResponseStatus(self, response: requests.Response, expected_statuses: Tuple[int, ...] = (200,)): # Using assert to avoid tampering with response content prematurely # (in case the response is streamed) assert response.status_code in expected_statuses, ( response.reason, next(response.iter_content(chunk_size=1024)) ) def _check_manifest(self, _catalog: CatalogName, response: bytes): self.__check_manifest(BytesIO(response), 'bundle_uuid') def _check_terra_bdbag(self, catalog: CatalogName, response: bytes): with ZipFile(BytesIO(response)) as zip_fh: data_path = os.path.join(os.path.dirname(first(zip_fh.namelist())), 'data') file_path = os.path.join(data_path, 'participants.tsv') with zip_fh.open(file_path) as file: rows = self.__check_manifest(file, 'bundle_uuid') for row in rows: # Terra doesn't allow colons in this column, but they may # exist in versions indexed by TDR self.assertNotIn(':', row['entity:participant_id']) suffix = '__file_drs_uri' prefixes = [ c[:-len(suffix)] for c in rows[0].keys() if c.endswith(suffix) ] size, drs_uri, name = min( ( int(row[prefix + '__file_size']), row[prefix + suffix], row[prefix + '__file_name'], ) for row in rows for prefix in prefixes if row[prefix + suffix] ) log.info('Resolving %r (%r) from catalog %r (%i bytes)', drs_uri, name, catalog, size) plugin = self.azul_client.repository_plugin(catalog) drs_client = plugin.drs_client() access = drs_client.get_object(drs_uri, access_method=AccessMethod.https) self.assertIsNone(access.headers) self.assertEqual('https', furl(access.url).scheme) # Try HEAD first because it's more efficient, fall back to GET if the # DRS implementations prohibits it, like Azul's DRS proxy of DSS. for method in ('HEAD', 'GET'): log.info('%s %s', method, access.url) # For DSS, any HTTP client should do but for TDR we need to use an # authenticated client. TDR does return a Bearer token in the `headers` # part of the DRS response but we know that this token is the same as # the one we're making the DRS request with. response = drs_client.http_client.request(method, access.url) if response.status != 403: break self.assertEqual(200, response.status, response.data) self.assertEqual(size, int(response.headers['Content-Length'])) def __check_manifest(self, file: IO[bytes], uuid_field_name: str) -> List[Mapping[str, str]]: text = TextIOWrapper(file) reader = csv.DictReader(text, delimiter='\t') rows = list(reader) log.info(f'Manifest contains {len(rows)} rows.') self.assertGreater(len(rows), 0) self.assertIn(uuid_field_name, reader.fieldnames) bundle_uuid = rows[0][uuid_field_name] self.assertEqual(bundle_uuid, str(uuid.UUID(bundle_uuid))) return rows def _check_curl_manifest(self, _catalog: CatalogName, response: bytes): text = TextIOWrapper(BytesIO(response)) # Skip over empty lines and curl configurations to count and verify that # all the remaining lines are pairs of 'url=' and 'output=' lines. lines = ( line for line in text if not line == '\n' and not line.startswith('--') ) num_files = 0 for url, output in grouper(lines, 2): num_files += 1 self.assertTrue(url.startswith('url=')) self.assertTrue(output.startswith('output=')) log.info(f'Manifest contains {num_files} files.') self.assertGreater(num_files, 0) def _test_repository_files(self, catalog: str): with self.subTest('repository_files', catalog=catalog): file_uuid = self._get_one_file_uuid(catalog) response = self._check_endpoint(endpoint=config.service_endpoint(), path=f'/fetch/repository/files/{file_uuid}', query=dict(catalog=catalog)) response = json.loads(response) while response['Status'] != 302: self.assertEqual(301, response['Status']) response = self._get_url(response['Location']).json() response = self._get_url(response['Location'], stream=True) self._validate_fastq_response(response) def _validate_fastq_response(self, response: requests.Response): """ Note: Response object must be obtained with stream=True https://requests.readthedocs.io/en/master/user/advanced/#body-content-workflow """ try: self._validate_fastq_content(response.raw) finally: response.close() def _test_drs(self, catalog: CatalogName, file_uuid: str): repository_plugin = self.azul_client.repository_plugin(catalog) drs = repository_plugin.drs_client() for access_method in AccessMethod: with self.subTest('drs', catalog=catalog, access_method=AccessMethod.https): log.info('Resolving file %r with DRS using %r', file_uuid, access_method) drs_uri = f'drs://{config.api_lambda_domain('service')}/{file_uuid}' access = drs.get_object(drs_uri, access_method=access_method) self.assertIsNone(access.headers) if access.method is AccessMethod.https: response = self._get_url(access.url, stream=True) self._validate_fastq_response(response) elif access.method is AccessMethod.gs: content = self._get_gs_url_content(access.url, size=self.num_fastq_bytes) self._validate_fastq_content(content) else: self.fail(access_method) def _test_dos(self, catalog: CatalogName, file_uuid: str): with self.subTest('dos', catalog=catalog): log.info('Resolving file %s with DOS', file_uuid) response = self._check_endpoint(config.service_endpoint(), path=drs.dos_object_url_path(file_uuid), query=dict(catalog=catalog)) json_data = json.loads(response)['data_object'] file_url = first(json_data['urls'])['url'] while True: with self._get_url(file_url, allow_redirects=False, stream=True) as response: # We handle redirects ourselves so we can log each request if response.status_code in (301, 302): file_url = response.headers['Location'] try: retry_after = response.headers['Retry-After'] except KeyError: pass else: time.sleep(int(retry_after)) else: break self._assertResponseStatus(response) self._validate_fastq_response(response) def _get_gs_url_content(self, url: str, size: Optional[int] = None) -> BytesIO: self.assertTrue(url.startswith('gs://')) path = os.environ['GOOGLE_APPLICATION_CREDENTIALS'] credentials = service_account.Credentials.from_service_account_file(path) storage_client = storage.Client(credentials=credentials) content = BytesIO() storage_client.download_blob_to_file(url, content, start=0, end=size) return content def _validate_fastq_content(self, content: BinaryIO): # Check signature of FASTQ file. with gzip.open(content) as buf: fastq = buf.read(self.num_fastq_bytes) lines = fastq.splitlines() # Assert first character of first and third line of file (see https://en.wikipedia.org/wiki/FASTQ_format). self.assertTrue(lines[0].startswith(b'@')) self.assertTrue(lines[2].startswith(b'+')) def _prepare_notifications(self, catalog: CatalogName) -> Dict[BundleFQID, JSON]: prefix_length = 2 prefix = ''.join([ str(random.choice('abcdef0123456789')) for _ in range(prefix_length) ]) while True: log.info('Preparing notifications for catalog %r and prefix %r.', catalog, prefix) bundle_fqids = list(chain.from_iterable( self.azul_client.list_bundles(catalog, source, prefix) for source in self.azul_client.catalog_sources(catalog) )) bundle_fqids = self._prune_test_bundles(catalog, bundle_fqids, self.max_bundles) if len(bundle_fqids) >= self.max_bundles: break elif prefix: log.info('Not enough bundles with prefix %r in catalog %r. ' 'Trying a shorter prefix.', prefix, catalog) prefix = prefix[:-1] else: log.warning('Not enough bundles in catalog %r. The test may fail.', catalog) break return { bundle_fqid: self.azul_client.synthesize_notification(catalog=catalog, prefix=prefix, bundle_fqid=bundle_fqid) for bundle_fqid in bundle_fqids } def _prune_test_bundles(self, catalog: CatalogName, bundle_fqids: Sequence[SourcedBundleFQID], max_bundles: int ) -> List[SourcedBundleFQID]: seed = self.pruning_seed log.info('Selecting %i bundles with project metadata, ' 'out of %i candidates, using random seed %i.', max_bundles, len(bundle_fqids), seed) random_ = random.Random(x=seed) # The same seed should give same random order so we need to have a # deterministic order in the input list. bundle_fqids = sorted(bundle_fqids) random_.shuffle(bundle_fqids) # Pick bundles off of the randomly ordered input until we have the # desired number of bundles with project metadata. filtered_bundle_fqids = [] for bundle_fqid in bundle_fqids: if len(filtered_bundle_fqids) < max_bundles: if self.azul_client.bundle_has_project_json(catalog, bundle_fqid): filtered_bundle_fqids.append(bundle_fqid) else: break return filtered_bundle_fqids def _assert_catalog_complete(self, catalog: CatalogName, entity_type: str, bundle_fqids: AbstractSet[SourcedBundleFQID]) -> None: fqid_by_uuid: Mapping[str, SourcedBundleFQID] = { fqid.uuid: fqid for fqid in bundle_fqids } self.assertEqual(len(bundle_fqids), len(fqid_by_uuid)) with self.subTest('catalog_complete', catalog=catalog): expected_fqids = set(self.azul_client.filter_obsolete_bundle_versions(bundle_fqids)) obsolete_fqids = bundle_fqids - expected_fqids if obsolete_fqids: log.debug('Ignoring obsolete bundle versions %r', obsolete_fqids) num_bundles = len(expected_fqids) timeout = 600 indexed_fqids = set() log.debug('Expecting bundles %s ', sorted(expected_fqids)) retries = 0 deadline = time.time() + timeout while True: hits = self._get_entities(catalog, entity_type) indexed_fqids.update( # FIXME: We should use the source from the index rather than # looking it up from the expectation. # https://github.com/DataBiosphere/azul/issues/2625 fqid_by_uuid[bundle['bundleUuid']] for hit in hits for bundle in hit.get('bundles', ()) ) log.info('Detected %i of %i bundles in %i hits for entity type %s on try #%i.', len(indexed_fqids), num_bundles, len(hits), entity_type, retries) if len(indexed_fqids) == num_bundles: log.info('Found the expected %i bundles.', num_bundles) break elif len(indexed_fqids) > num_bundles: log.error('Found %i bundles, more than the expected %i.', len(indexed_fqids), num_bundles) break elif time.time() > deadline: log.error('Only found %i of %i bundles in under %i seconds.', len(indexed_fqids), num_bundles, timeout) break else: retries += 1 time.sleep(5) self.assertSetEqual(indexed_fqids, expected_fqids) entity_types = ['files', 'projects', 'samples', 'bundles'] def _assert_catalog_empty(self, catalog: CatalogName): for entity_type in self.entity_types: with self.subTest('catalog_empty', catalog=catalog, entity_type=entity_type): hits = self._get_entities(catalog, entity_type) self.assertEqual([], [hit['entryId'] for hit in hits]) def _get_entities(self, catalog: CatalogName, entity_type): entities = [] size = 100 params = dict(catalog=catalog, size=str(size)) url = furl(url=config.service_endpoint(), path=('index', entity_type), query_params=params ).url while True: response = self._get_url(url) body = response.json() hits = body['hits'] entities.extend(hits) url = body['pagination']['next'] if url is None: break return entities def _assert_indices_exist(self, catalog: CatalogName): """ Aside from checking that all indices exist this method also asserts that we can instantiate a local ES client pointing at a real, remote ES domain. """ es_client = ESClientFactory.get() service = IndexService() for index_name in service.index_names(catalog): self.assertTrue(es_client.indices.exists(index_name)) class AzulClientIntegrationTest(IntegrationTestCase): def test_azul_client_error_handling(self): invalid_notification = {} notifications = [invalid_notification] self.assertRaises(AzulClientNotificationError, self.azul_client.index, first(config.integration_test_catalogs), notifications) @unittest.skipIf(config.is_main_deployment(), 'Test would pollute portal DB') class PortalRegistrationIntegrationTest(IntegrationTestCase, AlwaysTearDownTestCase): @cached_property def portal_service(self) -> PortalService: return PortalService() def setUp(self) -> None: self.old_db = self.portal_service.read() def test_concurrent_portal_db_crud(self): """ Use multithreading to simulate multiple users simultaneously modifying the portals database. """ n_threads = 4 n_tasks = n_threads * 5 n_ops = 5 entry_format = 'task={};op={}' def run(thread_count): for op_count in range(n_ops): mock_entry = { "portal_id": "foo", "integrations": [ { "integration_id": "bar", "entity_type": "project", "integration_type": "get", "entity_ids": ["baz"] } ], "mock-count": entry_format.format(thread_count, op_count) } self.portal_service._crud(lambda db: [*db, mock_entry]) with ThreadPoolExecutor(max_workers=n_threads) as executor: futures = [executor.submit(run, i) for i in range(n_tasks)] self.assertTrue(all(f.result() is None for f in futures)) new_db = self.portal_service.read() old_entries = [portal for portal in new_db if 'mock-count' not in portal] self.assertEqual(old_entries, self.old_db) mock_counts = [portal['mock-count'] for portal in new_db if 'mock-count' in portal] self.assertEqual(len(mock_counts), len(set(mock_counts))) self.assertEqual(set(mock_counts), { entry_format.format(i, j) for i in range(n_tasks) for j in range(n_ops) }) def tearDown(self) -> None: self.portal_service.overwrite(self.old_db) class OpenAPIIntegrationTest(AzulTestCase): def test_openapi(self): service = config.service_endpoint() response = requests.get(service + '/') self.assertEqual(response.status_code, 200) self.assertEqual(response.headers['content-type'], 'text/html') self.assertGreater(len(response.content), 0) # validate OpenAPI spec response = requests.get(service + '/openapi') response.raise_for_status() spec = response.json() validate_spec(spec) @unittest.skipIf(config.dss_endpoint is None, 'DSS endpoint is not configured') class DSSIntegrationTest(AzulTestCase): def test_patched_dss_client(self): query = { "query": { "bool": { "must_not": [ { "term": { "admin_deleted": True } } ], "must": [ { "exists": { "field": "files.project_json" } }, { "range": { "manifest.version": { "gte": "2019-04-01" } } } ] } } } self.maxDiff = None for direct in {config.dss_direct_access, False}: for replica in 'aws', 'gcp': if direct: with self._failing_s3_get_object(): dss_client = azul.dss.direct_access_client() self._test_dss_client(direct, query, dss_client, replica, fallback=True) dss_client = azul.dss.direct_access_client() self._test_dss_client(direct, query, dss_client, replica, fallback=False) else: dss_client = azul.dss.client() self._test_dss_client(direct, query, dss_client, replica, fallback=False) class SpecialError(Exception): pass def _failing_s3_get_object(self): def make_mock(**kwargs): original = kwargs['spec'] def mock_boto3_client(service, *args, **kwargs): if service == 's3': mock_s3 = mock.MagicMock() mock_s3.get_object.side_effect = self.SpecialError() return mock_s3 else: return original(service, *args, **kwargs) return mock_boto3_client return mock.patch('azul.deployment.aws.client', spec=True, new_callable=make_mock) def _test_dss_client(self, direct: bool, query: JSON, dss_client: DSSClient, replica: str, fallback: bool): with self.subTest(direct=direct, replica=replica, fallback=fallback): response = dss_client.post_search(es_query=query, replica=replica, per_page=10) bundle_uuid, _, bundle_version = response['results'][0]['bundle_fqid'].partition('.') with mock.patch('azul.dss.logger') as captured_log: _, manifest, metadata = download_bundle_metadata(client=dss_client, replica=replica, uuid=bundle_uuid, version=bundle_version, num_workers=config.num_dss_workers) log.info('Captured log calls: %r', captured_log.mock_calls) self.assertGreater(len(metadata), 0) self.assertGreater(set(f['name'] for f in manifest), set(metadata.keys())) for f in manifest: self.assertIn('s3_etag', f) # Extract the log method name and the first three words of log # message logged. Note that the PyCharm debugger will call # certain dunder methods on the variable, leading to failed # assertions. actual = [(m, ' '.join(re.split(r'[\s,]', a[0])[:3])) for m, a, k in captured_log.mock_calls] if direct: if replica == 'aws': if fallback: expected = [ ('debug', 'Loading bundle %s'), ('debug', 'Loading object %s'), ('warning', 'Error accessing bundle'), ('warning', 'Failed getting bundle') ] + [ ('debug', 'Loading file %s'), ('debug', 'Loading object %s'), ('warning', 'Error accessing file'), ('warning', 'Failed getting file') ] * len(metadata) else: expected = [ ('debug', 'Loading bundle %s'), ('debug', 'Loading object %s') ] + [ ('debug', 'Loading file %s'), ('debug', 'Loading object %s'), # file ('debug', 'Loading object %s') # blob ] * len(metadata) else: # On `gcp` the precondition check fails right away, preventing any attempts of direct access expected = [ ('warning', 'Failed getting bundle') ] + [ ('warning', 'Failed getting file') ] * len(metadata) else: expected = [] self.assertSequenceEqual(sorted(expected), sorted(actual)) def test_get_file_fail(self): for direct in {config.dss_direct_access, False}: with self.subTest(direct=direct): dss_client = azul.dss.direct_access_client() if direct else azul.dss.client() with self.assertRaises(SwaggerAPIException) as e: dss_client.get_file(uuid='acafefed-beef-4bad-babe-feedfa11afe1', version='2018-11-19T232756.056947Z', replica='aws') self.assertEqual(e.exception.reason, 'not_found') def test_mini_dss_failures(self): uuid = 'acafefed-beef-4bad-babe-feedfa11afe1' version = '2018-11-19T232756.056947Z' with self._failing_s3_get_object(): mini_dss = azul.dss.MiniDSS(config.dss_endpoint) with self.assertRaises(self.SpecialError): mini_dss._get_file_object(uuid, version) with self.assertRaises(KeyError): mini_dss._get_blob_key({}) with self.assertRaises(self.SpecialError): mini_dss._get_blob('/blobs/foo', {'content-type': 'application/json'}) with self.assertRaises(self.SpecialError): mini_dss.get_bundle(uuid, version, 'aws') with self.assertRaises(self.SpecialError): mini_dss.get_file(uuid, version, 'aws') with self.assertRaises(self.SpecialError): mini_dss.get_native_file_url(uuid, version, 'aws') class AzulChaliceLocalIntegrationTest(AzulTestCase): url = furl(scheme='http', host='127.0.0.1', port=8000) server = None server_thread = None @classmethod def setUpClass(cls) -> None: super().setUpClass() app_module = load_app_module('service') app_dir = os.path.dirname(app_module.__file__) factory = chalice.cli.factory.CLIFactory(app_dir) config = factory.create_config_obj() cls.server = factory.create_local_server(app_obj=app_module.app, config=config, host=cls.url.host, port=cls.url.port) cls.server_thread = threading.Thread(target=cls.server.serve_forever) cls.server_thread.start() @classmethod def tearDownClass(cls) -> None: cls.server.shutdown() cls.server_thread.join() super().tearDownClass() def test_local_chalice_health_endpoint(self): url = self.url.copy().set(path='health').url response = requests.get(url) self.assertEqual(200, response.status_code) catalog = first(config.integration_test_catalogs) def test_local_chalice_index_endpoints(self): url = self.url.copy().set(path='index/files', query=dict(catalog=self.catalog)).url response = requests.get(url) self.assertEqual(200, response.status_code) def test_local_filtered_index_endpoints(self): filters = {'genusSpecies': {'is': ['Homo sapiens']}} url = self.url.copy().set(path='index/files', query=dict(filters=json.dumps(filters), catalog=self.catalog)).url response = requests.get(url) self.assertEqual(200, response.status_code)
from abc import ( ABCMeta, ) from concurrent.futures.thread import ( ThreadPoolExecutor, ) from contextlib import ( contextmanager, ) import csv import gzip from io import ( BytesIO, TextIOWrapper, ) from itertools import ( chain, ) import json import logging import os import random import re import sys import threading import time from typing import ( AbstractSet, Any, BinaryIO, Dict, IO, List, Mapping, Optional, Sequence, Tuple, ) import unittest from unittest import ( mock, ) import uuid from zipfile import ( ZipFile, ) import attr import chalice.cli from furl import ( furl, ) from google.cloud import ( storage, ) from google.oauth2 import ( service_account, ) from hca.dss import ( DSSClient, ) from hca.util import ( SwaggerAPIException, ) from humancellatlas.data.metadata.helpers.dss import ( download_bundle_metadata, ) from more_itertools import ( first, grouper, one, ) from openapi_spec_validator import ( validate_spec, ) import requests from azul import ( CatalogName, cache, cached_property, config, drs, ) from azul.azulclient import ( AzulClient, AzulClientNotificationError, ) from azul.drs import ( AccessMethod, ) import azul.dss from azul.es import ( ESClientFactory, ) from azul.indexer import ( BundleFQID, SourcedBundleFQID, ) from azul.indexer.index_service import ( IndexService, ) from azul.logging import ( configure_test_logging, ) from azul.modules import ( load_app_module, ) from azul.portal_service import ( PortalService, ) from azul.requests import ( requests_session_with_retry_after, ) from azul.types import ( JSON, ) from azul_test_case import ( AlwaysTearDownTestCase, AzulTestCase, ) log = logging.getLogger(__name__) # noinspection PyPep8Naming def setUpModule(): configure_test_logging(log) class IntegrationTestCase(AzulTestCase, metaclass=ABCMeta): @cached_property def azul_client(self): return AzulClient() class IndexingIntegrationTest(IntegrationTestCase, AlwaysTearDownTestCase): max_bundles = 64 num_fastq_bytes = 1024 * 1024 def setUp(self) -> None: super().setUp() self.pruning_seed = random.randint(0, sys.maxsize) @contextmanager def subTest(self, msg: Any = None, **params: Any): log.info('Beginning sub-test [%s] %r', msg, params) with super().subTest(msg, **params): try: yield except BaseException: log.info('Failed sub-test [%s] %r', msg, params) raise else: log.info('Successful sub-test [%s] %r', msg, params) def test_catalog_listing(self): response = self._check_endpoint(config.service_endpoint(), '/index/catalogs') response = json.loads(response) self.assertEqual(config.default_catalog, response['default_catalog']) self.assertIn(config.default_catalog, response['catalogs']) # Test the classification of catalogs as internal or not, other # response properties are covered by unit tests. expected = { catalog.name: catalog.is_internal for catalog in config.catalogs.values() } actual = { catalog_name: catalog['internal'] for catalog_name, catalog in response['catalogs'].items() } self.assertEqual(expected, actual) def test_indexing(self): @attr.s(auto_attribs=True, kw_only=True) class Catalog: name: CatalogName notifications: Mapping[SourcedBundleFQID, JSON] @property def num_bundles(self): return len(self.notifications) @property def bundle_fqids(self) -> AbstractSet[SourcedBundleFQID]: return self.notifications.keys() def notifications_with_duplicates(self) -> List[JSON]: num_duplicates = self.num_bundles // 2 notifications = list(self.notifications.values()) # Index some bundles again to test that we handle duplicate additions. # Note: random.choices() may pick the same element multiple times so # some notifications will end up being sent three or more times. notifications.extend(random.choices(notifications, k=num_duplicates)) return notifications def _wait_for_indexer(): self.azul_client.wait_for_indexer() # For faster modify-deploy-test cycles, set `delete` to False and run # test once. Then also set `index` to False. Subsequent runs will use # catalogs from first run. Don't commit changes to these two lines. index = True delete = True if index: self._reset_indexer() catalogs: List[Catalog] = [ Catalog(name=catalog, notifications=self._prepare_notifications(catalog) if index else {}) for catalog in config.integration_test_catalogs ] if index: for catalog in catalogs: self.azul_client.index(catalog=catalog.name, notifications=catalog.notifications_with_duplicates()) _wait_for_indexer() for catalog in catalogs: self._assert_catalog_complete(catalog=catalog.name, entity_type='files', bundle_fqids=catalog.bundle_fqids) for catalog in catalogs: self._test_manifest(catalog.name) self._test_dos_and_drs(catalog.name) self._test_repository_files(catalog.name) if index and delete: for catalog in catalogs: self.azul_client.index(catalog=catalog.name, notifications=catalog.notifications_with_duplicates(), delete=True) _wait_for_indexer() for catalog in catalogs: self._assert_catalog_empty(catalog.name) self._test_other_endpoints() def _reset_indexer(self): # While it's OK to erase the integration test catalog, the queues are # shared by all catalogs and we can't afford to trash them in a stable # deployment like production. self.azul_client.reset_indexer(catalogs=config.integration_test_catalogs, # Can't purge the queues in stable deployment as # they may contain work for non-IT catalogs. purge_queues=not config.is_stable_deployment(), delete_indices=True, create_indices=True) def _test_other_endpoints(self): service_paths = ( '/', '/openapi', '/version', '/index/summary', '/index/files/order', ) service_routes = ( (config.service_endpoint(), path) for path in service_paths ) health_endpoints = ( config.service_endpoint(), config.indexer_endpoint() ) health_paths = ( '', # default keys for lambda '/', # all keys '/basic', '/elasticsearch', '/queues', '/progress', '/api_endpoints', '/other_lambdas' ) health_routes = ( (endpoint, '/health' + path) for endpoint in health_endpoints for path in health_paths ) for endpoint, path in (*service_routes, *health_routes): with self.subTest('other_endpoints', endpoint=endpoint, path=path): self._check_endpoint(endpoint, path) def _test_manifest(self, catalog: CatalogName): for format_, validator, attempts in [ (None, self._check_manifest, 1), ('compact', self._check_manifest, 1), ('full', self._check_manifest, 3), ('terra.bdbag', self._check_terra_bdbag, 1), ('curl', self._check_curl_manifest, 1), ]: with self.subTest('manifest', catalog=catalog, format=format_, attempts=attempts): assert attempts > 0 params = dict(catalog=catalog) if format_ is not None: params['format'] = format_ for attempt in range(attempts): start = time.time() response = self._check_endpoint(config.service_endpoint(), '/manifest/files', params) log.info('Request %i/%i took %.3fs to execute.', attempt + 1, attempts, time.time() - start) validator(catalog, response) @cache def _get_one_file_uuid(self, catalog: CatalogName) -> str: filters = {'fileFormat': {'is': ['fastq.gz', 'fastq']}} response = self._check_endpoint(endpoint=config.service_endpoint(), path='/index/files', query=dict(catalog=catalog, filters=json.dumps(filters), size=1, order='asc', sort='fileSize')) hits = json.loads(response) return one(one(hits['hits'])['files'])['uuid'] def _test_dos_and_drs(self, catalog: CatalogName): if config.is_dss_enabled(catalog) and config.dss_direct_access: file_uuid = self._get_one_file_uuid(catalog) self._test_dos(catalog, file_uuid) self._test_drs(catalog, file_uuid) @cached_property def _requests(self) -> requests.Session: return requests_session_with_retry_after() def _check_endpoint(self, endpoint: str, path: str, query: Optional[Mapping[str, Any]] = None) -> bytes: query = {} if query is None else {k: str(v) for k, v in query.items()} url = furl(endpoint, path=path, query=query) return self._get_url_content(url.url) def _get_url_content(self, url: str) -> bytes: return self._get_url(url).content def _get_url(self, url: str, allow_redirects: bool = True, stream: bool = False ) -> requests.Response: log.info('GET %s', url) response = self._requests.get(url, allow_redirects=allow_redirects, stream=stream) expected_statuses = (200,) if allow_redirects else (200, 301, 302) self._assertResponseStatus(response, expected_statuses) return response def _assertResponseStatus(self, response: requests.Response, expected_statuses: Tuple[int, ...] = (200,)): # Using assert to avoid tampering with response content prematurely # (in case the response is streamed) assert response.status_code in expected_statuses, ( response.reason, next(response.iter_content(chunk_size=1024)) ) def _check_manifest(self, _catalog: CatalogName, response: bytes): self.__check_manifest(BytesIO(response), 'bundle_uuid') def _check_terra_bdbag(self, catalog: CatalogName, response: bytes): with ZipFile(BytesIO(response)) as zip_fh: data_path = os.path.join(os.path.dirname(first(zip_fh.namelist())), 'data') file_path = os.path.join(data_path, 'participants.tsv') with zip_fh.open(file_path) as file: rows = self.__check_manifest(file, 'bundle_uuid') for row in rows: # Terra doesn't allow colons in this column, but they may # exist in versions indexed by TDR self.assertNotIn(':', row['entity:participant_id']) suffix = '__file_drs_uri' prefixes = [ c[:-len(suffix)] for c in rows[0].keys() if c.endswith(suffix) ] size, drs_uri, name = min( ( int(row[prefix + '__file_size']), row[prefix + suffix], row[prefix + '__file_name'], ) for row in rows for prefix in prefixes if row[prefix + suffix] ) log.info('Resolving %r (%r) from catalog %r (%i bytes)', drs_uri, name, catalog, size) plugin = self.azul_client.repository_plugin(catalog) drs_client = plugin.drs_client() access = drs_client.get_object(drs_uri, access_method=AccessMethod.https) self.assertIsNone(access.headers) self.assertEqual('https', furl(access.url).scheme) # Try HEAD first because it's more efficient, fall back to GET if the # DRS implementations prohibits it, like Azul's DRS proxy of DSS. for method in ('HEAD', 'GET'): log.info('%s %s', method, access.url) # For DSS, any HTTP client should do but for TDR we need to use an # authenticated client. TDR does return a Bearer token in the `headers` # part of the DRS response but we know that this token is the same as # the one we're making the DRS request with. response = drs_client.http_client.request(method, access.url) if response.status != 403: break self.assertEqual(200, response.status, response.data) self.assertEqual(size, int(response.headers['Content-Length'])) def __check_manifest(self, file: IO[bytes], uuid_field_name: str) -> List[Mapping[str, str]]: text = TextIOWrapper(file) reader = csv.DictReader(text, delimiter='\t') rows = list(reader) log.info(f'Manifest contains {len(rows)} rows.') self.assertGreater(len(rows), 0) self.assertIn(uuid_field_name, reader.fieldnames) bundle_uuid = rows[0][uuid_field_name] self.assertEqual(bundle_uuid, str(uuid.UUID(bundle_uuid))) return rows def _check_curl_manifest(self, _catalog: CatalogName, response: bytes): text = TextIOWrapper(BytesIO(response)) # Skip over empty lines and curl configurations to count and verify that # all the remaining lines are pairs of 'url=' and 'output=' lines. lines = ( line for line in text if not line == '\n' and not line.startswith('--') ) num_files = 0 for url, output in grouper(lines, 2): num_files += 1 self.assertTrue(url.startswith('url=')) self.assertTrue(output.startswith('output=')) log.info(f'Manifest contains {num_files} files.') self.assertGreater(num_files, 0) def _test_repository_files(self, catalog: str): with self.subTest('repository_files', catalog=catalog): file_uuid = self._get_one_file_uuid(catalog) response = self._check_endpoint(endpoint=config.service_endpoint(), path=f'/fetch/repository/files/{file_uuid}', query=dict(catalog=catalog)) response = json.loads(response) while response['Status'] != 302: self.assertEqual(301, response['Status']) response = self._get_url(response['Location']).json() response = self._get_url(response['Location'], stream=True) self._validate_fastq_response(response) def _validate_fastq_response(self, response: requests.Response): """ Note: Response object must be obtained with stream=True https://requests.readthedocs.io/en/master/user/advanced/#body-content-workflow """ try: self._validate_fastq_content(response.raw) finally: response.close() def _test_drs(self, catalog: CatalogName, file_uuid: str): repository_plugin = self.azul_client.repository_plugin(catalog) drs = repository_plugin.drs_client() for access_method in AccessMethod: with self.subTest('drs', catalog=catalog, access_method=AccessMethod.https): log.info('Resolving file %r with DRS using %r', file_uuid, access_method) drs_uri = f'drs://{config.api_lambda_domain("service")}/{file_uuid}' access = drs.get_object(drs_uri, access_method=access_method) self.assertIsNone(access.headers) if access.method is AccessMethod.https: response = self._get_url(access.url, stream=True) self._validate_fastq_response(response) elif access.method is AccessMethod.gs: content = self._get_gs_url_content(access.url, size=self.num_fastq_bytes) self._validate_fastq_content(content) else: self.fail(access_method) def _test_dos(self, catalog: CatalogName, file_uuid: str): with self.subTest('dos', catalog=catalog): log.info('Resolving file %s with DOS', file_uuid) response = self._check_endpoint(config.service_endpoint(), path=drs.dos_object_url_path(file_uuid), query=dict(catalog=catalog)) json_data = json.loads(response)['data_object'] file_url = first(json_data['urls'])['url'] while True: with self._get_url(file_url, allow_redirects=False, stream=True) as response: # We handle redirects ourselves so we can log each request if response.status_code in (301, 302): file_url = response.headers['Location'] try: retry_after = response.headers['Retry-After'] except KeyError: pass else: time.sleep(int(retry_after)) else: break self._assertResponseStatus(response) self._validate_fastq_response(response) def _get_gs_url_content(self, url: str, size: Optional[int] = None) -> BytesIO: self.assertTrue(url.startswith('gs://')) path = os.environ['GOOGLE_APPLICATION_CREDENTIALS'] credentials = service_account.Credentials.from_service_account_file(path) storage_client = storage.Client(credentials=credentials) content = BytesIO() storage_client.download_blob_to_file(url, content, start=0, end=size) return content def _validate_fastq_content(self, content: BinaryIO): # Check signature of FASTQ file. with gzip.open(content) as buf: fastq = buf.read(self.num_fastq_bytes) lines = fastq.splitlines() # Assert first character of first and third line of file (see https://en.wikipedia.org/wiki/FASTQ_format). self.assertTrue(lines[0].startswith(b'@')) self.assertTrue(lines[2].startswith(b'+')) def _prepare_notifications(self, catalog: CatalogName) -> Dict[BundleFQID, JSON]: prefix_length = 2 prefix = ''.join([ str(random.choice('abcdef0123456789')) for _ in range(prefix_length) ]) while True: log.info('Preparing notifications for catalog %r and prefix %r.', catalog, prefix) bundle_fqids = list(chain.from_iterable( self.azul_client.list_bundles(catalog, source, prefix) for source in self.azul_client.catalog_sources(catalog) )) bundle_fqids = self._prune_test_bundles(catalog, bundle_fqids, self.max_bundles) if len(bundle_fqids) >= self.max_bundles: break elif prefix: log.info('Not enough bundles with prefix %r in catalog %r. ' 'Trying a shorter prefix.', prefix, catalog) prefix = prefix[:-1] else: log.warning('Not enough bundles in catalog %r. The test may fail.', catalog) break return { bundle_fqid: self.azul_client.synthesize_notification(catalog=catalog, prefix=prefix, bundle_fqid=bundle_fqid) for bundle_fqid in bundle_fqids } def _prune_test_bundles(self, catalog: CatalogName, bundle_fqids: Sequence[SourcedBundleFQID], max_bundles: int ) -> List[SourcedBundleFQID]: seed = self.pruning_seed log.info('Selecting %i bundles with project metadata, ' 'out of %i candidates, using random seed %i.', max_bundles, len(bundle_fqids), seed) random_ = random.Random(x=seed) # The same seed should give same random order so we need to have a # deterministic order in the input list. bundle_fqids = sorted(bundle_fqids) random_.shuffle(bundle_fqids) # Pick bundles off of the randomly ordered input until we have the # desired number of bundles with project metadata. filtered_bundle_fqids = [] for bundle_fqid in bundle_fqids: if len(filtered_bundle_fqids) < max_bundles: if self.azul_client.bundle_has_project_json(catalog, bundle_fqid): filtered_bundle_fqids.append(bundle_fqid) else: break return filtered_bundle_fqids def _assert_catalog_complete(self, catalog: CatalogName, entity_type: str, bundle_fqids: AbstractSet[SourcedBundleFQID]) -> None: fqid_by_uuid: Mapping[str, SourcedBundleFQID] = { fqid.uuid: fqid for fqid in bundle_fqids } self.assertEqual(len(bundle_fqids), len(fqid_by_uuid)) with self.subTest('catalog_complete', catalog=catalog): expected_fqids = set(self.azul_client.filter_obsolete_bundle_versions(bundle_fqids)) obsolete_fqids = bundle_fqids - expected_fqids if obsolete_fqids: log.debug('Ignoring obsolete bundle versions %r', obsolete_fqids) num_bundles = len(expected_fqids) timeout = 600 indexed_fqids = set() log.debug('Expecting bundles %s ', sorted(expected_fqids)) retries = 0 deadline = time.time() + timeout while True: hits = self._get_entities(catalog, entity_type) indexed_fqids.update( # FIXME: We should use the source from the index rather than # looking it up from the expectation. # https://github.com/DataBiosphere/azul/issues/2625 fqid_by_uuid[bundle['bundleUuid']] for hit in hits for bundle in hit.get('bundles', ()) ) log.info('Detected %i of %i bundles in %i hits for entity type %s on try #%i.', len(indexed_fqids), num_bundles, len(hits), entity_type, retries) if len(indexed_fqids) == num_bundles: log.info('Found the expected %i bundles.', num_bundles) break elif len(indexed_fqids) > num_bundles: log.error('Found %i bundles, more than the expected %i.', len(indexed_fqids), num_bundles) break elif time.time() > deadline: log.error('Only found %i of %i bundles in under %i seconds.', len(indexed_fqids), num_bundles, timeout) break else: retries += 1 time.sleep(5) self.assertSetEqual(indexed_fqids, expected_fqids) entity_types = ['files', 'projects', 'samples', 'bundles'] def _assert_catalog_empty(self, catalog: CatalogName): for entity_type in self.entity_types: with self.subTest('catalog_empty', catalog=catalog, entity_type=entity_type): hits = self._get_entities(catalog, entity_type) self.assertEqual([], [hit['entryId'] for hit in hits]) def _get_entities(self, catalog: CatalogName, entity_type): entities = [] size = 100 params = dict(catalog=catalog, size=str(size)) url = furl(url=config.service_endpoint(), path=('index', entity_type), query_params=params ).url while True: response = self._get_url(url) body = response.json() hits = body['hits'] entities.extend(hits) url = body['pagination']['next'] if url is None: break return entities def _assert_indices_exist(self, catalog: CatalogName): """ Aside from checking that all indices exist this method also asserts that we can instantiate a local ES client pointing at a real, remote ES domain. """ es_client = ESClientFactory.get() service = IndexService() for index_name in service.index_names(catalog): self.assertTrue(es_client.indices.exists(index_name)) class AzulClientIntegrationTest(IntegrationTestCase): def test_azul_client_error_handling(self): invalid_notification = {} notifications = [invalid_notification] self.assertRaises(AzulClientNotificationError, self.azul_client.index, first(config.integration_test_catalogs), notifications) @unittest.skipIf(config.is_main_deployment(), 'Test would pollute portal DB') class PortalRegistrationIntegrationTest(IntegrationTestCase, AlwaysTearDownTestCase): @cached_property def portal_service(self) -> PortalService: return PortalService() def setUp(self) -> None: self.old_db = self.portal_service.read() def test_concurrent_portal_db_crud(self): """ Use multithreading to simulate multiple users simultaneously modifying the portals database. """ n_threads = 4 n_tasks = n_threads * 5 n_ops = 5 entry_format = 'task={};op={}' def run(thread_count): for op_count in range(n_ops): mock_entry = { "portal_id": "foo", "integrations": [ { "integration_id": "bar", "entity_type": "project", "integration_type": "get", "entity_ids": ["baz"] } ], "mock-count": entry_format.format(thread_count, op_count) } self.portal_service._crud(lambda db: [*db, mock_entry]) with ThreadPoolExecutor(max_workers=n_threads) as executor: futures = [executor.submit(run, i) for i in range(n_tasks)] self.assertTrue(all(f.result() is None for f in futures)) new_db = self.portal_service.read() old_entries = [portal for portal in new_db if 'mock-count' not in portal] self.assertEqual(old_entries, self.old_db) mock_counts = [portal['mock-count'] for portal in new_db if 'mock-count' in portal] self.assertEqual(len(mock_counts), len(set(mock_counts))) self.assertEqual(set(mock_counts), { entry_format.format(i, j) for i in range(n_tasks) for j in range(n_ops) }) def tearDown(self) -> None: self.portal_service.overwrite(self.old_db) class OpenAPIIntegrationTest(AzulTestCase): def test_openapi(self): service = config.service_endpoint() response = requests.get(service + '/') self.assertEqual(response.status_code, 200) self.assertEqual(response.headers['content-type'], 'text/html') self.assertGreater(len(response.content), 0) # validate OpenAPI spec response = requests.get(service + '/openapi') response.raise_for_status() spec = response.json() validate_spec(spec) @unittest.skipIf(config.dss_endpoint is None, 'DSS endpoint is not configured') class DSSIntegrationTest(AzulTestCase): def test_patched_dss_client(self): query = { "query": { "bool": { "must_not": [ { "term": { "admin_deleted": True } } ], "must": [ { "exists": { "field": "files.project_json" } }, { "range": { "manifest.version": { "gte": "2019-04-01" } } } ] } } } self.maxDiff = None for direct in {config.dss_direct_access, False}: for replica in 'aws', 'gcp': if direct: with self._failing_s3_get_object(): dss_client = azul.dss.direct_access_client() self._test_dss_client(direct, query, dss_client, replica, fallback=True) dss_client = azul.dss.direct_access_client() self._test_dss_client(direct, query, dss_client, replica, fallback=False) else: dss_client = azul.dss.client() self._test_dss_client(direct, query, dss_client, replica, fallback=False) class SpecialError(Exception): pass def _failing_s3_get_object(self): def make_mock(**kwargs): original = kwargs['spec'] def mock_boto3_client(service, *args, **kwargs): if service == 's3': mock_s3 = mock.MagicMock() mock_s3.get_object.side_effect = self.SpecialError() return mock_s3 else: return original(service, *args, **kwargs) return mock_boto3_client return mock.patch('azul.deployment.aws.client', spec=True, new_callable=make_mock) def _test_dss_client(self, direct: bool, query: JSON, dss_client: DSSClient, replica: str, fallback: bool): with self.subTest(direct=direct, replica=replica, fallback=fallback): response = dss_client.post_search(es_query=query, replica=replica, per_page=10) bundle_uuid, _, bundle_version = response['results'][0]['bundle_fqid'].partition('.') with mock.patch('azul.dss.logger') as captured_log: _, manifest, metadata = download_bundle_metadata(client=dss_client, replica=replica, uuid=bundle_uuid, version=bundle_version, num_workers=config.num_dss_workers) log.info('Captured log calls: %r', captured_log.mock_calls) self.assertGreater(len(metadata), 0) self.assertGreater(set(f['name'] for f in manifest), set(metadata.keys())) for f in manifest: self.assertIn('s3_etag', f) # Extract the log method name and the first three words of log # message logged. Note that the PyCharm debugger will call # certain dunder methods on the variable, leading to failed # assertions. actual = [(m, ' '.join(re.split(r'[\s,]', a[0])[:3])) for m, a, k in captured_log.mock_calls] if direct: if replica == 'aws': if fallback: expected = [ ('debug', 'Loading bundle %s'), ('debug', 'Loading object %s'), ('warning', 'Error accessing bundle'), ('warning', 'Failed getting bundle') ] + [ ('debug', 'Loading file %s'), ('debug', 'Loading object %s'), ('warning', 'Error accessing file'), ('warning', 'Failed getting file') ] * len(metadata) else: expected = [ ('debug', 'Loading bundle %s'), ('debug', 'Loading object %s') ] + [ ('debug', 'Loading file %s'), ('debug', 'Loading object %s'), # file ('debug', 'Loading object %s') # blob ] * len(metadata) else: # On `gcp` the precondition check fails right away, preventing any attempts of direct access expected = [ ('warning', 'Failed getting bundle') ] + [ ('warning', 'Failed getting file') ] * len(metadata) else: expected = [] self.assertSequenceEqual(sorted(expected), sorted(actual)) def test_get_file_fail(self): for direct in {config.dss_direct_access, False}: with self.subTest(direct=direct): dss_client = azul.dss.direct_access_client() if direct else azul.dss.client() with self.assertRaises(SwaggerAPIException) as e: dss_client.get_file(uuid='acafefed-beef-4bad-babe-feedfa11afe1', version='2018-11-19T232756.056947Z', replica='aws') self.assertEqual(e.exception.reason, 'not_found') def test_mini_dss_failures(self): uuid = 'acafefed-beef-4bad-babe-feedfa11afe1' version = '2018-11-19T232756.056947Z' with self._failing_s3_get_object(): mini_dss = azul.dss.MiniDSS(config.dss_endpoint) with self.assertRaises(self.SpecialError): mini_dss._get_file_object(uuid, version) with self.assertRaises(KeyError): mini_dss._get_blob_key({}) with self.assertRaises(self.SpecialError): mini_dss._get_blob('/blobs/foo', {'content-type': 'application/json'}) with self.assertRaises(self.SpecialError): mini_dss.get_bundle(uuid, version, 'aws') with self.assertRaises(self.SpecialError): mini_dss.get_file(uuid, version, 'aws') with self.assertRaises(self.SpecialError): mini_dss.get_native_file_url(uuid, version, 'aws') class AzulChaliceLocalIntegrationTest(AzulTestCase): url = furl(scheme='http', host='127.0.0.1', port=8000) server = None server_thread = None @classmethod def setUpClass(cls) -> None: super().setUpClass() app_module = load_app_module('service') app_dir = os.path.dirname(app_module.__file__) factory = chalice.cli.factory.CLIFactory(app_dir) config = factory.create_config_obj() cls.server = factory.create_local_server(app_obj=app_module.app, config=config, host=cls.url.host, port=cls.url.port) cls.server_thread = threading.Thread(target=cls.server.serve_forever) cls.server_thread.start() @classmethod def tearDownClass(cls) -> None: cls.server.shutdown() cls.server_thread.join() super().tearDownClass() def test_local_chalice_health_endpoint(self): url = self.url.copy().set(path='health').url response = requests.get(url) self.assertEqual(200, response.status_code) catalog = first(config.integration_test_catalogs) def test_local_chalice_index_endpoints(self): url = self.url.copy().set(path='index/files', query=dict(catalog=self.catalog)).url response = requests.get(url) self.assertEqual(200, response.status_code) def test_local_filtered_index_endpoints(self): filters = {'genusSpecies': {'is': ['Homo sapiens']}} url = self.url.copy().set(path='index/files', query=dict(filters=json.dumps(filters), catalog=self.catalog)).url response = requests.get(url) self.assertEqual(200, response.status_code)
import datetime import json import math import random import re import time import threading from datetime import date from deepdiff import DeepDiff from membase.api.exception import CBQError from membase.api.rest_client import RestConnection from remote.remote_util import RemoteMachineShellConnection from collection.collections_n1ql_client import CollectionsN1QL from .tuq import QueryTests class QuerySanityTests(QueryTests): def setUp(self): super(QuerySanityTests, self).setUp() self.log.info("============== QuerySanityTests setup has started ==============") self.index_to_be_created = self.input.param("index_to_be_created", '') self.query_to_be_run = self.input.param("query_to_be_run", '') if self.load_sample: self.rest.load_sample("travel-sample") self.wait_for_all_indexes_online() self.log.info("============== QuerySanityTests setup has completed ==============") self.log_config_info() self.query_buckets = self.get_query_buckets(check_all_buckets=True) self.collection_names = [] self.creation_failure = [] self.deletion_failure = [] def suite_setUp(self): super(QuerySanityTests, self).suite_setUp() self.log.info("============== QuerySanityTests suite_setup has started ==============") if self.input.param("fast_count", False): random_number = 23917 shell = RemoteMachineShellConnection(self.master) shell.execute_cbworkloadgen(self.rest.username, self.rest.password, random_number, 100, self.default_bucket_name, 1024, '-j') self.run_cbq_query( query="INSERT INTO " + self.query_buckets[0] + " ( key, value) VALUES ('pymc100205',{'name':'Sara','age':'30'})") self.log.info("============== QuerySanityTests suite_setup has completed ==============") def tearDown(self): self.log.info("============== QuerySanityTests tearDown has started ==============") self.log.info("============== QuerySanityTests tearDown has completed ==============") super(QuerySanityTests, self).tearDown() def suite_tearDown(self): self.log.info("============== QuerySanityTests suite_tearDown has started ==============") self.log.info("============== QuerySanityTests suite_tearDown has completed ==============") super(QuerySanityTests, self).suite_tearDown() ############################################################################################## # # SIMPLE CHECKS ############################################################################################## def test_error_message_collections_full(self): try: self.run_cbq_query(query="SELECT * FROM default:default.test.tes") self.fail("This query should error") except Exception as e: self.assertTrue("Keyspace not found in CB datastore: default:default.test.tes" in str(e), "The full path was not inside the error message! {0}".format(str(e))) try: self.run_cbq_query(query="SELECT * FROM default.test.tes") self.fail("This query should error") except Exception as e: self.assertTrue("Keyspace not found in CB datastore: default:default.test.tes" in str(e), "The full path was not inside the error message! {0}".format(str(e))) def test_error_message_collections_query_context(self): try: self.run_cbq_query(query="SELECT * FROM tes", query_context=self.query_context) self.fail("This query should error") except Exception as e: self.assertTrue("Keyspace not found in CB datastore: default:default.test.tes" in str(e), "The full path was not inside the error message! {0}".format(str(e))) def test_error_namespace(self): try: results = self.run_cbq_query(query='select * from default.test.tes where name = "new hotel"', query_context='default:') self.fail("This query should error") except Exception as e: self.assertTrue("Keyspace not found in CB datastore: default:default.test.tes" in str(e), "The full path was not inside the error message! {0}".format(str(e))) def test_stats_collections(self): curl_output = self.shell.execute_command( "curl http://{0}:{1}/admin/stats".format(self.master.ip, self.n1ql_port)) curl = json.loads(curl_output[0][0]) starting_deletes = curl['deletes.count'] starting_selects = curl['selects.count'] starting_inserts = curl['inserts.count'] try: self.run_cbq_query(query="CREATE PRIMARY INDEX ON default:default.{0}.{1}".format(self.scope, self.collections[0])) self.run_cbq_query(query="SELECT * FROM default:default.test.test1 b WHERE b.name = 'new hotel'") self.run_cbq_query(query="SELECT * FROM test1 b WHERE b.name = 'new hotel'", query_context='default:default.test') self.run_cbq_query( query=('INSERT INTO default:default.{0}.{1}'.format(self.scope, self.collections[ 0]) + '(KEY, VALUE) VALUES ("key6", { "type" : "hotel", "name" : "new hotel" })')) self.run_cbq_query( query='DELETE FROM default:default.test.test1 LIMIT 1') curl_output = self.shell.execute_command( "curl http://{0}:{1}/admin/stats".format(self.master.ip, self.n1ql_port)) curl = json.loads(curl_output[0][0]) self.assertEqual(curl['deletes.count'], starting_deletes + 1) self.assertEqual(curl['selects.count'], starting_selects + 2) self.assertEqual(curl['inserts.count'], starting_inserts + 1) except Exception as e: self.log.error("One of the queries failed or the stats were wrong: {0}".format(str(e))) self.fail() def test_stats_collections_prepareds(self): try: self.run_cbq_query(query="PREPARE p1 AS SELECT * FROM default:default.test.test1 b WHERE b.name = 'new hotel'") self.run_cbq_query(query="PREPARE p2 AS SELECT * FROM test1 b WHERE b.name = 'new hotel'", query_context='default:default.test') self.run_cbq_query(query="execute p2", query_context='default:default.test') self.run_cbq_query(query="execute p1", query_context='default:default.test') curl_output = self.shell.execute_command("curl http://{0}:{1}/admin/stats".format(self.master.ip, self.n1ql_port)) curl = json.loads(curl_output[0][0]) self.assertEqual(curl['prepared.count'], 2) finally: self.run_cbq_query(query="DELETE from system:prepareds") def test_escaped_identifiers(self): self.fail_if_no_buckets() queries_errors = {'SELECT name FROM {0} as bucket': ('syntax error', 3000)} self.negative_common_body(queries_errors) for query_bucket in self.query_buckets: self.query = 'SELECT name FROM %s as `bucket` ORDER BY name' % query_bucket actual_result = self.run_cbq_query() expected_list = [{"name": doc["name"]} for doc in self.full_list] expected_list_sorted = sorted(expected_list, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_list_sorted) def test_prepared_encoded_rest(self): result_count = 1412 if not self.sample_bucket: self.sample_bucket = 'beer-sample' self.rest.load_sample(self.sample_bucket) self.wait_for_buckets_status({self.sample_bucket: "healthy"}, 5, 120) self.wait_for_bucket_docs({self.sample_bucket: 7303}, 5, 120) self._wait_for_index_online('beer-sample', 'beer_primary') query_bucket = self.get_collection_name(self.sample_bucket) try: query = 'create index myidx on {0}(name,country,code) where (type="brewery")'.format(query_bucket) self.run_cbq_query(query) self._wait_for_index_online('beer-sample', 'myidx') query = 'prepare s1 from SELECT name, IFMISSINGORNULL(country,999), IFMISSINGORNULL(code,999)' \ ' FROM {0} WHERE type = "brewery" AND name IS NOT MISSING'.format(query_bucket) result = self.run_cbq_query(query) encoded_plan = '"' + result['results'][0]['encoded_plan'] + '"' for server in self.servers: remote = RemoteMachineShellConnection(server) remote.stop_server() time.sleep(20) server = None for server in self.servers: remote = RemoteMachineShellConnection(server) remote.start_server() self.wait_for_buckets_status({self.sample_bucket: "healthy"}, 5, 120) self.wait_for_bucket_docs({self.sample_bucket: 7303}, 5, 120) self._wait_for_index_online('beer-sample', 'beer_primary') cmd = "%s http://%s:%s/query/service -u %s:%s -H 'Content-Type: application/json' " \ "-d '{ \"prepared\": \"s1\", \"encoded_plan\": %s }'" % ( self.curl_path, server.ip, self.n1ql_port, self.username, self.password, encoded_plan) for server in self.servers: remote = RemoteMachineShellConnection(server) result = remote.execute_command(cmd) new_list = [string.strip() for string in result[0]] concat_string = ''.join(new_list) json_output = json.loads(concat_string) self.log.info(json_output['metrics']['resultCount']) self.assertEqual(json_output['metrics']['resultCount'], result_count) finally: self.rest.delete_bucket(self.sample_bucket) self.wait_for_bucket_delete(self.sample_bucket, 5, 120) # These bugs are not planned to be fixed therefore this test isnt in any confs '''MB-19887 and MB-24303: These queries were returning incorrect results with views.''' def test_views(self): self.fail_if_no_buckets() created_indexes = [] try: idx = "ix1" self.query = "CREATE INDEX %s ON " % idx + self.query_buckets[0] + " (x,y) USING VIEW" self.run_cbq_query() created_indexes.append(idx) time.sleep(15) self.run_cbq_query("insert into " + self.query_buckets[0] + " values ('k01',{'x':10})") result = self.run_cbq_query("select x,y from " + self.query_buckets[0] + " where x > 3") self.assertTrue(result['results'][0] == {"x": 10}) self.run_cbq_query('insert into ' + self.query_buckets[0] + ' values("k02", {"x": 20, "y": 20})') self.run_cbq_query('insert into ' + self.query_buckets[0] + ' values("k03", {"x": 30, "z": 30})') self.run_cbq_query('insert into ' + self.query_buckets[0] + ' values("k04", {"x": 40, "y": 40, "z": 40})') idx2 = "iv1" self.query = "CREATE INDEX %s ON " % idx2 + self.query_buckets[0] + " (x,y,z) USING VIEW" self.run_cbq_query() created_indexes.append(idx2) expected_result = [{'x': 10}, {'x': 20, 'y': 20}, {'x': 30, 'z': 30}, {'x': 40, 'y': 40, 'z': 40}] result = self.run_cbq_query('select x,y,z from ' + self.query_buckets[0] + ' use index (iv1 using view) ' 'where x is not missing') self.assertTrue(result['results'] == expected_result) finally: for idx in created_indexes: self.query = "DROP INDEX %s ON %s USING VIEW" % (self.query_buckets[0], idx) self.run_cbq_query() def test_collections_meta_keyspace(self): results = self.run_cbq_query(query='select meta(d) from default:default.test.test1 as d') self.assertEqual(results['results'][0]['$1']['keyspace'], 'default:default.test.test1') def test_collections_meta_query_context(self): results = self.run_cbq_query(query='select meta(d) from test1 as d', query_context='default:default.test') self.assertEqual(results['results'][0]['$1']['keyspace'], 'default:default.test.test1') def test_collections_meta_keyspace_full(self): results = self.run_cbq_query(query='select meta(default.test.test1) from default:default.test.test1') self.assertEqual(results['results'][0]['$1']['keyspace'], 'default:default.test.test1') results = self.run_cbq_query(query='select meta(default:default.test.test1) from default:default.test.test1') self.assertEqual(results['results'][0]['$1']['keyspace'], 'default:default.test.test1') def test_collections_meta_id(self): results = self.run_cbq_query(query='select meta(d).id from default:default.test.test1 as d') self.assertEqual(results['results'], [{'id': 'key1'}, {'id': 'key2'}, {'id': 'key3'}, {'id': 'key4'}]) results = self.run_cbq_query(query='select meta(d).id from test1 as d', query_context='default:default.test') self.assertEqual(results['results'], [{'id': 'key1'}, {'id': 'key2'}, {'id': 'key3'}, {'id': 'key4'}]) def test_collections_meta_id_full_path(self): results = self.run_cbq_query(query='select meta(default.test.test1).id from default:default.test.test1') self.assertEqual(results['results'], [{'id': 'key1'}, {'id': 'key2'}, {'id': 'key3'}, {'id': 'key4'}]) results = self.run_cbq_query(query='select meta(default:default.test.test1).id from default:default.test.test1') self.assertEqual(results['results'], [{'id': 'key1'}, {'id': 'key2'}, {'id': 'key3'}, {'id': 'key4'}]) def test_collections_meta_cas(self): results = self.run_cbq_query(query='select meta(d).cas from default:default.test.test1 as d') self.assertEqual(results['metrics']['resultCount'], 4) results = self.run_cbq_query(query='select meta(d).cas from test1 as d', query_context='default:default.test') self.assertEqual(results['metrics']['resultCount'], 4) def test_collections_meta_cas_full(self): results = self.run_cbq_query(query='select meta(default.test.test1).cas from default:default.test.test1') self.assertEqual(results['metrics']['resultCount'], 4) results = self.run_cbq_query(query='select meta(default:default.test.test1).cas from default:default.test.test1') self.assertEqual(results['metrics']['resultCount'], 4) def test_collections_meta_expiration(self): results = self.run_cbq_query(query='select meta(d).expiration from default:default.test.test1 as d') self.assertEqual(results['results'], [{'expiration': 0}, {'expiration': 0}, {'expiration': 0}, {'expiration': 0}]) results = self.run_cbq_query(query='select meta(d).expiration from test1 as d', query_context='default:default.test') self.assertEqual(results['results'], [{'expiration': 0}, {'expiration': 0}, {'expiration': 0}, {'expiration': 0}]) def test_collections_meta_expiration_full(self): results = self.run_cbq_query(query='select meta(default.test.test1).expiration from default:default.test.test1') self.assertEqual(results['results'], [{'expiration': 0}, {'expiration': 0}, {'expiration': 0}, {'expiration': 0}]) results = self.run_cbq_query(query='select meta(default:default.test.test1).expiration from default:default.test.test1') self.assertEqual(results['results'], [{'expiration': 0}, {'expiration': 0}, {'expiration': 0}, {'expiration': 0}]) ''' This test will concurrently create and drop collections, and then give them 5 seconds to appear in system:keyspaces, if any one collection creation/deletion fails the whole test fails ''' def test_create_drop_collections(self): self.collections_helper = CollectionsN1QL(self.master) self.collections_helper.create_scope(bucket_name="default", scope_name="scope1") self.collections_helper.create_scope(bucket_name="default", scope_name="scope2") for i in range(0, 100): thread_name = threading.Thread(name='run_collection', target=self.run_create_collection,args=("scope1", "collection1" + str(i))) thread2_name = threading.Thread(name='run_collection', target=self.run_create_collection,args=("scope2", "collection2" + str(i))) thread_name.start() thread2_name.start() self.sleep(1) if len(self.creation_failure) > 0: for collection in self.creation_failure: self.log.error("Creation failed for collection: {0}".format(str(collection))) self.fail("Some collections failed to create! Check logs for more details") if len(self.collection_names) > 0: for collection in self.collection_names: delete_thread = threading.Thread(name='drop_collection', target=self.run_drop_collection, args=(collection[0], collection[1])) delete_thread.start() delete_thread.join() if len(self.deletion_failure) > 0: for collection in self.deletion_failure: self.log.error("Deletion failed for collection: {0}".format(str(collection))) self.fail("Some collections failed to drop! Check logs for more details") retry_count = 100 while retry_count > 0: if len(self.collection_names) > 0: for collection in self.collection_names: delete_thread = threading.Thread(name='drop_collection', target=self.run_drop_collection, args=(collection[0], collection[1])) delete_thread.start() if len(self.deletion_failure) > 0: for collection in self.deletion_failure: self.log.error("Deletion failed for collection: {0}".format(str(collection))) self.fail("Some collections failed to drop! Check logs for more details") self.sleep(.5) retry_count -= 1 if len(self.creation_failure) > 0: for collection in self.creation_failure: self.log.error("Creation failed for collection: {0}".format(str(collection))) self.fail("Some collections failed to create! Check logs for more details") if len(self.deletion_failure) > 0: for collection in self.deletion_failure: self.log.error("Deletion failed for collection: {0}".format(str(collection))) self.fail("Some collections failed to drop! Check logs for more details") '''Create a collection and verify that within 5 seconds it is apart of system:keyspaces, print any errors that occur''' def run_create_collection(self, scope_name='',collection_name=''): retry_count = 5 created = self.collections_helper.create_collection(bucket_name="default", scope_name=scope_name, collection_name=collection_name) while retry_count > 0: try: results = self.run_cbq_query('select * from system:keyspaces where name = "{0}"'.format(collection_name)) if results['metrics']['resultCount'] == 1: break except Exception as e: self.log.info(str(e)) continue self.sleep(1) retry_count -= 1 if not retry_count > 0: if collection_name not in self.creation_failure: self.creation_failure.append((scope_name, collection_name, "Entry not found in system:keyspaces")) if collection_name not in self.creation_failure: self.collection_names.append((scope_name, collection_name)) return '''Drop a collection and verify that within 5 seconds it is removed from system:keyspaces''' def run_drop_collection(self, scope_name='', collection_name=''): retry_count = 5 deleted = self.collections_helper.delete_collection(bucket_name="default", scope_name=scope_name, collection_name=collection_name) while retry_count > 0: try: results = self.run_cbq_query('select * from system:keyspaces where name = "{0}"'.format(collection_name)) if results['metrics']['resultCount'] == 0: break except Exception as e: if 'Keyspace not found in CB datastore' in str(e): break continue self.sleep(1) retry_count -= 1 if not retry_count > 0: if collection_name not in self.deletion_failure: self.deletion_failure.append((scope_name, collection_name, "Entry not deleted from system:keyspaces")) self.collection_names.remove((scope_name, collection_name)) return ############################################################################################## # # ALL ############################################################################################## def test_all(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'SELECT ALL job_title FROM %s ORDER BY job_title' % query_bucket actual_result = self.run_cbq_query() expected_result = [{"job_title": doc['job_title']} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result['results'], expected_result) def test_all_nested(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'SELECT ALL tasks_points.task1 FROM %s ' % query_bucket + \ 'ORDER BY tasks_points.task1' actual_result = self.run_cbq_query() expected_result = [{"task1": doc['tasks_points']['task1']} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['task1'])) self._verify_results(actual_result['results'], expected_result) self.query = 'SELECT ALL skills[0] as skill' + \ ' FROM %s ORDER BY skills[0]' % query_bucket actual_result = self.run_cbq_query() expected_result = [{"skill": doc['skills'][0]} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['skill'])) self._verify_results(actual_result['results'], expected_result) if not self.analytics: self.query = 'SELECT ALL tasks_points.* FROM %s' % query_bucket actual_result = self.run_cbq_query() expected_result = [doc['tasks_points'] for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['task1'], doc['task2'])) actual_result = sorted(actual_result['results'], key=lambda doc: (doc['task1'], doc['task2'])) self._verify_results(actual_result, expected_result) # This method is not used anywhere def set_indexer_pokemon_settings(self): projector_json = {"projector.dcp.numConnections": 1} moi_json = {"indexer.moi.useMemMgmt": True} server = self.get_nodes_from_services_map(service_type="index") rest = RestConnection(server) rest.set_index_settings(projector_json) self.log.info("{0} set".format(projector_json)) self.sleep(60) servers = self.get_nodes_from_services_map(service_type="kv", get_all_nodes=True) for server in servers: remote = RemoteMachineShellConnection(server) remote.terminate_process(process_name="projector") self.sleep(60) self.sleep(60) # self.set_indexer_logLevel() self.loglevel = "info" self.log.info("Setting indexer log level to {0}".format(self.loglevel)) server = self.get_nodes_from_services_map(service_type="index") rest = RestConnection(server) rest.set_indexer_params("logLevel", self.loglevel) self.sleep(30) rest.set_index_settings(moi_json) self.log.info("{0} set".format(moi_json)) self.sleep(30) def test_all_negative(self): queries_errors = {'SELECT ALL * FROM %s': ('syntax error', 3000)} self.negative_common_body(queries_errors) def test_keywords(self): queries_errors = {'SELECT description as DESC FROM %s order by DESC': ('syntax error', 3000)} self.negative_common_body(queries_errors) def test_distinct_negative(self): queries_errors = {'SELECT name FROM {0} ORDER BY DISTINCT name': ('syntax error', 3000), 'SELECT name FROM {0} GROUP BY DISTINCT name': ('syntax error', 3000), 'SELECT ANY tasks_points FROM {0}': ('syntax error', 3000)} self.negative_common_body(queries_errors) def test_any(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name, email FROM {0} d WHERE (ANY skill IN d.skills SATISFIES skill = 'skill2010' " \ "END) AND (ANY vm IN d.VMs SATISFIES vm.RAM = 5 END) AND NOT (job_title = 'Sales') ORDER BY" \ " name".format(query_bucket) actual_result = self.run_cbq_query() expected_result = [{"name": doc['name'], "email": doc["email"]} for doc in self.full_list if len([skill for skill in doc["skills"] if skill == 'skill2010']) > 0 and len([vm for vm in doc["VMs"] if vm["RAM"] == 5]) > 0 and doc["job_title"] != 'Sales'] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) # This test isnt used anywhere def test_any_within(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name, email FROM %s " % query_bucket + \ " d WHERE ANY vm within d.VMs SATISFIES vm.RAM = 5 END" actual_result = self.run_cbq_query() expected_result = [{"name": doc['name'], "email": doc["email"]} for doc in self.full_list if len([vm for vm in doc["VMs"] if vm["RAM"] == 5]) > 0] self._verify_results(actual_result['results'], expected_result) def test_any_no_in_clause(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name, email FROM %s d WHERE " % query_bucket + \ "(ANY skill IN d.skills SATISFIES skill = 'skill2010' end)" + \ "AND (ANY vm IN d.VMs SATISFIES vm.RAM = 5 end) " + \ "AND NOT (job_title = 'Sales') ORDER BY name" actual_result = self.run_cbq_query() expected_result = [{"name": doc['name'], "email": doc["email"]} for doc in self.full_list if len([skill for skill in doc["skills"] if skill == 'skill2010']) > 0 and len([vm for vm in doc["VMs"] if vm["RAM"] == 5]) > 0 and doc["job_title"] != 'Sales'] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) def test_prepared_any_no_in_clause(self): self.fail_if_no_buckets() if self.monitoring: self.query = "select * from system:prepareds" result = self.run_cbq_query() self.assertTrue(result['metrics']['resultCount'] == 0) for query_bucket in self.query_buckets: query_bucket = self.get_collection_name(query_bucket) self.query = "SELECT name, email FROM %s as d WHERE " % query_bucket + \ "(ANY skill IN d.skills SATISFIES skill = 'skill2010' end) AND" \ " (ANY vm IN d.VMs SATISFIES vm.RAM = 5 end) " \ "AND NOT (job_title = 'Sales') ORDER BY name" self.prepared_common_body() if self.monitoring: self.query = "select * from system:prepareds" result = self.run_cbq_query() self.assertTrue(result['metrics']['resultCount'] == 1) def test_any_external(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'SELECT name FROM %s WHERE ' % query_bucket + \ 'ANY x IN ["Support", "Management"] SATISFIES job_title = x END ' + \ 'ORDER BY name' actual_result = self.run_cbq_query() expected_result = [{"name": doc['name']} for doc in self.full_list if doc["job_title"] in ["Support", "Management"]] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) def test_every(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name FROM %s d WHERE " % query_bucket + \ "(EVERY vm IN d.VMs SATISFIES CEIL(vm.memory) > 5 END) ORDER BY name" actual_result = self.run_cbq_query() expected_result = [{"name": doc['name']} for doc in self.full_list if len([vm for vm in doc["VMs"] if math.ceil(vm['memory']) > 5]) == len(doc["VMs"])] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) def test_satisfy_negative(self): queries_errors = {'SELECT name FROM %s WHERE ANY x IN 123 SATISFIES job_title = x END': ('syntax error', 3000), 'SELECT name FROM %s WHERE ANY x IN ["Sales"] SATISFIES job_title = x': ( 'syntax error', 3000), 'SELECT job_title FROM %s WHERE ANY job_title IN ["Sales"] SATISFIES job_title = job_title ' 'END': ( 'syntax error', 3000), 'SELECT job_title FROM %s WHERE EVERY ANY x IN ["Sales"] SATISFIES x = job_title END': ( 'syntax error', 3000)} self.negative_common_body(queries_errors) def test_check_is_isnot_negative(self): queries_errors = {'SELECT * FROM %s WHERE name is foo': ('syntax error', 3000), 'SELECT * FROM %s WHERE name is not foo': ('syntax error', 3000)} self.negative_common_body(queries_errors) def test_array(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT ARRAY vm.memory FOR vm IN VMs END AS vm_memories" + \ " FROM %s WHERE VMs IS NOT NULL " % query_bucket if self.analytics: self.query = 'SELECT (SELECT VALUE vm.memory FROM VMs AS vm) AS vm_memories FROM %s WHERE VMs IS NOT ' \ 'NULL ' % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['vm_memories'])) expected_result = [{"vm_memories": [vm["memory"] for vm in doc['VMs']]} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['vm_memories'])) self._verify_results(actual_result, expected_result) # This test is not used anywhere def test_array_objects(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT VMs[*].os from %s" % query_bucket actual_result = self.run_cbq_query() actual_result = actual_result['results'] expected_result = [{"os": [vm["os"] for vm in doc['VMs']]} for doc in self.full_list] self._verify_results(actual_result, expected_result) def test_arrays_negative(self): queries_errors = {'SELECT ARRAY vm.memory FOR vm IN 123 END AS vm_memories FROM %s': ('syntax error', 3000), 'SELECT job_title, array_agg(name)[:5] as names FROM %s': ('syntax error', 3000), 'SELECT job_title, array_agg(name)[-20:-5] as names FROM %s': ('syntax error', 3000), 'SELECT job_title, array_agg(name)[a:-b] as names FROM %s': ('syntax error', 3000)} self.negative_common_body(queries_errors) # This test is not used anywhere def test_slicing(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, array_agg(name)[0:5] as names" + \ " FROM %s GROUP BY job_title" % query_bucket actual_result = self.run_cbq_query() for item in actual_result['results']: self.log.info("Result: %s" % actual_result['results']) self.assertTrue(len(item['names']) <= 5, "Slicing doesn't work") self.query = "SELECT job_title, array_agg(name)[5:] as names" + \ " FROM %s GROUP BY job_title" % query_bucket actual_result = self.run_cbq_query() tmp_groups = {doc['job_title'] for doc in self.full_list} expected_list = [{"job_title": group, "names": [x["name"] for x in self.full_list if x["job_title"] == group]} for group in tmp_groups] expected_item = None for item in actual_result['results']: for tmp_item in expected_list: if item['job_title'] == tmp_item['job_title']: expected_item = tmp_item self.log.info("Result: %s" % actual_result['results']) self.assertTrue(len(item['names']) == len(expected_item['names']), "Slicing doesn't work") self.query = "SELECT job_title, array_agg(name)[5:10] as names" + \ " FROM %s GROUP BY job_title" % query_bucket actual_result = self.run_cbq_query() for item in actual_result['results']: self.log.info("Result: %s" % actual_result['results']) self.assertTrue(len(item['names']) <= 5, "Slicing doesn't work") def test_count_prepare(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "create index idx_cover on %s(join_mo,join_day) where join_mo > 7" % query_bucket self.run_cbq_query() self.query = "SELECT count(*) AS cnt from %s " % query_bucket + \ "WHERE join_mo > 7 and join_day > 1" self.prepared_common_body() def test_leak_goroutine(self): shell = RemoteMachineShellConnection(self.master) for i in range(20): cmd = 'curl http://%s:6060/debug/pprof/goroutine?debug=2 | grep NewLexer' % self.master.ip o = shell.execute_command(cmd) new_curl = json.dumps(o) string_curl = json.loads(new_curl) self.assertTrue("curl: (7) couldn't connect to host" == str(string_curl[1][1])) cmd = "curl http://%s:8093/query/service -d 'statement=select * from 1+2+3'" % self.master.ip o = shell.execute_command(cmd) new_curl = json.dumps(o) string_curl = json.loads(new_curl) self.assertTrue(len(string_curl) == 2) cmd = 'curl http://%s:6060/debug/pprof/goroutine?debug=2 | grep NewLexer' % self.master.ip o = shell.execute_command(cmd) new_curl = json.dumps(o) string_curl = json.loads(new_curl) self.assertTrue(len(string_curl) == 2) ############################################################################################## # # COUNT ############################################################################################## def test_fast_count(self): if self.index_to_be_created: if "EQUALS" in self.index_to_be_created: self.index_to_be_created = self.index_to_be_created.replace("EQUALS", "=") self.run_cbq_query(query=self.index_to_be_created) self.wait_for_all_indexes_online() try: if "STAR" in self.query_to_be_run: self.query_to_be_run = self.query_to_be_run.replace("STAR", "*") if "EQUALS" in self.query_to_be_run: self.query_to_be_run = self.query_to_be_run.replace("EQUALS", "=") # add use primary index hint to the query to compare the GSI query to the primary index query actual_results = self.run_cbq_query(query=self.query_to_be_run) split_query = self.query_to_be_run.split("where") primary_index_query = split_query[0] + "USE INDEX(`#primary`) where" + split_query[1] expected_results = self.run_cbq_query(query=primary_index_query) self.assertEqual(actual_results['results'][0]['$1'], expected_results['results'][0]['$1']) finally: if self.load_sample: query_bucket = self.get_collection_name('`travel-sample`') self.run_cbq_query(query="DROP INDEX idx_flight_stops ON {0}".format(query_bucket)) else: query_bucket = self.get_collection_name(self.default_bucket_name) self.run_cbq_query(query="DROP INDEX idx1 ON {0}".format(query_bucket)) def test_primary_count(self): # number of documents inserted at the beginning of suite_setup random_number = 23918 RemoteMachineShellConnection(self.master) if "STAR" in self.query_to_be_run: self.query_to_be_run = self.query_to_be_run.replace("STAR", "*") actual_results = self.run_cbq_query(query=self.query_to_be_run) self.assertEqual(actual_results['results'][0]['$1'], random_number + self.docs_per_day * 2016) ############################################################################################## # # LIKE ############################################################################################## def test_like(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name FROM {0} WHERE job_title LIKE 'S%' ORDER BY name".format(query_bucket) actual_result = self.run_cbq_query() expected_result = [{"name": doc['name']} for doc in self.full_list if doc["job_title"].startswith('S')] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) self.query = "SELECT name FROM {0} WHERE job_title LIKE '%u%' ORDER BY name".format(query_bucket) actual_result = self.run_cbq_query() expected_result = [{"name": doc['name']} for doc in self.full_list if doc["job_title"].find('u') != -1] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) self.query = "SELECT name FROM {0} WHERE job_title NOT LIKE 'S%' ORDER BY name".format(query_bucket) actual_result = self.run_cbq_query() expected_result = [{"name": doc['name']} for doc in self.full_list if not doc["job_title"].startswith('S')] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) self.query = "SELECT name FROM {0} WHERE job_title NOT LIKE '_ales' ORDER BY name".format(query_bucket) actual_result = self.run_cbq_query() expected_result = [{"name": doc['name']} for doc in self.full_list if not (doc["job_title"].endswith('ales') and len(doc["job_title"]) == 5)] self.query = "SELECT name FROM {0} WHERE reverse(job_title) NOT LIKE 'sela_' " \ "ORDER BY name".format(query_bucket) actual_result1 = self.run_cbq_query() self.assertEqual(actual_result1['results'], actual_result['results']) expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) def test_like_negative(self): queries_errors = {"SELECT tasks_points FROM {0} WHERE tasks_points.* LIKE '_1%'": ('syntax error', 3000)} self.negative_common_body(queries_errors) queries_errors = {"SELECT tasks_points FROM {0} WHERE REVERSE(tasks_points.*) LIKE '%1_'": ('syntax error', 3000)} self.negative_common_body(queries_errors) def test_like_any(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name, email FROM %s d WHERE (ANY vm IN d.VMs" % query_bucket + \ " SATISFIES vm.os LIKE '%bun%'" + \ "END) AND (ANY skill IN d.skills " + \ "SATISFIES skill = 'skill2010' END) ORDER BY name" actual_result = self.run_cbq_query() expected_result = [{"name": doc['name'], "email": doc["email"]} for doc in self.full_list if len([vm for vm in doc["VMs"] if vm["os"].find('bun') != -1]) > 0 and len([skill for skill in doc["skills"] if skill == 'skill2010']) > 0] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) def test_like_every(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name, email FROM %s d WHERE (EVERY vm IN d.VMs " % query_bucket + \ "SATISFIES vm.os NOT LIKE '%cent%' END)" + \ " AND (ANY skill IN d.skills SATISFIES skill =" + \ " 'skill2010' END) ORDER BY name" actual_result = self.run_cbq_query() expected_result = [{"name": doc['name'], "email": doc["email"]} for doc in self.full_list if len([vm for vm in doc["VMs"] if vm["os"].find('cent') == -1]) == len(doc["VMs"]) and len([skill for skill in doc["skills"] if skill == 'skill2010']) > 0] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) def test_like_aliases(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name AS NAME from %s " % query_bucket + \ "AS EMPLOYEE where EMPLOYEE.name LIKE '_mpl%' ORDER BY name" actual_result = self.run_cbq_query() self.query = "select name AS NAME from %s " % query_bucket + \ "AS EMPLOYEE where reverse(EMPLOYEE.name) LIKE '%lpm_' ORDER BY name" actual_result1 = self.run_cbq_query() self.assertEqual(actual_result['results'], actual_result1['results']) expected_result = [{"NAME": doc['name']} for doc in self.full_list if doc["name"].find('mpl') == 1] expected_result = sorted(expected_result, key=lambda doc: (doc['NAME'])) self._verify_results(actual_result['results'], expected_result) def test_like_wildcards(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT email FROM %s WHERE email " % query_bucket + \ "LIKE '%@%.%' ORDER BY email" actual_result = self.run_cbq_query() self.query = "SELECT email FROM %s WHERE reverse(email) " % query_bucket + \ "LIKE '%.%@%' ORDER BY email" actual_result1 = self.run_cbq_query() self.assertEqual(actual_result['results'], actual_result1['results']) expected_result = [{"email": doc['email']} for doc in self.full_list if re.match(r'.*@.*\..*', doc['email'])] expected_result = sorted(expected_result, key=lambda doc: (doc['email'])) self._verify_results(actual_result['results'], expected_result) self.query = "SELECT email FROM %s WHERE email" % query_bucket + \ " LIKE '%@%.h' ORDER BY email" actual_result = self.run_cbq_query() expected_result = [] self._verify_results(actual_result['results'], expected_result) def test_prepared_like_wildcards(self): self.fail_if_no_buckets() if self.monitoring: self.query = "select * from system:prepareds" result = self.run_cbq_query() self.assertTrue(result['metrics']['resultCount'] == 0) for query_bucket in self.query_buckets: self.query = "SELECT email FROM %s WHERE email " % query_bucket + \ "LIKE '%@%.%' ORDER BY email" self.prepared_common_body() if self.monitoring: self.query = "select * from system:prepareds" result = self.run_cbq_query() self.assertTrue(result['metrics']['resultCount'] == 1) def test_between(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name FROM {0} WHERE join_mo BETWEEN 1 AND 6 ORDER BY name".format(query_bucket) actual_result = self.run_cbq_query() expected_result = [{"name": doc['name']} for doc in self.full_list if 1 <= doc["join_mo"] <= 6] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) self.query = "SELECT name FROM {0} WHERE join_mo NOT BETWEEN 1 AND 6 ORDER BY name".format(query_bucket) actual_result = self.run_cbq_query() expected_result = [{"name": doc['name']} for doc in self.full_list if not 1 <= doc["join_mo"] <= 6] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) def test_between_negative(self): queries_errors = {'SELECT name FROM %s WHERE join_mo BETWEEN 1 AND -10 ORDER BY name': ('syntax error', 3000), 'SELECT name FROM %s WHERE join_mo BETWEEN 1 AND a ORDER BY name': ('syntax error', 3000)} self.negative_common_body(queries_errors) ############################################################################################## # # GROUP BY ############################################################################################## def test_group_by(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT tasks_points.task1 AS task from %s " % query_bucket + \ "WHERE join_mo>7 GROUP BY tasks_points.task1 " + \ "ORDER BY tasks_points.task1" if self.analytics: self.query = "SELECT d.tasks_points.task1 AS task from %s d " % query_bucket + \ "WHERE d.join_mo>7 GROUP BY d.tasks_points.task1 " + \ "ORDER BY d.tasks_points.task1" actual_result = self.run_cbq_query() expected_result = [{"task": doc['tasks_points']["task1"]} for doc in self.full_list if doc["join_mo"] > 7] expected_result = [dict(y) for y in set(tuple(x.items()) for x in expected_result)] expected_result = sorted(expected_result, key=lambda doc: (doc['task'])) self._verify_results(actual_result['results'], expected_result) def test_group_by_having(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "from %s WHERE join_mo>7 GROUP BY tasks_points.task1 " % query_bucket + \ "HAVING COUNT(tasks_points.task1) > 0 SELECT tasks_points.task1 " + \ "AS task ORDER BY tasks_points.task1" actual_result = self.run_cbq_query() expected_result = [{"task": doc['tasks_points']["task1"]} for doc in self.full_list if doc["join_mo"] > 7] expected_result = [doc for doc in expected_result if expected_result.count(doc) > 0] expected_result = [dict(y) for y in set(tuple(x.items()) for x in expected_result)] expected_result = sorted(expected_result, key=lambda doc: (doc['task'])) self._verify_results(actual_result['results'], expected_result) def test_group_by_aggr_fn(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT tasks_points.task1 AS task from %s " % query_bucket + \ "WHERE join_mo>7 GROUP BY tasks_points.task1 " + \ "HAVING COUNT(tasks_points.task1) > 0 AND " + \ "(MIN(join_day)=1 OR MAX(join_yr=2011)) " + \ "ORDER BY tasks_points.task1" actual_result = self.run_cbq_query() if self.analytics: self.query = "SELECT d.tasks_points.task1 AS task from %s d " % query_bucket + \ "WHERE d.join_mo>7 GROUP BY d.tasks_points.task1 " + \ "HAVING COUNT(d.tasks_points.task1) > 0 AND " + \ "(MIN(d.join_day)=1 OR MAX(d.join_yr=2011)) " + \ "ORDER BY d.tasks_points.task1" tmp_groups = {doc['tasks_points']["task1"] for doc in self.full_list} expected_result = [{"task": group} for group in tmp_groups if [doc['tasks_points']["task1"] for doc in self.full_list].count(group) > 0 and (min([doc["join_day"] for doc in self.full_list if doc['tasks_points']["task1"] == group]) == 1 or max([doc["join_yr"] for doc in self.full_list if doc['tasks_points']["task1"] == group]) == 2011)] expected_result = sorted(expected_result, key=lambda doc: (doc['task'])) self._verify_results(actual_result['results'], expected_result) def test_prepared_group_by_aggr_fn(self): self.fail_if_no_buckets() if self.monitoring: self.query = "select * from system:prepareds" result = self.run_cbq_query() self.assertTrue(result['metrics']['resultCount'] == 0) for query_bucket in self.query_buckets: self.query = "SELECT tasks_points.task1 AS task from %s " % query_bucket + \ "WHERE join_mo>7 GROUP BY tasks_points.task1 " + \ "HAVING COUNT(tasks_points.task1) > 0 AND " + \ "(MIN(join_day)=1 OR MAX(join_yr=2011)) " + \ "ORDER BY tasks_points.task1" self.prepared_common_body() if self.monitoring: self.query = "select * from system:prepareds" result = self.run_cbq_query() self.assertTrue(result['metrics']['resultCount'] == 1) self.query = "delete from system:prepareds" self.run_cbq_query() self.query = "select * from system:prepareds" result = self.run_cbq_query() self.assertTrue(result['metrics']['resultCount'] == 0) def test_group_by_satisfy(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, AVG(test_rate) as avg_rate FROM %s d " % query_bucket + \ "WHERE (ANY skill IN d.skills SATISFIES skill = 'skill2010' end) " + \ "AND (ANY vm IN d.VMs SATISFIES vm.RAM = 5 end) " + \ "GROUP BY job_title ORDER BY job_title" if self.analytics: self.query = "SELECT d.job_title, AVG(d.test_rate) as avg_rate FROM %s d " % query_bucket + \ "WHERE (ANY skill IN d.skills SATISFIES skill = 'skill2010' end) " + \ "AND (ANY vm IN d.VMs SATISFIES vm.RAM = 5 end) " + \ "GROUP BY d.job_title ORDER BY d.job_title" actual_result = self.run_cbq_query() tmp_groups = {doc["job_title"] for doc in self.full_list} expected_result = [{"job_title": doc['job_title'], "test_rate": doc["test_rate"]} for doc in self.full_list if 'skill2010' in doc["skills"] and len([vm for vm in doc["VMs"] if vm["RAM"] == 5]) > 0] expected_result = [{"job_title": group, "avg_rate": math.fsum([doc["test_rate"] for doc in expected_result if doc["job_title"] == group]) / len([doc["test_rate"] for doc in expected_result if doc["job_title"] == group])} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result['results'], expected_result) def test_group_by_negative(self): queries_errors = {"SELECT tasks_points from {0} WHERE tasks_points.task2>3" + " GROUP BY tasks_points.*": ('syntax error', 3000), "from {0} WHERE join_mo>7 GROUP BY tasks_points.task1 " + "SELECT tasks_points.task1 AS task HAVING COUNT(tasks_points.task1) > 0": ('syntax error', 3000)} self.negative_common_body(queries_errors) # This test has no usages anywhere def test_groupby_first(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select job_title, (FIRST p FOR p IN ARRAY_AGG(name) END) as names from {0} group by " \ "job_title order by job_title ".format(query_bucket) actual_result = self.run_cbq_query() tmp_groups = {doc['job_title'] for doc in self.full_list} expected_list = [{"job_title": group, "names": ([x["name"] for x in self.full_list if x["job_title"] == group][0])} for group in tmp_groups] expected_result = self.sort_nested_list(expected_list) expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self.assertTrue(actual_result['results'] == expected_result) ############################################################################################## # # SCALAR FN ############################################################################################## def test_ceil(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name, ceil(test_rate) as rate from %s" % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['name'], doc['rate'])) expected_result = [{"name": doc['name'], "rate": math.ceil(doc['test_rate'])} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['name'], doc['rate'])) self._verify_results(actual_result, expected_result) self.query = "select name from %s where ceil(test_rate) > 5" % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['name'])) expected_result = [{"name": doc['name']} for doc in self.full_list if math.ceil(doc['test_rate']) > 5] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result, expected_result) def test_floor(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name, floor(test_rate) as rate from %s" % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['name'], doc['rate'])) expected_result = [{"name": doc['name'], "rate": math.floor(doc['test_rate'])} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['name'], doc['rate'])) self._verify_results(actual_result, expected_result) self.query = "select name from %s where floor(test_rate) > 5" % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['name'])) expected_result = [{"name": doc['name']} for doc in self.full_list if math.floor(doc['test_rate']) > 5] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result, expected_result) self.query = "select name from %s where floor(job_title) > 5" % query_bucket actual_result = self.run_cbq_query() self._verify_results(actual_result['results'], []) def test_greatest(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name, GREATEST(skills[0], skills[1]) as SKILL from %s" % ( query_bucket) actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['name'], doc['SKILL'])) expected_result = [{"name": doc['name'], "SKILL": (doc['skills'][0], doc['skills'][1])[doc['skills'][0] < doc['skills'][1]]} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['name'], doc['SKILL'])) self._verify_results(actual_result, expected_result) def test_least(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name, LEAST(skills[0], skills[1]) as SKILL from %s" % ( query_bucket) actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['name'], doc['SKILL'])) expected_result = [{"name": doc['name'], "SKILL": (doc['skills'][0], doc['skills'][1])[doc['skills'][0] > doc['skills'][1]]} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['name'], doc['SKILL'])) self._verify_results(actual_result, expected_result) def test_meta(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'SELECT distinct name FROM %s d WHERE META(d).`type` = "json"' % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['name'])) expected_result = [{"name": doc['name']} for doc in self.full_list] expected_result = [dict(y) for y in set(tuple(x.items()) for x in expected_result)] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result, expected_result) self.query = "SELECT distinct name FROM %s WHERE META().id IS NOT NULL" % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['name'])) self._verify_results(actual_result, expected_result) def test_meta_like(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'SELECT name FROM %s d WHERE META(d).id LIKE "%s"' % (query_bucket, "query%") actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['name'])) expected_result = [{"name": doc['name']} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result, expected_result) def test_prepared_meta_like(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'SELECT name FROM %s d WHERE META(d).id ' % query_bucket + 'LIKE "employee%"' self.prepared_common_body() if self.monitoring: self.query = 'select * from system:completed_requests' result = self.run_cbq_query() request_id = result['request_id'] self.query = 'delete from system:completed_requests where request_id = "%s"' % request_id self.run_cbq_query() result = self.run_cbq_query( 'select * from system:completed_requests where request_id = "%s"' % request_id) self.assertTrue(result['metrics']['resultCount'] == 0) def test_meta_flags(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'SELECT DISTINCT META().flags as flags FROM %s' % query_bucket actual_result = self.run_cbq_query() expected_result = [{"flags": self.item_flag}] self._verify_results(actual_result['results'], expected_result) def test_long_values(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'insert into %s values("k051", { "id":-9223372036854775808 } )' % query_bucket self.run_cbq_query() self.query = 'insert into %s values("k031", { "id":-9223372036854775807 } )' % query_bucket self.run_cbq_query() self.query = 'insert into %s values("k021", { "id":1470691191458562048 } )' % query_bucket self.run_cbq_query() self.query = 'insert into %s values("k011", { "id":9223372036854775807 } )' % query_bucket self.run_cbq_query() self.query = 'insert into %s values("k041", { "id":9223372036854775808 } )' % query_bucket self.run_cbq_query() self.query = 'select * from ' + query_bucket + ' d where meta().id = "{0}"'.format("k051") actual_result = self.run_cbq_query() print("k051 results is {0}".format(actual_result['results'][0]['d'])) # self.assertEqual(actual_result['results'][0]["default"],{'id': -9223372036854775808}) self.query = 'select * from ' + query_bucket + ' d where meta().id = "{0}"'.format("k031") actual_result = self.run_cbq_query() print("k031 results is {0}".format(actual_result['results'][0]['d'])) # self.assertEqual(actual_result['results'][0]["default"],{'id': -9223372036854775807}) self.query = 'select * from ' + query_bucket + ' d where meta().id = "{0}"'.format("k021") actual_result = self.run_cbq_query() print("k021 results is {0}".format(actual_result['results'][0]['d'])) # self.assertEqual(actual_result['results'][0]["default"],{'id': 1470691191458562048}) self.query = 'select * from ' + query_bucket + ' d where meta().id = "{0}"'.format("k011") actual_result = self.run_cbq_query() print("k011 results is {0}".format(actual_result['results'][0]['d'])) # self.assertEqual(actual_result['results'][0]["default"],{'id': 9223372036854775807}) self.query = 'select * from ' + query_bucket + ' d where meta().id = "{0}"'.format("k041") actual_result = self.run_cbq_query() print("k041 results is {0}".format(actual_result['results'][0]['d'])) # self.assertEqual(actual_result['results'][0]["default"],{'id': 9223372036854776000L}) self.query = 'delete from ' + query_bucket + ' where meta().id in ["k051","k021","k011","k041","k031"]' self.run_cbq_query() def test_meta_cas(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'select meta().cas from {0} order by meta().id limit 10'.format(query_bucket) actual_result = self.run_cbq_query() print(actual_result) def test_meta_negative(self): queries_errors = {'SELECT distinct name FROM %s WHERE META().type = "json"': ('syntax error', 3000)} self.negative_common_body(queries_errors) def test_length(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'Select name, email from %s where LENGTH(job_title) = 5' % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['name'])) expected_result = [{"name": doc['name'], "email": doc['email']} for doc in self.full_list if len(doc['job_title']) == 5] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result, expected_result) def test_upper(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'SELECT DISTINCT UPPER(job_title) as JOB from %s' % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['JOB'])) expected_result = [{"JOB": doc['job_title'].upper()} for doc in self.full_list] expected_result = [dict(y) for y in set(tuple(x.items()) for x in expected_result)] expected_result = sorted(expected_result, key=lambda doc: (doc['JOB'])) self._verify_results(actual_result, expected_result) def test_lower(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT distinct email from %s" % query_bucket + \ " WHERE LOWER(job_title) < 't'" actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['email'])) expected_result = [{"email": doc['email'].lower()} for doc in self.full_list if doc['job_title'].lower() < 't'] expected_result = [dict(y) for y in set(tuple(x.items()) for x in expected_result)] expected_result = sorted(expected_result, key=lambda doc: (doc['email'])) self._verify_results(actual_result, expected_result) def test_round(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name, round(test_rate) as rate from %s" % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['name'], doc['rate'])) expected_result = [{"name": doc["name"], "rate": round(doc['test_rate'])} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['name'], doc['rate'])) self._verify_results(actual_result, expected_result) def test_trunc(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name, TRUNC(test_rate, 0) as rate from %s" % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['name'], doc['rate'])) expected_result = [{"name": doc["name"], "rate": math.trunc(doc['test_rate'])} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['name'], doc['rate'])) self._verify_results(actual_result, expected_result) def test_first(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name, FIRST vm.os for vm in VMs end as OS from %s" % ( query_bucket) if self.analytics: self.query = "select name, VMs[0].os as OS from %s" % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['name'], doc['OS'])) expected_result = [{"name": doc["name"], "OS": doc['VMs'][0]["os"]} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['name'], doc['OS'])) self._verify_results(actual_result, expected_result) ############################################################################################## # # Substring ############################################################################################## def test_substr(self): self.fail_if_no_buckets() indices_to_test = [-100, -2, -1, 0, 1, 2, 100] for index in indices_to_test: for query_bucket in self.query_buckets: self.query = "select name, SUBSTR(email, %s) as DOMAIN from %s" % ( str(index), query_bucket) query_result = self.run_cbq_query() query_docs = query_result['results'] sorted_query_docs = sorted(query_docs, key=lambda doc: (doc['name'], doc['DOMAIN'])) expected_result = [{"name": doc["name"], "DOMAIN": self.expected_substr(doc['email'], 0, index)} for doc in self.full_list] sorted_expected_result = sorted(expected_result, key=lambda doc: ( doc['name'], doc['DOMAIN'])) self._verify_results(sorted_query_docs, sorted_expected_result) def test_substr0(self): self.fail_if_no_buckets() indices_to_test = [-100, -2, -1, 0, 1, 2, 100] for index in indices_to_test: for query_bucket in self.query_buckets: self.query = "select name, SUBSTR0(email, %s) as DOMAIN from %s" % ( str(index), query_bucket) query_result = self.run_cbq_query() query_docs = query_result['results'] sorted_query_docs = sorted(query_docs, key=lambda doc: (doc['name'], doc['DOMAIN'])) expected_result = [{"name": doc["name"], "DOMAIN": self.expected_substr(doc['email'], 0, index)} for doc in self.full_list] sorted_expected_result = sorted(expected_result, key=lambda doc: ( doc['name'], doc['DOMAIN'])) self._verify_results(sorted_query_docs, sorted_expected_result) def test_substr1(self): self.fail_if_no_buckets() indices_to_test = [-100, -2, -1, 0, 1, 2, 100] for index in indices_to_test: for query_bucket in self.query_buckets: self.query = "select name, SUBSTR1(email, %s) as DOMAIN from %s" % ( str(index), query_bucket) query_result = self.run_cbq_query() query_docs = query_result['results'] sorted_query_docs = sorted(query_docs, key=lambda doc: (doc['name'], doc['DOMAIN'])) expected_result = [{"name": doc["name"], "DOMAIN": self.expected_substr(doc['email'], 1, index)} for doc in self.full_list] sorted_expected_result = sorted(expected_result, key=lambda doc: ( doc['name'], doc['DOMAIN'])) self._verify_results(sorted_query_docs, sorted_expected_result) ############################################################################################## # # AGGR FN ############################################################################################## def test_agg_counters(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: vals = [] keys = [] for i in range(10): new_val = random.randint(0, 99) new_counter = "counter_US" + str(i) vals.append(new_val) keys.append(new_counter) self.query = 'INSERT INTO %s VALUES ("%s",%s)' % (query_bucket, new_counter, new_val) self.run_cbq_query() self.query = 'SELECT sum(d) FROM %s d USE KEYS %s;' % (query_bucket, str(keys)) actual_results = self.run_cbq_query() self.assertEqual(actual_results['results'][0]['$1'], sum(vals)) self.query = 'SELECT avg(d) FROM %s d USE KEYS %s;' % (query_bucket, str(keys)) actual_results = self.run_cbq_query() self.assertEqual(actual_results['results'][0]['$1'], float(sum(vals)) / max(len(vals), 1)) self.query = 'DELETE FROM %s USE KEYS %s;' % (query_bucket, str(keys)) actual_results = self.run_cbq_query() self.assertEqual(actual_results['results'], []) def test_sum(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT join_mo, SUM(tasks_points.task1) as points_sum" + \ " FROM %s WHERE join_mo < 5 GROUP BY join_mo " % query_bucket + \ "ORDER BY join_mo" if self.analytics: self.query = "SELECT d.join_mo, SUM(d.tasks_points.task1) as points_sum" + \ " FROM %s d WHERE d.join_mo < 5 GROUP BY d.join_mo " % query_bucket + \ "ORDER BY d.join_mo" actual_result = self.run_cbq_query() tmp_groups = {doc['join_mo'] for doc in self.full_list if doc['join_mo'] < 5} expected_result = [{"join_mo": group, "points_sum": int(math.fsum([doc['tasks_points']['task1'] for doc in self.full_list if doc['join_mo'] == group]))} for group in tmp_groups] self._verify_results(actual_result['results'], expected_result) self.query = "SELECT join_mo, SUM(test_rate) as rate FROM %s " % query_bucket + \ "as employees WHERE job_title='Sales' GROUP BY join_mo " + \ "HAVING SUM(employees.test_rate) > 0 and " + \ "SUM(test_rate) < 100000" if self.analytics: self.query = "SELECT d.join_mo, SUM(d.test_rate) as rate FROM %s d " % query_bucket + \ " WHERE d.job_title='Sales' GROUP BY d.join_mo " + \ "HAVING SUM(d.test_rate) > 0 and " + \ "SUM(d.test_rate) < 100000" actual_result = self.run_cbq_query() actual_result = [{"join_mo": doc["join_mo"], "rate": round(doc["rate"])} for doc in actual_result['results']] actual_result = sorted(actual_result, key=lambda doc: (doc['join_mo'])) tmp_groups = {doc['join_mo'] for doc in self.full_list} expected_result = [{"join_mo": group, "rate": round(math.fsum([doc['test_rate'] for doc in self.full_list if doc['join_mo'] == group and doc['job_title'] == 'Sales']))} for group in tmp_groups if math.fsum([doc['test_rate'] for doc in self.full_list if doc['join_mo'] == group and doc['job_title'] == 'Sales']) > 0 and math.fsum([doc['test_rate'] for doc in self.full_list if doc['join_mo'] == group and doc['job_title'] == 'Sales']) < 100000] expected_result = sorted(expected_result, key=lambda doc: (doc['join_mo'])) self._verify_results(actual_result, expected_result) def test_prepared_sum(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT join_mo, SUM(tasks_points.task1) as points_sum" + \ " FROM %s WHERE join_mo < 5 GROUP BY join_mo " % query_bucket + \ "ORDER BY join_mo" self.prepared_common_body() def test_sum_negative(self): queries_errors = {'SELECT join_mo, SUM(job_title) as rate FROM %s as employees' + ' WHERE job_title="Sales" GROUP BY join_mo': ('syntax error', 3000), 'SELECT join_mo, SUM(VMs) as rate FROM %s as employees' + ' WHERE job_title="Sales" GROUP BY join_mo': ('syntax error', 3000)} self.negative_common_body(queries_errors) def test_avg(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT join_mo, AVG(tasks_points.task1) as points_avg" + \ " FROM %s WHERE join_mo < 5 GROUP BY join_mo " % query_bucket + \ "ORDER BY join_mo" if self.analytics: self.query = "SELECT d.join_mo, AVG(d.tasks_points.task1) as points_avg" + \ " FROM %s d WHERE d.join_mo < 5 GROUP BY d.join_mo " % query_bucket + \ "ORDER BY d.join_mo" actual_result = self.run_cbq_query() tmp_groups = {doc['join_mo'] for doc in self.full_list if doc['join_mo'] < 5} expected_result = [{"join_mo": group, "points_avg": math.fsum([doc['tasks_points']['task1'] for doc in self.full_list if doc['join_mo'] == group]) / len([doc['tasks_points']['task1'] for doc in self.full_list if doc['join_mo'] == group])} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['join_mo'])) self._verify_results(actual_result['results'], expected_result) self.query = "SELECT join_mo, AVG(test_rate) as rate FROM %s " % query_bucket + \ "as employees WHERE job_title='Sales' GROUP BY join_mo " + \ "HAVING AVG(employees.test_rate) > 0 and " + \ "SUM(test_rate) < 100000" if self.analytics: self.query = "SELECT d.join_mo, AVG(d.test_rate) as rate FROM %s d" % query_bucket + \ " WHERE d.job_title='Sales' GROUP BY d.join_mo " + \ "HAVING AVG(d.test_rate) > 0 and " + \ "SUM(d.test_rate) < 100000" actual_result = self.run_cbq_query() actual_result = [{'join_mo': doc['join_mo'], 'rate': round(doc['rate'], 2)} for doc in actual_result['results']] actual_result = sorted(actual_result, key=lambda doc: (doc['join_mo'])) tmp_groups = {doc['join_mo'] for doc in self.full_list} expected_result = [{"join_mo": group, "rate": math.fsum([doc['test_rate'] for doc in self.full_list if doc['join_mo'] == group and doc['job_title'] == 'Sales']) / len([doc['test_rate'] for doc in self.full_list if doc['join_mo'] == group and doc['job_title'] == 'Sales'])} for group in tmp_groups if (math.fsum([doc['test_rate'] for doc in self.full_list if doc['join_mo'] == group and doc['job_title'] == 'Sales']) / len([doc['test_rate'] for doc in self.full_list if doc['join_mo'] == group and doc['job_title'] == 'Sales']) > 0) and math.fsum([doc['test_rate'] for doc in self.full_list if doc['join_mo'] == group and doc['job_title'] == 'Sales']) < 100000] expected_result = [{'join_mo': doc['join_mo'], 'rate': round(doc['rate'], 2)} for doc in expected_result] expected_result = sorted(expected_result, key=lambda doc: (doc['join_mo'])) self._verify_results(actual_result, expected_result) def test_min(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: query_bucket = self.get_collection_name(query_bucket) self.query = "SELECT join_mo, MIN(test_rate) as rate FROM %s " % query_bucket + \ "as employees WHERE job_title='Sales' GROUP BY join_mo " + \ "HAVING MIN(employees.test_rate) > 0 and " + \ "SUM(test_rate) < 100000" actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['join_mo'])) tmp_groups = {doc['join_mo'] for doc in self.full_list} expected_result = [{"join_mo": group, "rate": min([doc['test_rate'] for doc in self.full_list if doc['join_mo'] == group and doc['job_title'] == 'Sales'])} for group in tmp_groups if min([doc['test_rate'] for doc in self.full_list if doc['join_mo'] == group and doc['job_title'] == 'Sales']) > 0 and math.fsum([doc['test_rate'] for doc in self.full_list if doc['join_mo'] == group and doc['job_title'] == 'Sales']) < 100000] expected_result = sorted(expected_result, key=lambda doc: (doc['join_mo'])) self._verify_results(actual_result, expected_result) def test_max(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT join_mo, MAX(test_rate) as rate FROM %s " % query_bucket + \ "as employees WHERE job_title='Sales' GROUP BY join_mo " + \ "HAVING MAX(employees.test_rate) > 0 and " + \ "SUM(test_rate) < 100000" actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['join_mo'])) tmp_groups = {doc['join_mo'] for doc in self.full_list} expected_result = [{"join_mo": group, "rate": max([doc['test_rate'] for doc in self.full_list if doc['join_mo'] == group and doc['job_title'] == 'Sales'])} for group in tmp_groups if max([doc['test_rate'] for doc in self.full_list if doc['join_mo'] == group and doc['job_title'] == 'Sales']) > 0 and math.fsum([doc['test_rate'] for doc in self.full_list if doc['join_mo'] == group and doc['job_title'] == 'Sales']) < 100000] expected_result = sorted(expected_result, key=lambda doc: (doc['join_mo'])) self._verify_results(actual_result, expected_result) def test_array_agg_distinct(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, array_agg(DISTINCT name) as names" + \ " FROM %s GROUP BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = self.sort_nested_list(actual_list['results']) actual_result = sorted(actual_result, key=lambda doc: (doc['job_title'])) tmp_groups = {doc['job_title'] for doc in self.full_list} expected_list = [{"job_title": group, "names": {x["name"] for x in self.full_list if x["job_title"] == group}} for group in tmp_groups] expected_result = self.sort_nested_list(expected_list) expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result, expected_result) def test_array_length(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, array_length(array_agg(DISTINCT name)) as num_names" + \ " FROM %s GROUP BY job_title" % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['job_title'])) tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "num_names": len({x["name"] for x in self.full_list if x["job_title"] == group})} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result, expected_result) self.query = "SELECT job_title, array_length(array_agg(DISTINCT test_rate)) as rates" + \ " FROM %s GROUP BY job_title" % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['job_title'])) expected_result = [{"job_title": group, "rates": len({x["test_rate"] for x in self.full_list if x["job_title"] == group})} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result, expected_result) def test_array_append(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: query_bucket = self.get_collection_name(query_bucket) self.query = "SELECT job_title," + \ " array_append(array_agg(DISTINCT name), 'new_name') as names" + \ " FROM %s GROUP BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = self.sort_nested_list(actual_list['results']) actual_result = sorted(actual_result, key=lambda doc: (doc['job_title'])) tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "names": sorted(set([x["name"] for x in self.full_list if x["job_title"] == group] + ['new_name']))} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result, expected_result) self.query = "SELECT job_title," + \ " array_append(array_agg(DISTINCT name), 'new_name','123') as names" + \ " FROM %s GROUP BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = self.sort_nested_list(actual_list['results']) actual_result = sorted(actual_result, key=lambda doc: (doc['job_title'])) tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "names": sorted(set([x["name"] for x in self.full_list if x["job_title"] == group] + ['new_name'] + ['123']))} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result, expected_result) def test_prepared_array_append(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title," + \ " array_append(array_agg(DISTINCT name), 'new_name') as names" + \ " FROM %s GROUP BY job_title" % query_bucket self.prepared_common_body() def test_array_union_symdiff(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'select ARRAY_SORT(ARRAY_UNION(["skill1","skill2","skill2010","skill2011"],skills)) as ' \ 'skills_union from {0} order by meta().id limit 5'.format(query_bucket) actual_result = self.run_cbq_query() expected_result = [{'skills_union': ['skill1', 'skill2', 'skill2010', 'skill2011']}, {'skills_union': ['skill1', 'skill2', 'skill2010', 'skill2011']}, {'skills_union': ['skill1', 'skill2', 'skill2010', 'skill2011']}, {'skills_union': ['skill1', 'skill2', 'skill2010', 'skill2011']}, {'skills_union': ['skill1', 'skill2', 'skill2010', 'skill2011']}] self.assertTrue(actual_result['results'] == expected_result, f"{actual_result["results"]} not matching with {expected_result}") self.query = 'select ARRAY_SORT(ARRAY_SYMDIFF(["skill1","skill2","skill2010","skill2011"],skills)) as ' \ 'skills_diff1 from {0} order by meta().id limit 5'.format(query_bucket) actual_result = self.run_cbq_query() self.assertTrue(actual_result['results'] == [{'skills_diff1': ['skill1', 'skill2']}, {'skills_diff1': ['skill1', 'skill2']}, {'skills_diff1': ['skill1', 'skill2']}, {'skills_diff1': ['skill1', 'skill2']}, {'skills_diff1': ['skill1', 'skill2']}]) self.query = 'select ARRAY_SORT(ARRAY_SYMDIFF1(skills,["skill2010","skill2011","skill2012"],' \ '["skills2010","skill2017"])) as skills_diff2 from {0} order by ' \ 'meta().id limit 5'.format(query_bucket) actual_result1 = self.run_cbq_query() self.assertTrue( actual_result1['results'] == [{'skills_diff2': ['skill2012', 'skill2017', 'skills2010']}, {'skills_diff2': ['skill2012', 'skill2017', 'skills2010']}, {'skills_diff2': ['skill2012', 'skill2017', 'skills2010']}, {'skills_diff2': ['skill2012', 'skill2017', 'skills2010']}, {'skills_diff2': ['skill2012', 'skill2017', 'skills2010']}]) self.query = 'select ARRAY_SORT(ARRAY_SYMDIFFN(skills,["skill2010","skill2011","skill2012"],' \ '["skills2010","skill2017"])) as skills_diff3 from {0} order by ' \ 'meta().id limit 5'.format(query_bucket) actual_result = self.run_cbq_query() self.assertTrue(actual_result['results'] == [{'skills_diff3': ['skill2012', 'skill2017', 'skills2010']}, {'skills_diff3': ['skill2012', 'skill2017', 'skills2010']}, {'skills_diff3': ['skill2012', 'skill2017', 'skills2010']}, {'skills_diff3': ['skill2012', 'skill2017', 'skills2010']}, {'skills_diff3': ['skill2012', 'skill2017', 'skills2010']}]) def test_let(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'select * from %s let x1 = {"name":1} order by meta().id limit 1' % query_bucket actual_result = self.run_cbq_query() if "query-testemployee10153.1877827" not in str(actual_result['results']): self.assertTrue(False, str(actual_result['results'])) self.assertTrue("'x1': {'name': 1}" in str(actual_result['results'])) def test_let_missing(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: created_indexes = [] try: self.query = 'CREATE INDEX ix1 on %s(x1)' % query_bucket self.run_cbq_query() created_indexes.append("ix1") self.query = 'INSERT INTO %s VALUES ("k01",{"x1":5, "type":"doc", "x2": "abc"}), ' \ '("k02",{"x1":5, "type":"d", "x2": "def"})' % query_bucket self.run_cbq_query() self.query = 'EXPLAIN SELECT x1, x2 FROM %s o LET o = CASE WHEN o.type = "doc" THEN o ELSE MISSING ' \ 'END WHERE x1 = 5' % query_bucket try: self.run_cbq_query(self.query) except CBQError as ex: self.assertTrue(str(ex).find("Duplicate variable o (near line 1, column 57) already in scope.") != -1 or str(ex).find("Duplicate variable o (near line 1, column 66) already in scope.") != -1, "Error is incorrect.") else: self.fail("There was no errors.") self.query = 'delete from %s use keys["k01","k02"]' % query_bucket self.run_cbq_query() finally: for idx in created_indexes: self.query = "DROP INDEX %s ON %s USING %s" % (idx, query_bucket, self.index_type) self.run_cbq_query() def test_optimized_let(self): self.fail_if_no_buckets() self.query = 'explain select name1 from ' + self.query_buckets[ 0] + ' d let name1 = substr(name[0].FirstName,0,10) WHERE name1 = "employeefi"' res = self.run_cbq_query() plan = self.ExplainPlanHelper(res) for operator in plan['~children'][2]['~child']['~children']: if operator['#operator'] == 'Filter': self.assertTrue(operator['condition'] == '(`name1` = "employeefi")' or operator['condition'] == '(substr0((((`d`.`name`)[0]).`FirstName`), 0, 10) = "employeefi")') if operator['#operator'] == 'Let': self.assertEqual(operator['bindings'], [{'expr': 'substr0((((`d`.`name`)[0]).`FirstName`), 0, 10)', 'var': 'name1'}]) if operator['#operator'] == 'InitialProject': self.assertEqual(operator['result_terms'], [{'expr': '`name1`'}]) self.query = 'select name1 from ' + self.query_buckets[ 0] + ' d let name1 = substr(name[0].FirstName,0,10) WHERE name1 = "employeefi" limit 2' res = self.run_cbq_query() self.assertEqual(res['results'], [{'name1': 'employeefi'}, {'name1': 'employeefi'}]) self.query = 'explain select name1 from ' + self.query_buckets[ 0] + ' d let name1 = substr(name[0].FirstName,0,10) WHERE name[0].MiddleName = "employeefirstname-4"' res = self.run_cbq_query() plan = self.ExplainPlanHelper(res) self.assertEqual(plan['~children'][2]['~child']['~children'], [{'#operator': 'Filter', 'condition': '((((`d`.`name`)[0]).`MiddleName`) = "employeefirstname-4")'}, {'#operator': 'Let', 'bindings': [ {'var': 'name1', 'expr': 'substr0((((`d`.`name`)[0]).`FirstName`), 0, 10)'}]}, {'#operator': 'InitialProject', 'result_terms': [{'expr': '`name1`'}]}]) self.query = 'select name1 from ' + self.query_buckets[0] + \ ' let name1 = substr(name[0].FirstName,0,10) WHERE name[0].MiddleName = "employeefirstname-4" ' \ 'limit 10 ' res = self.run_cbq_query() self.assertTrue(res['results'] == []) def test_correlated_queries(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: if query_bucket == self.default_bucket_name: try: self.query = 'create index ix1 on %s(x,id)' % query_bucket self.run_cbq_query() self.query = 'insert into %s (KEY, VALUE) VALUES ' \ '("kk02",{"x":100,"y":101,"z":102,"id":"kk02"})' % query_bucket self.run_cbq_query() self.query = 'explain select d.x from {0} d where x in (select raw d.x from {0} b ' \ 'use keys ["kk02"])'.format(query_bucket) actual_result = self.run_cbq_query() plan = self.ExplainPlanHelper(actual_result) self.assertTrue("covers" in str(plan)) self.assertTrue(plan['~children'][0]['index'] == 'ix1') self.query = 'select d.x from {0} d where x in (select raw d.x from {0} b ' \ 'use keys ["kk02"])'.format(query_bucket) actual_result = self.run_cbq_query() self.assertTrue(actual_result['results'] == [{'x': 100}]) self.query = 'explain select d.x from {0} d where x IN (select raw d.x from {0} ' \ 'b use keys[d.id])'.format(query_bucket) actual_result = self.run_cbq_query() plan = self.ExplainPlanHelper(actual_result) self.assertTrue("covers" in str(plan)) self.assertTrue(plan['~children'][0]['index'] == 'ix1') self.query = 'select d.x from {0} d where x IN (select raw d.x from {0}' \ ' b use keys[d.id])'.format(query_bucket) actual_result = self.run_cbq_query() self.assertTrue(actual_result['results'] == [{'x': 100}]) self.query = 'explain select d.x from {0} d where x IN (select raw b.x from {0} b where b.x IN (' \ 'select raw d.x from {0} c use keys["kk02"]))'.format(query_bucket) actual_result = self.run_cbq_query() plan = self.ExplainPlanHelper(actual_result) self.assertTrue("covers" in str(plan)) self.assertTrue(plan['~children'][0]['index'] == 'ix1') self.query = 'select d.x from {0} d where x IN (select raw b.x from {0} b ' \ ' where b.x IN (select raw ' \ 'd.x from {0} c use keys["kk02"]))'.format(query_bucket) actual_result = self.run_cbq_query() self.assertTrue(actual_result['results'] == [{'x': 100}]) self.query = 'explain select d.x from {0} d where x IN (select raw b.x from {0} b where b.x IN (' \ 'select raw d.x from {0} c use keys["kk02"] where d.x = b.x))'.format(query_bucket) actual_result = self.run_cbq_query() plan = self.ExplainPlanHelper(actual_result) self.assertTrue("covers" in str(plan)) self.assertTrue(plan['~children'][0]['index'] == 'ix1') self.query = 'select d.x from {0} d where x IN (select raw b.x from {0} b ' \ ' where b.x IN (select raw ' \ 'd.x from {0} c use keys["kk02"] where d.x = b.x))'.format(query_bucket) actual_result = self.run_cbq_query() self.assertTrue(actual_result['results'] == [{'x': 100}]) self.query = 'explain select d.x from {0} d where x IN (select raw b.x from {0} b where b.x IN (' \ 'select raw d.x from {0} c use keys["kk02"] where d.x = b.x))'.format(query_bucket) actual_result = self.run_cbq_query() plan = self.ExplainPlanHelper(actual_result) self.assertTrue("covers" in str(plan)) self.assertTrue(plan['~children'][0]['index'] == 'ix1') self.query = 'select d.x from {0} d where x IN (select raw b.x from {0} b' \ ' where b.x IN (select raw ' \ 'd.x from {0} c use keys["kk02"] where d.x = b.x))'.format(query_bucket) actual_result = self.run_cbq_query() self.assertTrue(actual_result['results'] == [{'x': 100}]) self.query = 'explain select d.x from {0} d where x IN (select raw b.x' \ ' from {0} b use keys["kk02"] ' \ 'where b.x IN (select raw d.x from {0} c use keys["kk02"]))'.format(query_bucket) actual_result = self.run_cbq_query() plan = self.ExplainPlanHelper(actual_result) self.assertTrue("covers" in str(plan)) self.assertTrue(plan['~children'][0]['index'] == 'ix1') self.query = 'select d.x from {0} d where x IN (select raw b.x from {0} b use keys["kk02"] ' \ 'where b.x IN (select raw d.x from {0} c use keys["kk02"]))'.format(query_bucket) actual_result = self.run_cbq_query() self.assertTrue(actual_result['results'] == [{'x': 100}]) self.query = 'explain select d.x,d.id from {0} d where x IN (select raw b.x from {0} b where ' \ 'b.x IN (select raw d.x from {0} c use keys["kk02"]))'.format(query_bucket) actual_result = self.run_cbq_query() plan = self.ExplainPlanHelper(actual_result) self.assertTrue("covers" in str(plan)) self.assertTrue(plan['~children'][0]['index'] == 'ix1') self.query = 'select d.x,d.y from {0} d where x IN (select raw b.x from {0} b where b.x ' \ 'IN (select raw d.x from {0} c use keys["kk02"]))'.format(query_bucket) actual_result = self.run_cbq_query() diffs = DeepDiff(actual_result['results'], [{'y': 101, 'x': 100}], ignore_order=True) if diffs: self.assertTrue(False, diffs) self.query = 'explain select d.x from {0} d where x IN (select raw (select raw d.x from {0}' \ ' c use keys[d.id] where d.x = b.x)[0] from {0} b ' \ 'where b.x is not null)'.format(query_bucket) self.run_cbq_query() self.assertTrue("covers" in str(plan)) self.assertTrue(plan['~children'][0]['index'] == 'ix1') self.query = 'select d.x from {0} d where x IN (select raw (select raw d.x from {0} c ' \ 'use keys[d.id] where d.x = b.x)[0] from {0} b where b.x ' \ 'is not null)'.format(query_bucket) actual_result = self.run_cbq_query() self.assertTrue(actual_result['results'] == [{'x': 100}]) self.query = 'explain select (select raw d.x from ' + self.query_buckets[0] + \ ' c use keys[d.id]) as s, d.x from ' + self.query_buckets[0] + \ ' d where x is not null' actual_result = self.run_cbq_query() plan = self.ExplainPlanHelper(actual_result) # print plan self.assertTrue("covers" in str(plan)) self.assertTrue(plan['~children'][0]['index'] == 'ix1') self.query = 'select (select raw d.x from ' + self.query_buckets[0] + \ ' c use keys[d.id]) as s, d.x from ' + self.query_buckets[0] + \ ' d where x is not null' actual_result = self.run_cbq_query() diffs = DeepDiff(actual_result['results'], [{'x': 100, 's': [100]}], ignore_order=True) self.assertEqual(diffs, {}) finally: self.query = 'delete from %s use keys["kk02"]' % query_bucket self.run_cbq_query() self.query = "DROP INDEX %s ON %s USING %s" % ("ix1", query_bucket, self.index_type) self.run_cbq_query() # This test has no uses anywhere def test_object_concat_remove(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'select object_concat({"name":"test"},{"test":123},tasks_points) as obj from %s order by ' \ 'meta().id limit 10;' % query_bucket actual_result = self.run_cbq_query() self.assertTrue(actual_result['results'] == ( [{'obj': {'test': 123, 'task1': 1, 'task2': 1, 'name': 'test'}}, {'obj': {'test': 123, 'task1': 1, 'task2': 1, 'name': 'test'}}, {'obj': {'test': 123, 'task1': 1, 'task2': 1, 'name': 'test'}}, {'obj': {'test': 123, 'task1': 1, 'task2': 1, 'name': 'test'}}, {'obj': {'test': 123, 'task1': 1, 'task2': 1, 'name': 'test'}}, {'obj': {'test': 123, 'task1': 1, 'task2': 1, 'name': 'test'}}, {'obj': {'test': 123, 'task1': 1, 'task2': 1, 'name': 'test'}}, {'obj': {'test': 123, 'task1': 1, 'task2': 1, 'name': 'test'}}, {'obj': {'test': 123, 'task1': 1, 'task2': 1, 'name': 'test'}}, {'obj': {'test': 123, 'task1': 1, 'task2': 1, 'name': 'test'}}])) self.query = 'select OBJECT_REMOVE({"abc":1,"def":2,"fgh":3},"def")' actual_result = self.run_cbq_query() self.assertTrue(actual_result['results'], ([{'$1': {'abc': 1, 'fgh': 3}}])) def test_array_concat(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title," + \ " array_concat(array_agg(name), array_agg(email)) as names" + \ " FROM %s GROUP BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = self.sort_nested_list(actual_list['results']) actual_result1 = sorted(actual_result, key=lambda doc: (doc['job_title'])) tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "names": [x["name"] for x in self.full_list if x["job_title"] == group] + [x["email"] for x in self.full_list if x["job_title"] == group]} for group in tmp_groups] expected_result1 = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result1, expected_result1) self.query = "SELECT job_title," + \ " array_concat(array_agg(name), array_agg(email),array_agg(join_day)) as names" + \ " FROM %s GROUP BY job_title limit 10" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"job_title": group, "names": [x["name"] for x in self.full_list if x["job_title"] == group] + [x["email"] for x in self.full_list if x["job_title"] == group] + [x["join_day"] for x in self.full_list if x["job_title"] == group]} for group in tmp_groups][0:10] diffs = DeepDiff(actual_result, expected_result, ignore_order=True) if diffs: self.assertTrue(False, diffs) def test_array_prepend(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title," + \ " array_prepend(1.2, array_agg(test_rate)) as rates" + \ " FROM %s GROUP BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = self.sort_nested_list(actual_list['results']) actual_result = sorted(actual_result, key=lambda doc: (doc['job_title'])) tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "rates": [x["test_rate"] for x in self.full_list if x["job_title"] == group] + [1.2]} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result, expected_result) self.query = "SELECT job_title," + \ " array_prepend(1.2,2.4, array_agg(test_rate)) as rates" + \ " FROM %s GROUP BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = self.sort_nested_list(actual_list['results']) actual_result = sorted(actual_result, key=lambda doc: (doc['job_title'])) tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "rates": [x["test_rate"] for x in self.full_list if x["job_title"] == group] + [1.2] + [2.4]} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result, expected_result) self.query = "SELECT job_title," + \ " array_prepend(['skill5', 'skill8'], array_agg(skills)) as skills_new" + \ " FROM %s GROUP BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = self.sort_nested_list(actual_list['results']) actual_result = sorted(actual_result, key=lambda doc: (doc['job_title'])) tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "skills_new": [x["skills"] for x in self.full_list if x["job_title"] == group] + [['skill5', 'skill8']]} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result, expected_result) self.query = "SELECT job_title," + \ " array_prepend(['skill5', 'skill8'],['skill9','skill10'], array_agg(skills)) as " + \ " skills_new FROM %s GROUP BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = self.sort_nested_list(actual_list['results']) actual_result = sorted(actual_result, key=lambda doc: (doc['job_title'])) tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "skills_new": [x["skills"] for x in self.full_list if x["job_title"] == group] + [['skill5', 'skill8']] + [['skill9', 'skill10']]} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result, expected_result) def test_array_remove(self): self.fail_if_no_buckets() value = 'employee-1' for query_bucket in self.query_buckets: self.query = "SELECT job_title," + \ " array_remove(array_agg(DISTINCT name), '%s') as names" % value + \ " FROM %s GROUP BY job_title ORDER BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = self.sort_nested_list(actual_list['results']) tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "names": [x["name"] for x in self.full_list if x["job_title"] == group and x["name"] != value]} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result, expected_result) value1 = 'employee-2' value2 = 'emp-2' value3 = 'employee-1' self.query = "SELECT job_title," + \ " array_remove(array_agg(DISTINCT name), '%s','%s','%s') as " % (value1, value2, value3) + \ " names FROM %s GROUP BY job_title ORDER BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "names": [x["name"] for x in self.full_list if x["job_title"] == group and x["name"] != value1 and x[ "name"] != value3]} for group in tmp_groups] self._verify_results(actual_result, expected_result) def test_array_insert(self): value1 = 'skill-20' value2 = 'skill-21' self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT array_insert(skills, 1, '%s','%s') " % (value1, value2) + \ " FROM %s limit 1" % query_bucket actual_list = self.run_cbq_query() expected_result = [{'$1': ['skill2010', 'skill-20', 'skill-21', 'skill2011']}] self.assertTrue(actual_list['results'] == expected_result) def test_array_avg(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, array_avg(array_agg(test_rate))" + \ " as rates FROM %s GROUP BY job_title ORDER BY job_title" % query_bucket actual_result = self.run_cbq_query() for doc in actual_result['results']: doc['rates'] = round(doc['rates']) tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "rates": round(sum([x["test_rate"] for x in self.full_list if x["job_title"] == group]) / float(len([x["test_rate"] for x in self.full_list if x[ "job_title"] == group])))} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result['results'], expected_result) def test_array_contains(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, array_contains(array_agg(name), 'employee-1')" + \ " as emp_job FROM %s GROUP BY job_title ORDER BY job_title" % query_bucket actual_result = self.run_cbq_query() actual_result = actual_result['results'] tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "emp_job": 'employee-1' in [x["name"] for x in self.full_list if x["job_title"] == group]} for group in tmp_groups] self._verify_results(actual_result, expected_result) def test_array_count(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, array_count(array_agg(name)) as names" + \ " FROM %s GROUP BY job_title ORDER BY job_title" % query_bucket actual_result = self.run_cbq_query() tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "names": len([x["name"] for x in self.full_list if x["job_title"] == group])} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result['results'], expected_result) def test_array_distinct(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, array_distinct(array_agg(name)) as names" + \ " FROM %s GROUP BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "names": [x["name"] for x in self.full_list if x["job_title"] == group]} for group in tmp_groups] for item in actual_result: self.assertTrue(item not in expected_result, f"{actual_result} not matching with {expected_result}") def test_array_max(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, array_max(array_agg(test_rate)) as rates" + \ " FROM %s GROUP BY job_title ORDER BY job_title" % query_bucket actual_result = self.run_cbq_query() tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "rates": max([x["test_rate"] for x in self.full_list if x["job_title"] == group])} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result['results'], expected_result) def test_array_sum(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, round(array_sum(array_agg(test_rate))) as rates" + \ " FROM %s GROUP BY job_title ORDER BY job_title" % query_bucket actual_result = self.run_cbq_query() tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "rates": round(sum([x["test_rate"] for x in self.full_list if x["job_title"] == group]))} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result['results'], expected_result) def test_array_min(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, array_min(array_agg(test_rate)) as rates" + \ " FROM %s GROUP BY job_title ORDER BY job_title" % query_bucket actual_result = self.run_cbq_query() tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "rates": min([x["test_rate"] for x in self.full_list if x["job_title"] == group])} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result['results'], expected_result) def test_array_position(self): self.query = "select array_position(['support', 'qa'], 'dev') as index_num" actual_result = self.run_cbq_query() expected_result = [{"index_num": -1}] self._verify_results(actual_result['results'], expected_result) self.query = "select array_position(['support', 'qa'], 'qa') as index_num" actual_result = self.run_cbq_query() expected_result = [{"index_num": 1}] self._verify_results(actual_result['results'], expected_result) def test_array_put(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, array_put(array_agg(distinct name), 'employee-1') as emp_job" + \ " FROM %s GROUP BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "emp_job": [x["name"] for x in self.full_list if x["job_title"] == group]} for group in tmp_groups] for item in actual_result: self.assertTrue(item not in expected_result, f"{actual_result} not matching with {expected_result}") self.query = "SELECT job_title, array_put(array_agg(distinct name), 'employee-50','employee-51') as " + \ " emp_job FROM %s GROUP BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "emp_job": [x["name"] for x in self.full_list if x["job_title"] == group] + ['employee-50'] + [ 'employee-51']} for group in tmp_groups] for item in actual_result: self.assertTrue(item not in expected_result, f"{actual_result} not matching with {expected_result}") self.query = "SELECT job_title, array_put(array_agg(distinct name), 'employee-47') as emp_job" + \ " FROM %s GROUP BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"job_title": group, "emp_job": [x["name"] for x in self.full_list if x["job_title"] == group] + ['employee-47']} for group in tmp_groups] for item in actual_result: self.assertTrue(item not in expected_result, f"{actual_result} not matching with {expected_result}") def test_array_range(self): self.query = "select array_range(0,10) as num" actual_result = self.run_cbq_query() expected_result = [{"num": list(range(10))}] self._verify_results(actual_result['results'], expected_result) def test_array_replace(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, array_replace(array_agg(name), 'employee-1', 'employee-47') as emp_job" + \ " FROM %s GROUP BY job_title ORDER BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = self.sort_nested_list(actual_list['results']) tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "emp_job": ["employee-47" if x["name"] == 'employee-1' else x["name"] for x in self.full_list if x["job_title"] == group]} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result, expected_result) def test_array_repeat(self): self.query = "select ARRAY_REPEAT(2, 2) as num" actual_result = self.run_cbq_query() expected_result = [{"num": [2] * 2}] self._verify_results(actual_result['results'], expected_result) def test_array_reverse(self): self.query = "select array_reverse([1,2,3]) as num" actual_result = self.run_cbq_query() expected_result = [{"num": [3, 2, 1]}] self._verify_results(actual_result['results'], expected_result) def test_array_sort(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, array_sort(array_agg(distinct test_rate)) as emp_job" + \ " FROM %s GROUP BY job_title ORDER BY job_title" % query_bucket actual_result = self.run_cbq_query() tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "emp_job": [x["test_rate"] for x in self.full_list if x["job_title"] == group]} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) for item in actual_result['results']: self.assertTrue(item not in expected_result, f"{actual_result} not matching with {expected_result}") # This test has no usages anywhere def test_poly_length(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: query_fields = ['tasks_points', 'VMs', 'skills'] for query_field in query_fields: self.query = "Select length(%s) as custom_num from %s order by custom_num" % (query_field, query_bucket) actual_result = self.run_cbq_query() expected_result = [{"custom_num": None} for _ in self.full_list] self._verify_results(actual_result['results'], expected_result) self.query = "Select poly_length(%s) as custom_num from %s order by custom_num" % ( query_field, query_bucket) actual_result = self.run_cbq_query() expected_result = [{"custom_num": len(doc[query_field])} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['custom_num'])) self._verify_results(actual_result['results'], expected_result) def test_array_agg(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, array_agg(name) as names" + \ " FROM %s GROUP BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = self.sort_nested_list(actual_list['results']) actual_result = sorted(actual_result, key=lambda doc: (doc['job_title'])) tmp_groups = {doc['job_title'] for doc in self.full_list} expected_list = [{"job_title": group, "names": [x["name"] for x in self.full_list if x["job_title"] == group]} for group in tmp_groups] expected_result = self.sort_nested_list(expected_list) expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result, expected_result) ############################################################################################## # # EXPRESSIONS ############################################################################################## def test_case(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: query_bucket = self.get_collection_name(query_bucket) self.query = "SELECT name, CASE WHEN join_mo < 3 OR join_mo > 11 THEN 'winter'" + \ " WHEN join_mo < 6 AND join_mo > 2 THEN 'spring' " + \ "WHEN join_mo < 9 AND join_mo > 5 THEN 'summer' " + \ "ELSE 'autumn' END AS period FROM %s" % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: ( doc['name'], doc['period'])) expected_result = [{"name": doc['name'], "period": ((('autumn', 'summer')[doc['join_mo'] in [6, 7, 8]], 'spring')[doc['join_mo'] in [3, 4, 5]], 'winter') [doc['join_mo'] in [12, 1, 2]]} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['name'], doc['period'])) self._verify_results(actual_result, expected_result) def test_case_expr(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: query_bucket = self.get_collection_name(query_bucket) self.query = "SELECT name, CASE job_title WHEN 'Sales' THEN 'Marketing'" + \ "ELSE job_title END AS dept FROM %s" % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: ( doc['name'], doc['dept'])) expected_result = [{"name": doc['name'], "dept": (doc['job_title'], 'Marketing')[doc['job_title'] == 'Sales']} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['name'], doc['dept'])) self._verify_results(actual_result, expected_result) def test_case_arithm(self): self.query = "SELECT CASE WHEN 1+1=3 THEN 7+7 WHEN 2+2=5 THEN 8+8 ELSE 2 END" actual_result = self.run_cbq_query() expected_result = [{"$1": 2}] self._verify_results(actual_result['results'], expected_result) def test_in_int(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name from %s where join_mo in [1,6]" % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['name'])) expected_result = [{"name": doc['name']} for doc in self.full_list if doc['join_mo'] in [1, 6]] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result, expected_result) self.query = "select name from %s where join_mo not in [1,6]" % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: ( doc['name'])) expected_result = [{"name": doc['name']} for doc in self.full_list if not (doc['join_mo'] in [1, 6])] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result, expected_result) def test_in_str(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name from %s where job_title in ['Sales', 'Support']" % query_bucket actual_result = self.run_cbq_query() self.query = "select name from %s where REVERSE(job_title) in ['selaS', 'troppuS']" % query_bucket actual_result1 = self.run_cbq_query() self.assertEqual(actual_result['results'], actual_result1['results']) actual_result = sorted(actual_result['results'], key=lambda doc: ( doc['name'])) expected_result = [{"name": doc['name']} for doc in self.full_list if doc['job_title'] in ['Sales', 'Support']] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result, expected_result) self.query = "select name from %s where job_title not in ['Sales', 'Support']" % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: ( doc['name'])) expected_result = [{"name": doc['name']} for doc in self.full_list if not (doc['job_title'] in ['Sales', 'Support'])] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result, expected_result) def test_prepared_in_str(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name from %s where job_title in ['Sales', 'Support']" % query_bucket self.prepared_common_body() def test_logic_expr(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT tasks_points.task1 as task FROM %s WHERE " % query_bucket + \ "tasks_points.task1 > 1 AND tasks_points.task1 < 4" actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: ( doc['task'])) expected_result = [{"task": doc['tasks_points']['task1']} for doc in self.full_list if 1 < doc['tasks_points']['task1'] < 4] expected_result = sorted(expected_result, key=lambda doc: (doc['task'])) self._verify_results(actual_result, expected_result) def test_comparition_equal_int(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT tasks_points.task1 as task FROM %s WHERE " % query_bucket + "tasks_points.task1 = 4" actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: ( doc['task'])) expected_result = [{"task": doc['tasks_points']['task1']} for doc in self.full_list if doc['tasks_points']['task1'] == 4] expected_result = sorted(expected_result, key=lambda doc: (doc['task'])) self._verify_results(actual_result, expected_result) self.query = "SELECT tasks_points.task1 as task FROM %s WHERE " % query_bucket + "tasks_points.task1 == 4" actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: ( doc['task'])) self._verify_results(actual_result, expected_result) def test_comparition_equal_str(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name FROM %s WHERE " % query_bucket + "name = 'employee-4'" actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: ( doc['name'])) expected_result = [{"name": doc['name']} for doc in self.full_list if doc['name'] == 'employee-4'] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result, expected_result) self.query = "SELECT name FROM %s WHERE " % query_bucket + "name == 'employee-4'" actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: ( doc['name'])) self._verify_results(actual_result, expected_result) def test_comparition_not_equal(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT tasks_points.task1 as task FROM %s WHERE " % query_bucket + \ "tasks_points.task1 != 1 ORDER BY task" actual_result = self.run_cbq_query() actual_result = actual_result['results'] expected_result = [{"task": doc['tasks_points']['task1']} for doc in self.full_list if doc['tasks_points']['task1'] != 1] expected_result = sorted(expected_result, key=lambda doc: (doc['task'])) self._verify_results(actual_result, expected_result) def test_comparition_not_equal_more_less(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT tasks_points.task1 as task FROM %s WHERE " % query_bucket + \ "tasks_points.task1 <> 1 ORDER BY task" actual_result = self.run_cbq_query() actual_result = actual_result['results'] expected_result = [{"task": doc['tasks_points']['task1']} for doc in self.full_list if doc['tasks_points']['task1'] != 1] expected_result = sorted(expected_result, key=lambda doc: (doc['task'])) self._verify_results(actual_result, expected_result) def test_every_comparision_not_equal(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name FROM %s d WHERE " % query_bucket + \ "(EVERY vm IN d.VMs SATISFIES vm.memory != 5 END) ORDER BY name" if self.analytics: self.query = "SELECT name FROM %s d WHERE " % query_bucket + \ "(EVERY vm IN d.VMs SATISFIES vm.memory != 5 ) ORDER BY name" actual_result = self.run_cbq_query() expected_result = [{"name": doc['name']} for doc in self.full_list if len([vm for vm in doc["VMs"] if vm['memory'] != 5]) == len(doc["VMs"])] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) def test_every_comparision_not_equal_less_more(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name FROM %s d WHERE " % query_bucket + \ "(EVERY vm IN d.VMs SATISFIES vm.memory <> 5 END) ORDER BY name" if self.analytics: self.query = "SELECT name FROM %s d WHERE " % query_bucket + \ "(EVERY vm IN d.VMs SATISFIES vm.memory <> 5 ) ORDER BY name" actual_result = self.run_cbq_query() expected_result = [{"name": doc['name']} for doc in self.full_list if len([vm for vm in doc["VMs"] if vm['memory'] != 5]) == len(doc["VMs"])] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) def test_any_between(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name, email FROM %s d WHERE " % query_bucket + \ "(ANY skill IN d.skills SATISFIES skill = 'skill2010' END)" + \ " AND (ANY vm IN d.VMs SATISFIES vm.RAM between 1 and 5 END)" + \ "AND NOT (job_title = 'Sales') ORDER BY name" if self.analytics: self.query = "SELECT name, email FROM %s d WHERE " % query_bucket + \ "(ANY skill IN d.skills SATISFIES skill = 'skill2010' )" + \ " AND (ANY vm IN d.VMs SATISFIES vm.RAM between 1 and 5 )" + \ "AND NOT (job_title = 'Sales') ORDER BY name" actual_result = self.run_cbq_query() expected_result = [{"name": doc['name'], "email": doc["email"]} for doc in self.full_list if len([skill for skill in doc["skills"] if skill == 'skill2010']) > 0 and len([vm for vm in doc["VMs"] if vm["RAM"] in [1, 2, 3, 4, 5]]) > 0 and doc["job_title"] != 'Sales'] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) def test_any_less_equal(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name, email FROM %s d WHERE " % query_bucket + \ "(ANY skill IN d.skills SATISFIES skill = 'skill2010' END)" + \ " AND (ANY vm IN d.VMs SATISFIES vm.RAM <= 5 END)" + \ "AND NOT (job_title = 'Sales') ORDER BY name" if self.analytics: self.query = "SELECT name, email FROM %s d WHERE " % query_bucket + \ "(ANY skill IN d.skills SATISFIES skill = 'skill2010' )" + \ " AND (ANY vm IN d.VMs SATISFIES vm.RAM <= 5 )" + \ "AND NOT (job_title = 'Sales') ORDER BY name" actual_result = self.run_cbq_query() expected_result = [{"name": doc['name'], "email": doc["email"]} for doc in self.full_list if len([skill for skill in doc["skills"] if skill == 'skill2010']) > 0 and len([vm for vm in doc["VMs"] if vm["RAM"] <= 5]) > 0 and doc["job_title"] != 'Sales'] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) def test_any_more_equal(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name, email FROM %s d WHERE " % query_bucket + \ "(ANY skill IN d.skills SATISFIES skill = 'skill2010' END)" + \ " AND (ANY vm IN d.VMs SATISFIES vm.RAM >= 5 END)" + \ "AND NOT (job_title = 'Sales') ORDER BY name" if self.analytics: self.query = "SELECT name, email FROM %s d WHERE " % query_bucket + \ "(ANY skill IN d.skills SATISFIES skill = 'skill2010' )" + \ " AND (ANY vm IN d.VMs SATISFIES vm.RAM >= 5 )" + \ "AND NOT (job_title = 'Sales') ORDER BY name" actual_result = self.run_cbq_query() expected_result = [{"name": doc['name'], "email": doc["email"]} for doc in self.full_list if len([skill for skill in doc["skills"] if skill == 'skill2010']) > 0 and len([vm for vm in doc["VMs"] if vm["RAM"] >= 5]) > 0 and doc["job_title"] != 'Sales'] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) def test_prepared_between(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: query_bucket = self.get_collection_name(query_bucket) self.query = "SELECT name, email FROM %s d WHERE " % query_bucket + \ "(ANY skill IN d.skills SATISFIES skill = 'skill2010' END)" + \ " AND (ANY vm IN d.VMs SATISFIES vm.RAM between 1 and 5 END)" + \ "AND NOT (job_title = 'Sales') ORDER BY name" self.prepared_common_body() def test_named_prepared_between(self): self.fail_if_no_buckets() if self.monitoring: self.query = "select * from system:prepareds" result = self.run_cbq_query() self.assertTrue(result['metrics']['resultCount'] == 0) for query_bucket in self.query_buckets: self.query = "SELECT name, email FROM %s d WHERE " % query_bucket + \ "(ANY skill IN d.skills SATISFIES skill = 'skill2010' END)" + \ " AND (ANY vm IN d.VMs SATISFIES vm.RAM between 1 and 5 END)" + \ "AND NOT (job_title = 'Sales') ORDER BY name" self.prepared_common_body() if self.monitoring: self.query = "select * from system:prepareds" result = self.run_cbq_query() self.assertTrue(result['metrics']['resultCount'] == 1) name = result['results'][0]['prepareds']['name'] self.query = 'delete from system:prepareds where name = "%s" ' % name self.run_cbq_query() self.query = 'select * from system:prepareds where name = "%s" ' % name result = self.run_cbq_query() self.assertTrue(result['metrics']['resultCount'] == 0) def test_prepared_comparision_not_equal_less_more(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name FROM %s d WHERE " % query_bucket + \ "(EVERY vm IN d.VMs SATISFIES vm.memory <> 5 END) ORDER BY name" self.prepared_common_body() def test_prepared_comparision_not_equal(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name FROM %s d WHERE " % query_bucket + \ "(EVERY vm IN d.VMs SATISFIES vm.memory != 5 END) ORDER BY name" self.prepared_common_body() def test_prepared_more_equal(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name FROM %s d WHERE " % query_bucket + \ "(EVERY vm IN d.VMs SATISFIES vm.memory >= 5 END) ORDER BY name" self.prepared_common_body() def test_prepared_less_equal(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name FROM %s d WHERE " % query_bucket + \ "(EVERY vm IN d.VMs SATISFIES vm.memory <= 5 END) ORDER BY name" self.prepared_common_body() def test_let_not_equal(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select compare from %s let compare = (test_rate != 2)" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"compare": doc["test_rate"] != 2} for doc in self.full_list] self._verify_results(actual_result, expected_result) def test_let_between(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select compare from %s let compare = (test_rate between 1 and 3)" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"compare": 1 <= doc["test_rate"] <= 3} for doc in self.full_list] self._verify_results(actual_result, expected_result) def test_let_not_equal_less_more(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select compare from %s let compare = (test_rate <> 2)" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"compare": doc["test_rate"] != 2} for doc in self.full_list] self._verify_results(actual_result, expected_result) def test_let_more_equal(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select compare from %s let compare = (test_rate >= 2)" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"compare": doc["test_rate"] >= 2} for doc in self.full_list] self._verify_results(actual_result, expected_result) def test_let_less_equal(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select compare from %s let compare = (test_rate <= 2)" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"compare": doc["test_rate"] <= 2} for doc in self.full_list] self._verify_results(actual_result, expected_result) def test_comparition_equal_not_equal(self): self.fail_if_no_buckets() template = "SELECT join_day, join_mo FROM %s WHERE " + \ "join_day == 1 and join_mo != 2 ORDER BY join_day, join_mo" for query_bucket in self.query_buckets: self.query = template % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['join_day'], doc['join_mo'])) expected_result = [{"join_mo": doc['join_mo'], "join_day": doc['join_day']} for doc in self.full_list if doc['join_day'] == 1 and doc["join_mo"] != 2] expected_result = sorted(expected_result, key=lambda doc: (doc['join_day'], doc['join_mo'])) self._verify_results(actual_result, expected_result) return template def test_comparition_more_and_less_equal(self): self.fail_if_no_buckets() template = "SELECT join_yr, test_rate FROM %s WHERE join_yr >= 2010 AND test_rate <= 4" for query_bucket in self.query_buckets: self.query = template % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: ( doc['test_rate'], doc['join_yr'])) expected_result = [{"test_rate": doc['test_rate'], "join_yr": doc['join_yr']} for doc in self.full_list if doc['test_rate'] <= 4 and doc['join_yr'] >= 2010] expected_result = sorted(expected_result, key=lambda doc: (doc['test_rate'], doc['join_yr'])) self._verify_results(actual_result, expected_result) return template def test_comparition_null_missing(self): self.fail_if_no_buckets() template = "SELECT skills, VMs FROM %s WHERE " + \ "skills is not null AND VMs is not missing" for query_bucket in self.query_buckets: self.query = template % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: ( doc['VMs'], doc['skills'])) expected_result = [{"VMs": doc['VMs'], "skills": doc['skills']} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['VMs'], doc['skills'])) self._verify_results(actual_result, expected_result) return template def test_comparition_aggr_fns(self): self.fail_if_no_buckets() template = "SELECT count(join_yr) years, sum(test_rate) rate FROM %s" for query_bucket in self.query_buckets: self.query = template % query_bucket actual_result = self.run_cbq_query() actual_result = actual_result['results'] expected_result = [{"years": len([doc['join_yr'] for doc in self.full_list]), "rate": sum([doc['test_rate'] for doc in self.full_list])}] self.assertTrue(round(actual_result[0]['rate']) == round(expected_result[0]['rate'])) self.assertTrue((actual_result[0]['years']) == (expected_result[0]['years'])) return template # This test has no uses anywhere def test_comparition_meta(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT meta(d).id, meta(d).type FROM %s d" % query_bucket actual_result = self.run_cbq_query() actual_result = actual_result['results'] def test_comparition_more_less_equal(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT tasks_points.task1 as task FROM %s WHERE " % query_bucket + \ "tasks_points.task1 >= 1 AND tasks_points.task1 <= 4" actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: ( doc['task'])) expected_result = [{"task": doc['tasks_points']['task1']} for doc in self.full_list if 1 <= doc['tasks_points']['task1'] <= 4] expected_result = sorted(expected_result, key=lambda doc: (doc['task'])) self._verify_results(actual_result, expected_result) def test_comparition_expr(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT tasks_points.task1 as task FROM %s WHERE " % query_bucket + \ "tasks_points.task1 > tasks_points.task1" actual_result = self.run_cbq_query() self._verify_results(actual_result['results'], []) def test_arithm(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, SUM(test_rate) % COUNT(distinct join_yr)" + \ " as avg_per_year from {0} group by job_title".format(query_bucket) if self.analytics: self.query = "SELECT d.job_title, SUM(d.test_rate) % COUNT(d.join_yr)" + \ " as avg_per_year from {0} d group by d.job_title".format(query_bucket) actual_result = self.run_cbq_query() actual_result = [{"job_title": doc["job_title"], "avg_per_year": round(doc["avg_per_year"], 2)} for doc in actual_result['results']] actual_result = sorted(actual_result, key=lambda doc: (doc['job_title'])) tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "avg_per_year": math.fsum([doc['test_rate'] for doc in self.full_list if doc['job_title'] == group]) % len({doc['join_yr'] for doc in self.full_list if doc['job_title'] == group})} for group in tmp_groups] expected_result = [{"job_title": doc["job_title"], "avg_per_year": round(doc["avg_per_year"], 2)} for doc in expected_result] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result, expected_result) self.query = "SELECT job_title, (SUM(tasks_points.task1) +" + \ " SUM(tasks_points.task2)) % COUNT(distinct join_yr) as avg_per_year" + \ " from {0} group by job_title".format(query_bucket) if self.analytics: self.query = "SELECT d.job_title, (SUM(d.tasks_points.task1) +" + \ " SUM(d.tasks_points.task2)) % COUNT(d.join_yr) as avg_per_year" + \ " from {0} d group by d.job_title".format(query_bucket) actual_result = self.run_cbq_query() actual_result = [{"job_title": doc["job_title"], "avg_per_year": round(doc["avg_per_year"], 2)} for doc in actual_result['results']] actual_result = sorted(actual_result, key=lambda doc: ( doc['job_title'])) tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "avg_per_year": (math.fsum([doc['tasks_points']['task1'] for doc in self.full_list if doc['job_title'] == group]) + math.fsum([doc['tasks_points']['task2'] for doc in self.full_list if doc['job_title'] == group])) % len({doc['join_yr'] for doc in self.full_list if doc['job_title'] == group})} for group in tmp_groups] expected_result = [{"job_title": doc["job_title"], "avg_per_year": int(round(doc["avg_per_year"], 2))} for doc in expected_result] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result, expected_result) # https://issues.couchbase.com/browse/MB-29401 def test_sum_large_negative_numbers(self): self.fail_if_no_buckets() self.run_cbq_query( "insert into " + self.query_buckets[0] + " (KEY, VALUE) VALUES ('doc1',{ 'f1' : -822337203685477580 })") self.run_cbq_query( "insert into " + self.query_buckets[0] + " (KEY, VALUE) VALUES ('doc2',{ 'f1' : -822337203685477580 })") self.query = "select SUM(f1) from " + self.query_buckets[0] + " " result = self.run_cbq_query() found_result = result['results'][0]['$1'] expected_result = -1644674407370955160 self.assertEqual(found_result, expected_result) self.run_cbq_query( "insert into " + self.query_buckets[0] + " (KEY, VALUE) VALUES ('doc3',{ 'f2' : -822337203685477580 })") self.run_cbq_query("insert into " + self.query_buckets[0] + " (KEY, VALUE) VALUES ('doc4',{ 'f2' : 10 })") self.query = "select SUM(f2) from " + self.query_buckets[0] + " " result = self.run_cbq_query() found_result = result['results'][0]['$1'] expected_result = -822337203685477570 self.assertEqual(found_result, expected_result) ############################################################################################## # # EXPLAIN ############################################################################################## def test_explain(self): self.fail_if_no_buckets() for _ in self.query_buckets: res = self.run_cbq_query() self.log.info(res) plan = self.ExplainPlanHelper(res) self.assertTrue(plan["~children"][0]["index"] == "#primary", "Type should be #primary, but is: %s" % plan["~children"][0]["index"]) ############################################################################################## # # EXPLAIN WITH A PARTICULAR INDEX ############################################################################################## # Test has no usages anywhere def test_explain_particular_index(self, index): self.fail_if_no_buckets() for _ in self.query_buckets: res = self.run_cbq_query() self.log.info(res) plan = self.ExplainPlanHelper(res) self.assertTrue(plan['~children'][2]['~child']['~children'][0]['scan']['index'] == index, "wrong index used") ############################################################################################### # # EXPLAIN WITH UNION SCAN: Covering Indexes ############################################################################################## # Test has no usages anywhere def test_explain_union(self, index): self.fail_if_no_buckets() for _ in self.query_buckets: res = self.run_cbq_query() plan = self.ExplainPlanHelper(res) if "IN" in self.query: self.assertTrue(plan["~children"][0]["~children"][0]["#operator"] == "DistinctScan", "DistinctScan Operator is not used by this query") else: self.assertTrue(plan["~children"][0]["~children"][0]["#operator"] == "UnionScan", "UnionScan Operator is not used by this query") if plan["~children"][0]["~children"][0]["scan"]["#operator"] == "IndexScan": self.log.info("IndexScan Operator is also used by this query in scans") else: self.log.error("IndexScan Operator is not used by this query, Covering Indexes not used properly") self.fail("IndexScan Operator is not used by this query, Covering Indexes not used properly") if plan["~children"][0]["~children"][0]["scan"]["index"] == index: self.log.info("Query is using specified index") else: self.log.info("Query is not using specified index") ############################################################################################## # # DATETIME ############################################################################################## def test_clock_millis(self): self.query = "select clock_millis() as now" res = self.run_cbq_query() self.assertFalse("error" in str(res).lower()) def test_clock_str(self): self.query = "select clock_str() as now" now = datetime.datetime.now() res = self.run_cbq_query() expected = "%s-%02d-%02dT" % (now.year, now.month, now.day) self.assertTrue(res["results"][0]["now"].startswith(expected), "Result expected: %s. Actual %s" % (expected, res["results"])) def test_date_add_millis(self): self.query = "select date_add_millis(clock_millis(), 100, 'day') as now" now = time.time() res = self.run_cbq_query() self.assertTrue((res["results"][0]["now"] > now * 1000 + 100 * 24 * 60 * 60), "Result expected to be in: [%s ... %s]. Actual %s" % ( now * 1000 + 100 * 24 * 60 * 60, (now + 10) * 1000 + 100 * 24 * 60 * 60, res["results"])) def test_date_add_str(self): self.query = "select date_add_str(clock_utc(), 10, 'day') as now" now = datetime.datetime.utcnow() + datetime.timedelta(days=10) res = self.run_cbq_query() expected = "%s-%02d-%02dT%02d:" % (now.year, now.month, now.day, now.hour) expected_delta = "%s-%02d-%02dT%02d:" % (now.year, now.month, now.day, now.hour + 1) self.assertTrue( res["results"][0]["now"].startswith(expected) or res["results"][0]["now"].startswith(expected_delta), "Result expected: %s. Actual %s" % (expected, res["results"])) def test_date_diff_millis(self): self.query = "select date_diff_millis(clock_millis(), date_add_millis(clock_millis(), 100, 'day'), 'day') as " \ "now " res = self.run_cbq_query() self.assertTrue(res["results"][0]["now"] == -100, "Result expected: %s. Actual %s" % (-100, res["results"])) def test_date_diff_str(self): self.query = 'select date_diff_str("2014-08-24T01:33:59", "2014-08-24T07:33:59", "minute") as now' res = self.run_cbq_query() self.assertTrue(res["results"][0]["now"] == -360, "Result expected: %s. Actual %s" % (-360, res["results"])) self.query = 'select date_diff_str("2014-08-24T01:33:59", "2014-08-24T07:33:59", "hour") as now' res = self.run_cbq_query() self.assertTrue(res["results"][0]["now"] == -6, "Result expected: %s. Actual %s" % (-6, res["results"])) def test_now(self): self.query = "select now_str() as now" now = datetime.datetime.now() today = date.today() res = self.run_cbq_query() expected = "%s-%02d-%02dT" % (today.year, today.month, today.day,) self.assertFalse("error" in str(res).lower()) def test_hours(self): self.query = 'select date_part_str(now_utc(), "hour") as hour, ' + \ 'date_part_str(now_utc(),"minute") as minute, date_part_str(' + \ 'now_utc(),"second") as sec, date_part_str(now_utc(),"millisecond") as msec' now = datetime.datetime.utcnow() res = self.run_cbq_query() self.assertTrue(res["results"][0]["hour"] == now.hour or res["results"][0]["hour"] == (now.hour + 1), "Result for hours expected: %s. Actual %s" % (now.hour, res["results"])) self.assertTrue("minute" in res["results"][0], "No minute field") self.assertTrue("sec" in res["results"][0], "No second field") self.assertTrue("msec" in res["results"][0], "No msec field") def test_where(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'select name, join_yr, join_mo, join_day from %s' % query_bucket + \ ' where date_part_str(now_str(),"month") < join_mo AND date_part_str(now_str(),"year")' + \ ' > join_yr AND date_part_str(now_str(),"day") < join_day' actual_result = self.run_cbq_query() actual_result = sorted(actual_result["results"], key=lambda doc: (doc['name'], doc['join_yr'], doc['join_mo'], doc['join_day'])) today = date.today() expected_result = [{"name": doc['name'], "join_yr": doc['join_yr'], "join_mo": doc['join_mo'], "join_day": doc['join_day']} for doc in self.full_list if doc['join_yr'] < today.year and doc['join_mo'] > today.month and doc['join_day'] > today.day] expected_result = sorted(expected_result, key=lambda doc: (doc['name'], doc['join_yr'], doc['join_mo'], doc['join_day'])) self._verify_results(actual_result, expected_result) def test_prepared_date_where(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'select name, join_yr, join_mo, join_day from %s' % query_bucket + \ ' where date_part_str(now_str(),"month") < join_mo AND date_part_str(now_str(),"year")' + \ ' > join_yr AND date_part_str(now_str(),"day") < join_day' self.prepared_common_body() def test_now_millis(self): self.query = "select now_millis() as now" now = time.time() res = self.run_cbq_query() self.assertFalse("error" in str(res).lower()) def test_str_to_millis(self): now_millis = time.time() now_time = datetime.datetime.fromtimestamp(now_millis) now_millis = now_millis * 1000 try: now_time_zone = round( (round((datetime.datetime.now() - datetime.datetime.utcnow()).total_seconds()) // 1800) // 2) except AttributeError as ex: raise Exception("Test requires python 2.7 : SKIPPING TEST") now_time_str = "%s-%02d-%02d" % (now_time.year, now_time.month, now_time.day) self.query = "select str_to_millis('%s') as now" % now_time_str res = self.run_cbq_query() self.assertTrue(res["results"][0]["now"] < now_millis and (res["results"][0]["now"] > (now_millis - 5184000000)), "Result expected to be in: [%s ... %s]. Actual %s" % ( now_millis - 5184000000, now_millis, res["results"])) def test_millis_to_str(self): now_millis = time.time() now_time = datetime.datetime.utcfromtimestamp(now_millis) expected = "%s-%02d-%02dT%02d:%02d" % (now_time.year, now_time.month, now_time.day, now_time.hour, now_time.minute) self.query = "select millis_to_utc(%s) as now" % (now_millis * 1000) res = self.run_cbq_query() self.assertTrue(res["results"][0]["now"].startswith(expected), "Result expected: %s. Actual %s" % (expected, res["results"])) def test_date_part_millis(self): now_millis = time.time() now_time = datetime.datetime.utcfromtimestamp(now_millis) now_millis = now_millis * 1000 self.query = 'select date_part_millis(%s, "hour", "UTC") as hour, ' % now_millis + \ 'date_part_millis(%s,"minute", "UTC") as minute, date_part_millis(' % now_millis + \ '%s,"second") as sec, date_part_millis(%s,"millisecond", "UTC") as msec' % (now_millis, now_millis) res = self.run_cbq_query() self.assertTrue(res["results"][0]["hour"] == now_time.hour, "Result expected: %s. Actual %s" % (now_time.hour, res["results"])) self.assertTrue(res["results"][0]["minute"] == now_time.minute, "Result expected: %s. Actual %s" % (now_time.minute, res["results"])) self.assertTrue(res["results"][0]["sec"] == now_time.second, "Result expected: %s. Actual %s" % (now_time.second, res["results"])) self.assertTrue("msec" in res["results"][0], "There are no msec in results") def test_where_millis(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select join_yr, join_mo, join_day, name from %s" % query_bucket + \ " where join_mo < 10 and join_day < 10 and str_to_millis(tostr(join_yr) || '-0'" + \ " || tostr(join_mo) || '-0' || tostr(join_day)) < now_millis()" actual_result = self.run_cbq_query() actual_result = sorted(actual_result["results"], key=lambda doc: (doc['name'], doc['join_yr'], doc['join_mo'], doc['join_day'])) expected_result = [{"name": doc['name'], "join_yr": doc['join_yr'], "join_mo": doc['join_mo'], "join_day": doc['join_day']} for doc in self.full_list if doc['join_mo'] < 10 and doc['join_day'] < 10] expected_result = sorted(expected_result, key=lambda doc: (doc['name'], doc['join_yr'], doc['join_mo'], doc['join_day'])) self._verify_results(actual_result, expected_result) def test_order_by_dates(self): self.fail_if_no_buckets() orders = ["asc", "desc"] for order in orders: for query_bucket in self.query_buckets: self.query = "select millis_to_str(str_to_millis('2010-01-01')) as date" actual_result = self.run_cbq_query() self.assertTrue(actual_result["results"][0]["date"][:10] == '2010-01-01', 'Actual result %s' % actual_result) self.query = "select join_yr, join_mo, join_day," \ " millis_to_str(str_to_millis(tostr(join_yr) || '-0' ||" + \ " tostr(join_mo) || '-0' || tostr(join_day))) as date from %s" % query_bucket + \ " where join_mo < 10 and join_day < 10 ORDER BY date %s" % order actual_result = self.run_cbq_query() actual_result = ([{"date": doc["date"][:10], "join_yr": doc['join_yr'], "join_mo": doc['join_mo'], "join_day": doc['join_day']} for doc in actual_result["results"]]) expected_result = [{"date": '%s-0%s-0%s' % (doc['join_yr'], doc['join_mo'], doc['join_day']), "join_yr": doc['join_yr'], "join_mo": doc['join_mo'], "join_day": doc['join_day']} for doc in self.full_list if doc['join_mo'] < 10 and doc['join_day'] < 10] expected_result = sorted(expected_result, key=lambda doc: (doc['date']), reverse=(order == 'desc')) self._verify_results(actual_result, expected_result) ############################################################################################## # # TYPE FNS ############################################################################################## def test_type(self): self.fail_if_no_buckets() types_list = [("name", "string"), ("tasks_points", "object"), ("some_wrong_key", "missing"), ("skills", "array"), ("VMs[0].RAM", "number"), ("true", "boolean"), ("test_rate", "number"), ("test.test[0]", "missing")] for query_bucket in self.query_buckets: for name_item, type_item in types_list: self.query = 'SELECT TYPENAME(%s) as type_output FROM %s' % ( name_item, query_bucket) actual_result = self.run_cbq_query() for doc in actual_result['results']: self.assertTrue(doc["type_output"] == type_item, "Expected type for %s: %s. Actual: %s" % ( name_item, type_item, doc["type_output"])) self.log.info("Type for %s(%s) is checked." % (name_item, type_item)) def test_check_types(self): self.fail_if_no_buckets() types_list = [("name", "ISSTR", True), ("skills[0]", "ISSTR", True), ("test_rate", "ISSTR", False), ("VMs", "ISSTR", False), ("false", "ISBOOL", True), ("join_day", "ISBOOL", False), ("VMs", "ISARRAY", True), ("VMs[0]", "ISARRAY", False), ("skills[0]", "ISARRAY", False), ("skills", "ISARRAY", True)] for query_bucket in self.query_buckets: for name_item, fn, expected_result in types_list: self.query = 'SELECT %s(%s) as type_output FROM %s' % ( fn, name_item, query_bucket) actual_result = self.run_cbq_query() for doc in actual_result['results']: self.assertTrue(doc["type_output"] == expected_result, "Expected output for fn %s( %s) : %s. Actual: %s" % ( fn, name_item, expected_result, doc["type_output"])) self.log.info("Fn %s(%s) is checked. (%s)" % (fn, name_item, expected_result)) def test_types_in_satisfy(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name FROM %s d WHERE " % query_bucket + \ "(EVERY vm IN d.VMs SATISFIES ISOBJ(vm) END) AND" + \ " ISSTR(email) ORDER BY name" if self.analytics: self.query = "SELECT name FROM %s d WHERE " % query_bucket + \ "(EVERY vm IN d.VMs SATISFIES ISOBJ(vm) ) AND" + \ " ISSTR(email) ORDER BY name" actual_result = self.run_cbq_query() expected_result = [{"name": doc['name']} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) def test_to_num(self): self.query = 'SELECT tonum("12.12") - tonum("0.12") as num' actual_result = self.run_cbq_query() self.assertTrue(actual_result['results'][0]['num'] == 12, "Expected: 12. Actual: %s" % (actual_result['results'])) self.log.info("TONUM is checked") def test_to_str(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT TOSTR(join_mo) month FROM %s" % query_bucket actual_result = self.run_cbq_query() actual_result = actual_result['results'] self.query = "SELECT REVERSE(TOSTR(join_mo)) rev_month FROM %s" % query_bucket actual_result1 = self.run_cbq_query() actual_result2 = actual_result1['results'] expected_result = [{"month": str(doc['join_mo'])} for doc in self.full_list] expected_result2 = [{"rev_month": str(doc['join_mo'])[::-1]} for doc in self.full_list] self._verify_results(actual_result, expected_result) self._verify_results(actual_result2, expected_result2) def test_to_bool(self): self.query = 'SELECT tobool("true") as boo' actual_result = self.run_cbq_query() self.assertTrue(actual_result['results'][0]['boo'], "Expected: true. Actual: %s" % (actual_result['results'])) self.log.info("TOBOOL is checked") # Test has no usages anywhere def test_to_array(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, toarray(name) as names" + \ " FROM %s" % query_bucket actual_list = self.run_cbq_query() actual_result = sorted(actual_list['results'], key=lambda doc: (doc['job_title'], doc['names'])) expected_result = [{"job_title": doc["job_title"], "names": [doc["name"]]} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'], doc['names'])) self._verify_results(actual_result, expected_result) ############################################################################################## # # CONCATENATION ############################################################################################## def test_concatenation(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name || \" \" || job_title as employee" + \ " FROM %s" % query_bucket actual_list = self.run_cbq_query() actual_result = sorted(actual_list['results'], key=lambda doc: (doc['employee'])) expected_result = [{"employee": doc["name"] + " " + doc["job_title"]} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['employee'])) self._verify_results(actual_result, expected_result) def test_concatenation_where(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'SELECT name, skills' + \ ' FROM %s WHERE skills[0]=("skill" || "2010")' % query_bucket actual_list = self.run_cbq_query() self.query = 'SELECT name, skills' + \ ' FROM %s WHERE reverse(skills[0])=("0102" || "lliks")' % query_bucket actual_list1 = self.run_cbq_query() actual_result = actual_list['results'] actual_result2 = actual_list1['results'] expected_result = [{"name": doc["name"], "skills": doc["skills"]} for doc in self.full_list if doc["skills"][0] == 'skill2010'] self._verify_results(actual_result, expected_result) self._verify_results(actual_result, actual_result2) ############################################################################################## # # SPLIT ############################################################################################## def test_select_split_fn(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT SPLIT(email, '@')[0] as login" + \ " FROM %s" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"login": doc["email"].split('@')[0]} for doc in self.full_list] self._verify_results(actual_result, expected_result) def test_split_where(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'SELECT name FROM %s' % query_bucket + \ ' WHERE SPLIT(email, \'-\')[0] = SPLIT(name, \'-\')[1]' actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"]} for doc in self.full_list if doc["email"].split('-')[0] == doc["name"].split('-')[1]] self._verify_results(actual_result, expected_result) ############################################################################################## # # UNION ############################################################################################## def test_union(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: query_bucket = self.get_collection_name(query_bucket) self.query = "select name from %s union select email from %s" % (query_bucket, query_bucket) actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"]} for doc in self.full_list] expected_result.extend([{"email": doc["email"]} for doc in self.full_list]) expected_result = [dict(y) for y in set(tuple(x.items()) for x in expected_result)] self._verify_results(actual_result, expected_result) def test_prepared_union(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: query_bucket = self.get_collection_name(query_bucket) self.query = "select name from %s union select email from %s" % (query_bucket, query_bucket) self.prepared_common_body() def test_union_multiply_buckets(self): self.assertTrue(len(self.buckets) > 1, 'This test needs more than one bucket') self.query = "select name from %s union select email from %s" % (self.buckets[0].name, self.buckets[1].name) actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"]} for doc in self.full_list] expected_result.extend([{"email": doc["email"]} for doc in self.full_list]) expected_result = [dict(y) for y in set(tuple(x.items()) for x in expected_result)] self._verify_results(actual_result, expected_result) def test_union_all(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: query_bucket = self.get_collection_name(query_bucket) self.query = "select name from %s union all select email from %s" % (query_bucket, query_bucket) actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"]} for doc in self.full_list] expected_result.extend([{"email": doc["email"]} for doc in self.full_list]) self._verify_results(actual_result, expected_result) def test_union_all_multiply_buckets(self): self.assertTrue(len(self.buckets) > 1, 'This test needs more than one bucket') self.query = "select name from %s union all select email from %s" % (self.query_buckets[0], self.query_buckets[1]) actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"]} for doc in self.full_list] expected_result.extend([{"email": doc["email"]} for doc in self.full_list]) self._verify_results(actual_result, expected_result) def test_union_where(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name from %s union select email from %s where join_mo > 2" % (query_bucket, query_bucket) actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"]} for doc in self.full_list] expected_result.extend([{"email": doc["email"]} for doc in self.full_list if doc["join_mo"] > 2]) expected_result = [dict(y) for y in set(tuple(x.items()) for x in expected_result)] self._verify_results(actual_result, expected_result) def test_union_where_covering(self): created_indexes = [] ind_list = ["one", "two"] index_name = "one" self.fail_if_no_buckets() for query_bucket, bucket in zip(self.query_buckets, self.buckets): for ind in ind_list: index_name = "coveringindex{0}".format(ind) if ind == "one": self.query = "CREATE INDEX {0} ON {1}(name, email, join_mo) USING {2}".format(index_name, query_bucket, self.index_type) elif ind == "two": self.query = "CREATE INDEX {0} ON {1}(email, join_mo) USING {2}".format(index_name, query_bucket, self.index_type) self.run_cbq_query() self._wait_for_index_online(bucket, index_name) created_indexes.append(index_name) for query_bucket in self.query_buckets: self.query = "explain select name from {0} where name is not null union select email from {0} where email " \ "is not null and join_mo >2 ".format(query_bucket) if self.covering_index: self.check_explain_covering_index(index_name[0]) self.query = "select name from {0} where name is not null union select email from {0} where email is not " \ "null and join_mo >2".format(query_bucket) actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"]} for doc in self.full_list] expected_result.extend([{"email": doc["email"]} for doc in self.full_list if doc["join_mo"] > 2]) expected_result = [dict(y) for y in set(tuple(x.items()) for x in expected_result)] self._verify_results(actual_result, expected_result) for index_name in created_indexes: try: self.query = "DROP INDEX {0} ON {1} USING {2}".format(index_name, query_bucket, self.index_type) self.run_cbq_query() except Exception as e: self.log.error("Drop index failed {0}".format(str(e))) self.query = "CREATE PRIMARY INDEX ON {0}".format(query_bucket) self.run_cbq_query() self.sleep(15, 'wait for index') self.query = "select name from {0} where name is not null union select email from {0} where email is not " \ "null and join_mo >2".format(query_bucket) result = self.run_cbq_query() diffs = DeepDiff(actual_result, result['results'], ignore_order=True) if diffs: self.assertTrue(False, diffs) #self.assertEqual(actual_result, sorted(result['results'])) self.query = "DROP PRIMARY INDEX ON {0}".format(query_bucket) self.run_cbq_query() def test_union_aggr_fns(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select count(name) as names from %s union select count(email) as " \ "emails from %s" % (query_bucket, query_bucket) actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"names": len(self.full_list)}] expected_result.extend([{"emails": len(self.full_list)}]) expected_result = [dict(y) for y in set(tuple(x.items()) for x in expected_result)] self._verify_results(actual_result, expected_result) def test_union_aggr_fns_covering(self): created_indexes = [] ind_list = ["one", "two"] index_name = "one" self.fail_if_no_buckets() for query_bucket, bucket in zip(self.query_buckets, self.buckets): for ind in ind_list: index_name = "coveringindex%s" % ind if ind == "one": self.query = "CREATE INDEX %s ON %s(name, email, join_day) USING %s" % (index_name, query_bucket, self.index_type) elif ind == "two": self.query = "CREATE INDEX %s ON %s(email) USING %s" % (index_name, query_bucket, self.index_type) self.run_cbq_query() self._wait_for_index_online(bucket, index_name) created_indexes.append(index_name) for query_bucket in self.query_buckets: self.query = "explain select count(name) as names from %s where join_day is not null union select count(" \ "email) as emails from %s where email is not null" % (query_bucket, query_bucket) if self.covering_index: self.check_explain_covering_index(index_name) self.query = "select count(name) as names from %s where join_day is not null union select count(email) " \ " as emails from %s where email is not null" % (query_bucket, query_bucket) actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"names": len(self.full_list)}] expected_result.extend([{"emails": len(self.full_list)}]) expected_result = [dict(y) for y in set(tuple(x.items()) for x in expected_result)] self._verify_results(actual_result, expected_result) for index_name in created_indexes: self.query = "DROP INDEX %s ON %s USING %s" % (index_name, query_bucket, self.index_type) self.run_cbq_query() self.query = "CREATE PRIMARY INDEX ON %s" % query_bucket self.run_cbq_query() self.sleep(15, 'wait for index') self.query = "select count(name) as names from %s where join_day is not null union select count(email) " \ " as emails from %s where email is not null" % ( query_bucket, query_bucket) result = self.run_cbq_query() self.assertEqual(actual_result, sorted(result['results'])) self.query = "DROP PRIMARY INDEX ON %s" % query_bucket self.run_cbq_query() # ############# META NEW ################### def test_meta_basic(self): created_indexes = [] ind_list = ["one"] index_name = "one" self.fail_if_no_buckets() for query_bucket, bucket in zip(self.query_buckets, self.buckets): for ind in ind_list: index_name = "metaindex%s" % ind if ind == "one": self.query = "CREATE INDEX %s ON %s(meta().id,meta().cas) USING %s" % ( index_name, query_bucket, self.index_type) self.run_cbq_query() self._wait_for_index_online(bucket, index_name) created_indexes.append(index_name) for query_bucket, bucket in zip(self.query_buckets, self.buckets): self.query = "explain select meta().id, meta().cas from {0} where meta().id is not null order by meta(" \ ").id limit 10".format(query_bucket) if self.covering_index: self.check_explain_covering_index(index_name[0]) self.query = "select meta().id, meta().cas from {0} where meta().id is not null order by " \ "meta().id limit 10".format(query_bucket) actual_list = self.run_cbq_query() actual_result = actual_list['results'] for index_name in created_indexes: self.query = "DROP INDEX %s ON %s USING %s" % (index_name, query_bucket, self.index_type) self.run_cbq_query() self.covering_index = False self.query = "CREATE PRIMARY INDEX ON %s" % query_bucket self.run_cbq_query() self._wait_for_index_online(bucket, '#primary') self.query = "select meta().id, meta().cas from {0} use index(`#primary`) where meta().id is not null " \ "order by meta().id limit 10".format(query_bucket) expected_list = self.run_cbq_query() diffs = DeepDiff(actual_result, expected_list['results'], ignore_order=True) if diffs: self.assertTrue(False, diffs) self.query = "DROP PRIMARY INDEX ON %s" % query_bucket self.run_cbq_query() def test_meta_where(self): created_indexes = [] ind_list = ["one"] index_name = "one" self.fail_if_no_buckets() for query_bucket, bucket in zip(self.query_buckets, self.buckets): for ind in ind_list: index_name = "meta_where%s" % ind if ind == "one": self.query = "CREATE INDEX {0} ON {1}(meta().id,meta().cas) where meta().id like " \ "'query-testemployee6%' USING {2}".format(index_name, query_bucket, self.index_type) self.run_cbq_query() self._wait_for_index_online(bucket, index_name) created_indexes.append(index_name) for query_bucket, bucket in zip(self.query_buckets, self.buckets): self.query = "explain select meta().id, meta().cas from {0} where meta().id like 'query-testemployee6%' " \ "order by meta().id limit 10".format( query_bucket) if self.covering_index: self.check_explain_covering_index(index_name[0]) self.query = "select meta().id, meta().cas from {0} where meta().id like 'query-testemployee6%' order by " \ "meta().id limit 10".format(query_bucket) actual_list = self.run_cbq_query() actual_result = actual_list['results'] for index_name in created_indexes: self.query = "DROP INDEX %s ON %s USING %s" % (index_name, query_bucket, self.index_type) self.run_cbq_query() self.covering_index = False self.query = "CREATE PRIMARY INDEX ON %s" % query_bucket self.run_cbq_query() self._wait_for_index_online(bucket, '#primary') self.query = "select meta().id, meta().cas from {0} where meta().id like 'query-testemployee6%' order by " \ "meta().id limit 10".format(query_bucket) expected_list = self.run_cbq_query() diffs = DeepDiff(actual_result, expected_list['results'], ignore_order=True) if diffs: self.assertTrue(False, diffs) self.query = "DROP PRIMARY INDEX ON %s" % query_bucket self.run_cbq_query() def test_meta_ambiguity(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "create index idx on %s(META())" % query_bucket self.run_cbq_query() self.query = "create index idx2 on {0}(META())".format(query_bucket) self.run_cbq_query() self.query = "SELECT META() as meta_c FROM %s ORDER BY meta_c limit 10" % query_bucket actual_result = self.run_cbq_query() self.assertTrue(actual_result['status'] == "success") self.query = "SELECT META(test) as meta_c FROM %s as test ORDER BY meta_c limit 10" % query_bucket actual_result = self.run_cbq_query() self.assertTrue(actual_result['status'] == "success") self.query = "SELECT META(t1).id as id FROM " + self.query_buckets[0] + " t1 JOIN " + \ self.query_buckets[0] + " t2 ON KEYS t1.id;" self.assertTrue(actual_result['status'] == "success") self.query = "drop index idx ON %s" % query_bucket self.run_cbq_query() self.query = "drop index idx2 ON %s" % query_bucket self.run_cbq_query() def test_meta_where_greater_than(self): created_indexes = [] ind_list = ["one"] index_name = "one" self.fail_if_no_buckets() for query_bucket, bucket in zip(self.query_buckets, self.buckets): for ind in ind_list: index_name = "meta_where%s" % ind if ind == "one": self.query = "CREATE INDEX {0} ON {1}(meta().id,meta().cas) where meta().id >10 USING {2}".format( index_name, query_bucket, self.index_type) self.run_cbq_query() self._wait_for_index_online(bucket, index_name) created_indexes.append(index_name) for query_bucket, bucket in zip(self.query_buckets, self.buckets): self.query = "explain select meta().id, meta().cas from {0} where meta().id >10 order by meta().id".format( query_bucket) if self.covering_index: self.check_explain_covering_index(index_name[0]) self.query = "select meta().id, meta().cas from {0} where meta().id >10 order by meta().id limit 10".format( query_bucket) actual_list = self.run_cbq_query() actual_result = actual_list['results'] for index_name in created_indexes: self.query = "DROP INDEX %s ON %s USING %s" % (index_name, query_bucket, self.index_type) self.run_cbq_query() self.covering_index = False self.query = "CREATE PRIMARY INDEX ON %s" % query_bucket self.run_cbq_query() self._wait_for_index_online(bucket, '#primary') self.query = "select meta().id, meta().cas from {0} use index(`#primary`) where meta().id > 10 order by " \ "meta().id limit 10".format(query_bucket) expected_list = self.run_cbq_query() diffs = DeepDiff(actual_result, expected_list['results'], ignore_order=True) if diffs: self.assertTrue(False, diffs) self.query = "DROP PRIMARY INDEX ON %s" % query_bucket self.run_cbq_query() def test_meta_partial(self): created_indexes = [] ind_list = ["one"] index_name = "one" self.fail_if_no_buckets() for query_bucket, bucket in zip(self.query_buckets, self.buckets): for ind in ind_list: index_name = "meta_where%s" % ind if ind == "one": self.query = "CREATE INDEX {0} ON {1}(meta().id, name) where meta().id >10 USING {2}".format( index_name, query_bucket, self.index_type) # if self.gsi_type: # self.query += "WITH {'index_type': 'memdb'}" self.run_cbq_query() self._wait_for_index_online(bucket, index_name) created_indexes.append(index_name) for query_bucket, bucket in zip(self.query_buckets, self.buckets): self.query = "explain select meta().id, name from {0} where meta().id >10 and name is not null order by " \ "meta().id limit 10".format(query_bucket) if self.covering_index: self.check_explain_covering_index(index_name[0]) self.query = "select meta().id, name from {0} where meta().id >10 and name is not null order by " \ "meta().id limit 10".format(query_bucket) actual_list = self.run_cbq_query() actual_result = actual_list['results'] for index_name in created_indexes: self.query = "DROP INDEX %s ON %s USING %s" % (index_name, query_bucket, self.index_type) self.run_cbq_query() self.covering_index = False self.query = "CREATE PRIMARY INDEX ON %s" % query_bucket self.run_cbq_query() self._wait_for_index_online(bucket, '#primary') self.query = "select meta().id, name from {0} use index(`#primary`) where meta().id > 10 and name is not " \ "null order by meta().id limit 10".format(query_bucket) expected_list = self.run_cbq_query() diffs = DeepDiff(actual_result, expected_list['results'], ignore_order=True) if diffs: self.assertTrue(False, diffs) self.query = "DROP PRIMARY INDEX ON %s" % query_bucket self.run_cbq_query() def test_meta_non_supported(self): created_indexes = [] ind_list = ["one"] index_name = "one" self.fail_if_no_buckets() for query_bucket in self.query_buckets: for ind in ind_list: index_name = "meta_cas_%s" % ind if ind == "one": queries_errors = {'CREATE INDEX ONE ON ' + self.query_buckets[0] + ' (meta().cas) using GSI': ( 'syntax error', 3000), 'CREATE INDEX ONE ON ' + self.query_buckets[0] + ' (meta().flags) using GSI': ( 'syntax error', 3000), 'CREATE INDEX ONE ON ' + self.query_buckets[ 0] + ' (meta().expiration) using GSI': ( 'syntax error', 3000), 'CREATE INDEX ONE ON ' + self.query_buckets[0] + ' (meta().cas) using VIEW': ( 'syntax error', 3000)} def test_meta_negative_namespace(self): created_indexes = [] ind_list = ["one"] index_name = "one" self.fail_if_no_buckets() for query_bucket in self.query_buckets: for ind in ind_list: index_name = "meta_cas_%s" % ind if ind == "one": queries_errors = { 'CREATE INDEX TWO ON ' + self.query_buckets[0] + ' (meta(invalid).id) using GSI': ( 'syntax error', 3000), 'CREATE INDEX THREE ON ' + self.query_buckets[0] + ' (meta(invalid).id) using VIEW': ( 'syntax error', 3000), 'CREATE INDEX FOUR ON ' + self.query_buckets[0] + ' (meta()) using GSI': ('syntax error', 3000), 'CREATE INDEX FIVE ON ' + self.query_buckets[0] + ' (meta()) using VIEW': ( 'syntax error', 3000)} self.negative_common_body(queries_errors) # ####################### META NEW END ###################################### def test_intersect(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name from %s intersect select name from %s s where s.join_day>5" % ( query_bucket, query_bucket) actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"]} for doc in self.full_list if doc['join_day'] > 5] expected_result = [dict(y) for y in set(tuple(x.items()) for x in expected_result)] self._verify_results(actual_result, expected_result) def test_intersect_covering(self): created_indexes = [] ind_list = ["one", "two"] index_name = "one" self.fail_if_no_buckets() for query_bucket, bucket in zip(self.query_buckets, self.buckets): for ind in ind_list: index_name = "coveringindex{0}".format(ind) if ind == "one": self.query = "CREATE INDEX {0} ON {1}(job_title, name) USING {2}".format(index_name, query_bucket, self.index_type) elif ind == "two": self.query = "CREATE INDEX {0} ON {1}(join_day, name) USING {2}".format(index_name, query_bucket, self.index_type) self.run_cbq_query() self._wait_for_index_online(bucket, index_name) created_indexes.append(index_name) for query_bucket, bucket in zip(self.query_buckets, self.buckets): self.query = "explain select name from {0} where job_title='Engineer' intersect select name from {0} s where s.join_day>5".format(query_bucket) if self.covering_index: self.check_explain_covering_index(index_name) self.query = "select name from {0} where job_title='Engineer' intersect select name from {0} s where s.join_day>5".format(query_bucket) actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"]} for doc in self.full_list if doc['join_day'] > 5] expected_result = [dict(y) for y in set(tuple(x.items()) for x in expected_result)] self._verify_results(actual_result, expected_result) for ind in ind_list: index_name = "coveringindex{0}".format(ind) try: self.query = "DROP INDEX {0} ON {1} USING {2}".format(index_name, query_bucket, self.index_type) self.run_cbq_query() except Exception as e: self.log.error("Drop index failed {0}".format(str(e))) self.query = "CREATE PRIMARY INDEX ON {0}".format(query_bucket) self.run_cbq_query() self._wait_for_index_online(bucket, '#primary') self.query = "select name from {0} where job_title='Engineer' intersect select name from {0} s where s.join_day>5".format(query_bucket, query_bucket) expected_list = self.run_cbq_query() diffs = DeepDiff(actual_result, expected_list['results'], ignore_order=True) if diffs: self.assertTrue(False, diffs) self.query = "DROP PRIMARY INDEX ON {0}".format(query_bucket) self.run_cbq_query() def test_intersect_all(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name from %s intersect all select name from %s s where s.join_day>5" % ( query_bucket, query_bucket) actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"]} for doc in self.full_list if doc['join_day'] > 5] self._verify_results(actual_result, expected_result) def test_prepared_intersect(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name from %s intersect all select name from %s s where s.join_day>5" % ( query_bucket, query_bucket) self.prepared_common_body() def test_except_secondsetempty(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "drop primary index on %s USING %s" % (query_bucket, self.primary_indx_type) self.run_cbq_query() try: self.query = "(select id keyspace_id from system:keyspaces) except (select indexes.keyspace_id from " \ "system:indexes) " actual_list = self.run_cbq_query() bucket_names = [] for bucket in self.buckets: bucket_names.append(bucket.name) count = 0 for _ in self.query_buckets: if actual_list['results'][count]['keyspace_id'] in bucket_names: count += 1 else: self.log.error("Wrong keyspace id returned or empty keyspace id returned") finally: for query_bucket in self.query_buckets: self.query = "create primary index on %s" % query_bucket self.run_cbq_query() def test_except(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name from %s except select name from %s s where s.join_day>5" % ( query_bucket, query_bucket) actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"]} for doc in self.full_list if not doc['join_day'] > 5] expected_result = [dict(y) for y in set(tuple(x.items()) for x in expected_result)] self._verify_results(actual_result, expected_result) def test_except_all(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name from %s except all select name from %s s where s.join_day>5" % ( query_bucket, query_bucket) actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"]} for doc in self.full_list if not doc['join_day'] > 5] self._verify_results(actual_result, expected_result) ############################################################################################## # # WITHIN ############################################################################################## def test_within_list_object(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name, VMs from %s WHERE 5 WITHIN VMs" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"], "VMs": doc["VMs"]} for doc in self.full_list if len([vm for vm in doc["VMs"] if vm["RAM"] == 5])] self._verify_results(actual_result, expected_result) def test_prepared_within_list_object(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: query_bucket = self.get_collection_name(query_bucket) self.query = "select name, VMs from %s WHERE 5 WITHIN VMs" % query_bucket self.prepared_common_body() def test_within_list_of_lists(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name, VMs from %s where name within [['employee-2', 'employee-4']," \ " ['employee-5']] " % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"], "VMs": doc["VMs"]} for doc in self.full_list if doc["name"] in ['employee-2', 'employee-4', 'employee-5']] self._verify_results(actual_result, expected_result) def test_within_object(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name, tasks_points from %s WHERE 1 WITHIN tasks_points" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"], "tasks_points": doc["tasks_points"]} for doc in self.full_list if doc["tasks_points"]["task1"] == 1 or doc["tasks_points"]["task2"] == 1] self._verify_results(actual_result, expected_result) def test_within_array(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = " select name, skills from %s where 'skill2010' within skills" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"], "skills": doc["skills"]} for doc in self.full_list if 'skill2010' in doc["skills"]] self._verify_results(actual_result, expected_result) ############################################################################################## # # RAW ############################################################################################## def test_raw(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select raw name from %s " % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] self.query = "select raw reverse(reverse(name)) from %s " % query_bucket actual_list1 = self.run_cbq_query() actual_result1 = actual_list1['results'] expected_result = [doc["name"] for doc in self.full_list] self._verify_results(actual_result, expected_result) self._verify_results(actual_result, actual_result1) def test_raw_limit(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select raw skills[0] from %s limit 5" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [doc["skills"][0] for doc in self.full_list][:5] self._verify_results(actual_result, expected_result) def test_raw_order(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select raw name from {0} order by name {1}".format(query_bucket, "desc") actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [doc["name"] for doc in self.full_list] diffs = DeepDiff(actual_result, expected_result, ignore_order=True) if diffs: self.assertTrue(False, diffs) self.query = "select raw name from {0} order by name {1}".format(query_bucket, "asc") actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [doc["name"] for doc in self.full_list] self._verify_results(actual_result, expected_result) self.query = "select raw meta().id from {0} order by meta().id {1}".format(query_bucket, "asc") actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = sorted(actual_result) self.assertEqual(actual_result, expected_result) self.query = "select raw meta().id from {0} order by meta().id {1}".format(query_bucket, "desc") actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = sorted(actual_result, reverse=True) self.assertEqual(actual_result, expected_result) def test_push_limit(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'insert into %s(KEY, VALUE) VALUES ("f01", {"f1":"f1"})' % query_bucket self.run_cbq_query() self.query = 'insert into %s(KEY, VALUE) VALUES ("f02", {"f1":"f1","f2":"f2"})' % query_bucket self.run_cbq_query() self.query = 'create index if1 on %s(f1)' % query_bucket self.query = 'select q.id, q.f1,q.f2 from (select meta().id, f1,f2 from %s where f1="f1") q where q.f2 = ' \ '"f2" limit 1' % query_bucket result = self.run_cbq_query() self.assertTrue(result['metrics']['resultCount'] == 1) self.query = 'delete from %s use keys["f01","f02"]' % query_bucket self.run_cbq_query() ############################################################################################## # # Number fns ############################################################################################## # This test has no usages anywhere def test_abs(self): for query_bucket in self.query_buckets: self.query = "select join_day from %s where join_day > abs(-10)" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [doc["join_day"] for doc in self.full_list if doc["join_day"] > abs(-10)] self._verify_results(actual_result, expected_result) # This test has no usages anywhere def test_acos(self): self.query = "select degrees(acos(0.5))" actual_list = self.run_cbq_query() expected_result = [{'$1': 60}] self._verify_results(actual_list['results'], expected_result) # Test has no usages anywhere def test_asin(self): self.query = "select degrees(asin(0.5))" actual_list = self.run_cbq_query() expected_result = [{'$1': 30}] self._verify_results(actual_list['results'], expected_result) # Test has no usages anywhere def test_tan(self): self.query = "select tan(radians(45))" actual_list = self.run_cbq_query() expected_result = [{'$1': 1}] self._verify_results(actual_list['results'], expected_result) # This test has no usages anywhere def test_ln(self): self.query = "select ln(10) = ln(2) + ln(5)" actual_list = self.run_cbq_query() expected_result = [{'$1': True}] self._verify_results(actual_list['results'], expected_result) # This test has no usages anywhere def test_power(self): self.query = "select power(sin(radians(33)), 2) + power(cos(radians(33)), 2)" actual_list = self.run_cbq_query() expected_result = [{'$1': 1}] self._verify_results(actual_list['results'], expected_result) # Test has no usages anywhere def test_sqrt(self): self.query = "select sqrt(9)" actual_list = self.run_cbq_query() expected_result = [{'$1': 3}] self._verify_results(actual_list['results'], expected_result) # This test has no uses anywhere def test_sign(self): self.query = "select sign(-5)" actual_list = self.run_cbq_query() expected_result = [{'$1': -1}] self._verify_results(actual_list['results'], expected_result) self.query = "select sign(5)" actual_list = self.run_cbq_query() expected_result = [{'$1': 1}] self._verify_results(actual_list['results'], expected_result) self.query = "select sign(0)" actual_list = self.run_cbq_query() expected_result = [{'$1': 0}] self._verify_results(actual_list['results'], expected_result) ############################################################################################## # # CONDITIONAL FNS ############################################################################################## def test_nanif(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select join_day, join_mo, NANIF(join_day, join_mo) as equality" + \ " from %s" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"join_day": doc["join_day"], "join_mo": doc["join_mo"], "equality": doc["join_day"] if doc["join_day"] != doc["join_mo"] else 'NaN'} for doc in self.full_list] self._verify_results(actual_result, expected_result) def test_posinf(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select join_day, join_mo, POSINFIF(join_day, join_mo) as equality" + \ " from %s" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"join_day": doc["join_day"], "join_mo": doc["join_mo"], "equality": doc["join_day"] if doc["join_day"] != doc["join_mo"] else '+Infinity'} for doc in self.full_list] self._verify_results(actual_result, expected_result) ############################################################################################## # # String FUNCTIONS ############################################################################################## def test_uuid(self): self.query = "select uuid() as uuid" actual_list = self.run_cbq_query() self.assertTrue('uuid' in actual_list['results'][0] and actual_list['results'][0]['uuid'], 'UUid is not working') def test_string_fn_negative(self): queries_errors = {'select name from %s when contains(VMs, "Sale")': ('syntax error', 3000), 'select TITLE(test_rate) as OS from %s': ('syntax error', 3000), 'select REPEAT(name, -2) as name from %s': ('syntax error', 3000), 'select REPEAT(name, a) as name from %s': ('syntax error', 3000), } self.negative_common_body(queries_errors) def test_contains(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name from %s where contains(job_title, 'Sale')" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] self.query = "select name from %s where contains(reverse(job_title), reverse('Sale'))" % query_bucket actual_list1 = self.run_cbq_query() actual_result1 = actual_list1['results'] diffs = DeepDiff(actual_result, actual_result1, ignore_order=True) if diffs: self.assertTrue(False, diffs) expected_result = [{"name": doc["name"]} for doc in self.full_list if doc['job_title'].find('Sale') != -1] self._verify_results(actual_result, expected_result) def test_initcap(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select INITCAP(VMs[0].os) as OS from %s" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"OS": (doc["VMs"][0]["os"][0].upper() + doc["VMs"][0]["os"][1:])} for doc in self.full_list] self._verify_results(actual_result, expected_result) def test_title(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select TITLE(VMs[0].os) as OS from %s" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] self.query = "select TITLE(REVERSE(VMs[0].os)) as rev_os from %s" % query_bucket actual_list1 = self.run_cbq_query() actual_result1 = actual_list1['results'] expected_result = [{"OS": (doc["VMs"][0]["os"][0].upper() + doc["VMs"][0]["os"][1:])} for doc in self.full_list] expected_result1 = [{"rev_os": (doc["VMs"][0]["os"][::-1][0].upper() + doc["VMs"][0]["os"][::-1][1:])} for doc in self.full_list] self._verify_results(actual_result, expected_result) self._verify_results(actual_result1, expected_result1) def test_prepared_title(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select TITLE(VMs[0].os) as OS from %s" % query_bucket self.prepared_common_body() def test_position(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select POSITION(VMs[1].name, 'vm') pos from %s" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"pos": (doc["VMs"][1]["name"].find('vm'))} for doc in self.full_list] self._verify_results(actual_result, expected_result) self.query = "select POSITION(VMs[1].name, 'server') pos from %s" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"pos": (doc["VMs"][1]["name"].find('server'))} for doc in self.full_list] self._verify_results(actual_result, expected_result) test_word = 'california' for letter in test_word: actual = self.run_position_query(test_word, letter) expected = test_word.find(letter) self.assertEqual(actual, expected) letter = '' actual = self.run_position_query(test_word, letter) expected = test_word.find(letter) self.assertEqual(actual, expected) letter = 'd' actual = self.run_position_query(test_word, letter) expected = test_word.find(letter) self.assertEqual(actual, expected) def test_position0(self): test_word = 'california' for letter in test_word: actual = self.run_position_query(test_word, letter, position_type='0') expected = test_word.find(letter) self.assertEqual(actual, expected) letter = '' actual = self.run_position_query(test_word, letter, position_type='0') expected = test_word.find(letter) self.assertEqual(actual, expected) letter = 'd' actual = self.run_position_query(test_word, letter, position_type='0') expected = test_word.find(letter) self.assertEqual(actual, expected) def test_position1(self): test_word = 'california' for letter in test_word: actual = self.run_position_query(test_word, letter, position_type='1') expected = test_word.find(letter) + 1 self.assertEqual(actual, expected) letter = '' actual = self.run_position_query(test_word, letter, position_type='1') expected = test_word.find(letter) + 1 self.assertEqual(actual, expected) letter = 'd' actual = self.run_position_query(test_word, letter, position_type='1') expected = test_word.find(letter) + 1 self.assertEqual(actual, expected) def test_regex_contains(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select email from %s where REGEXP_CONTAINS(email, '-m..l')" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] self.query = "select email from %s where REGEXP_CONTAINS(reverse(email), 'l..m-')" % query_bucket actual_list1 = self.run_cbq_query() actual_result1 = actual_list1['results'] diffs = DeepDiff(actual_result, actual_result1, ignore_order=True) if diffs: self.assertTrue(False, diffs) actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"email": doc["email"]} for doc in self.full_list if len(re.compile('-m..l').findall(doc['email'])) > 0] self._verify_results(actual_result, expected_result) def test_regex_like(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select email from %s where REGEXP_LIKE(email, '.*-mail.*')" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"email": doc["email"]} for doc in self.full_list if re.compile('.*-mail.*').search(doc['email'])] self._verify_results(actual_result, expected_result) def test_regex_position(self): test_word = 'california' for letter in test_word: actual = self.run_regex_query(test_word, letter) expected = test_word.find(letter) self.assertEqual(actual, expected) letter = '' actual = self.run_regex_query(test_word, letter) expected = test_word.find(letter) self.assertEqual(actual, expected) letter = 'd' actual = self.run_regex_query(test_word, letter) expected = test_word.find(letter) self.assertEqual(actual, expected) def test_regex_position0(self): test_word = 'california' for letter in test_word: actual = self.run_regex_query(test_word, letter, regex_type='0') expected = test_word.find(letter) self.assertEqual(actual, expected) letter = '' actual = self.run_regex_query(test_word, letter, regex_type='0') expected = test_word.find(letter) self.assertEqual(actual, expected) letter = 'd' actual = self.run_regex_query(test_word, letter, regex_type='0') expected = test_word.find(letter) self.assertEqual(actual, expected) def test_regex_position1(self): test_word = 'california' for letter in test_word: actual = self.run_regex_query(test_word, letter, regex_type='1') expected = test_word.find(letter) + 1 self.assertEqual(actual, expected) letter = '' actual = self.run_regex_query(test_word, letter, regex_type='1') expected = test_word.find(letter) + 1 self.assertEqual(actual, expected) letter = 'd' actual = self.run_regex_query(test_word, letter, regex_type='1') expected = test_word.find(letter) self.assertEqual(actual, expected) def test_regex_replace(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name, REGEXP_REPLACE(email, '-mail', 'domain') as mail from %s" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"], "mail": doc["email"].replace('-mail', 'domain')} for doc in self.full_list] self._verify_results(actual_result, expected_result) self.query = "select name, REGEXP_REPLACE(email, 'e', 'a', 2) as mail from %s" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"], "mail": doc["email"].replace('e', 'a', 2)} for doc in self.full_list] self._verify_results(actual_result, expected_result) def test_replace(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name, REPLACE(email, 'a', 'e', 1) as mail from %s" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"], "mail": doc["email"].replace('a', 'e', 1)} for doc in self.full_list] self._verify_results(actual_result, expected_result) def test_repeat(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select REPEAT(name, 2) as name from %s" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"] * 2} for doc in self.full_list] self._verify_results(actual_result, expected_result) ############################################################################################## # # LET ############################################################################################## def test_let_nums(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select test_r, test_r > 2 compare from %s let test_r = (test_rate / 2)" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"test_r": doc["test_rate"] / 2, "compare": (doc["test_rate"] / 2) > 2} for doc in self.full_list] self._verify_results(actual_result, expected_result) def test_prepared_let_nums(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select test_r, test_r > 2 compare from %s let test_r = (test_rate / 2)" % query_bucket self.prepared_common_body() def test_let_string(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name, join_date as date from %s let join_date = tostr(join_yr) || '-' || tostr(" \ "join_mo)" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"], "date": '%s-%s' % (doc['join_yr'], doc['join_mo'])} for doc in self.full_list] self._verify_results(actual_result, expected_result) self.query = "select name, join_date as date from %s let join_date = reverse(tostr(join_yr)) || '-' || " \ "reverse(tostr(join_mo)) order by name, meta().id limit 10" % query_bucket actual_list2 = self.run_cbq_query() actual_result2 = actual_list2['results'] expected_result2 = [{'date': '1102-9', 'name': 'employee-1'}, {'date': '1102-9', 'name': 'employee-1'}, {'date': '1102-9', 'name': 'employee-1'}, {'date': '1102-9', 'name': 'employee-1'}, {'date': '1102-9', 'name': 'employee-1'}, {'date': '1102-9', 'name': 'employee-1'}, {'date': '0102-4', 'name': 'employee-1'}, {'date': '0102-4', 'name': 'employee-1'}, {'date': '0102-4', 'name': 'employee-1'}, {'date': '0102-4', 'name': 'employee-1'}] self._verify_results(actual_result2, expected_result2) def test_letting(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT join_mo, sum_test from %s WHERE join_mo>7 group by join_mo letting sum_test = sum(" \ "tasks_points.task1)" % query_bucket if self.analytics: self.query = "SELECT d.join_mo, sum_test from %s d WHERE d.join_mo>7 group by d.join_mo letting " \ "sum_test = sum(d.tasks_points.task1)" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] tmp_groups = {doc['join_mo'] for doc in self.full_list if doc['join_mo'] > 7} expected_result = [{"join_mo": group, "sum_test": sum([x["tasks_points"]["task1"] for x in self.full_list if x["join_mo"] == group])} for group in tmp_groups] self._verify_results(actual_result, expected_result) def test_prepared_letting(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT join_mo, sum_test from %s WHERE join_mo>7 group by join_mo letting sum_test = sum(" \ "tasks_points.task1)" % query_bucket self.prepared_common_body() # https://issues.couchbase.com/browse/MB-26086 def check_special_symbols(self): self.fail_if_no_buckets() symbols = ['~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '-', '+', '=', '{', '[', '}', ']', '|', '.', ':', ';', '"', '<', ',', '>', '.', '?', '/'] errors_simple = {} errors_complex = {} query = "INSERT INTO " + self.query_buckets[0] + " VALUES ('simple', {" for i in range(len(symbols)): query += "'a" + symbols[i] + "b':1" if i < len(symbols) - 1: query += "," query += "})" self.run_cbq_query(query) for i in range(len(symbols)): query = "SELECT `a" + symbols[i] + "b` FROM " + self.query_buckets[0] + " USE KEYS ['simple'] WHERE `a" + \ symbols[i] + "b` IS NOT MISSING" result = self.run_cbq_query(query) if result['metrics']['resultCount'] < 1: errors_simple[symbols[i]] = query # Assuming I have only 3 special characters: ~!@ the resulting query will be like # INSERT INTO default VALUES ('complex', {'a~b':{'a~b':12, 'a!b':12, 'a@b':12}, # 'a!b':{'a~b':12, 'a!b':12, 'a@b':12}, # 'a@b':{'a~b':12, 'a!b':12, 'a@b':12 }}) query = "INSERT INTO " + self.query_buckets[0] + " VALUES ('complex', {" for i in range(len(symbols)): query += "'a" + symbols[i] + "b':{" for j in range(len(symbols)): query += "'a" + symbols[j] + "b':12" if j < len(symbols) - 1: query += "," else: query += "}" if i < len(symbols) - 1: query += "," query += "})" self.run_cbq_query(query) for i in range(len(symbols)): for j in range(len(symbols)): query = "SELECT `a" + symbols[i] + "b`.`a" + symbols[j] + \ "b` FROM " + self.query_buckets[0] + " USE KEYS ['complex'] WHERE `a" + symbols[i] + \ "b`.`a" + symbols[j] + "b` IS NOT MISSING" result = self.run_cbq_query(query) if result['metrics']['resultCount'] < 1: errors_complex[str(symbols[i]) + str(symbols[j])] = query self.assertEqual(len(errors_simple) + len(errors_complex), 0)
import datetime import json import math import random import re import time import threading from datetime import date from deepdiff import DeepDiff from membase.api.exception import CBQError from membase.api.rest_client import RestConnection from remote.remote_util import RemoteMachineShellConnection from collection.collections_n1ql_client import CollectionsN1QL from .tuq import QueryTests class QuerySanityTests(QueryTests): def setUp(self): super(QuerySanityTests, self).setUp() self.log.info("============== QuerySanityTests setup has started ==============") self.index_to_be_created = self.input.param("index_to_be_created", '') self.query_to_be_run = self.input.param("query_to_be_run", '') if self.load_sample: self.rest.load_sample("travel-sample") self.wait_for_all_indexes_online() self.log.info("============== QuerySanityTests setup has completed ==============") self.log_config_info() self.query_buckets = self.get_query_buckets(check_all_buckets=True) self.collection_names = [] self.creation_failure = [] self.deletion_failure = [] def suite_setUp(self): super(QuerySanityTests, self).suite_setUp() self.log.info("============== QuerySanityTests suite_setup has started ==============") if self.input.param("fast_count", False): random_number = 23917 shell = RemoteMachineShellConnection(self.master) shell.execute_cbworkloadgen(self.rest.username, self.rest.password, random_number, 100, self.default_bucket_name, 1024, '-j') self.run_cbq_query( query="INSERT INTO " + self.query_buckets[0] + " ( key, value) VALUES ('pymc100205',{'name':'Sara','age':'30'})") self.log.info("============== QuerySanityTests suite_setup has completed ==============") def tearDown(self): self.log.info("============== QuerySanityTests tearDown has started ==============") self.log.info("============== QuerySanityTests tearDown has completed ==============") super(QuerySanityTests, self).tearDown() def suite_tearDown(self): self.log.info("============== QuerySanityTests suite_tearDown has started ==============") self.log.info("============== QuerySanityTests suite_tearDown has completed ==============") super(QuerySanityTests, self).suite_tearDown() ############################################################################################## # # SIMPLE CHECKS ############################################################################################## def test_error_message_collections_full(self): try: self.run_cbq_query(query="SELECT * FROM default:default.test.tes") self.fail("This query should error") except Exception as e: self.assertTrue("Keyspace not found in CB datastore: default:default.test.tes" in str(e), "The full path was not inside the error message! {0}".format(str(e))) try: self.run_cbq_query(query="SELECT * FROM default.test.tes") self.fail("This query should error") except Exception as e: self.assertTrue("Keyspace not found in CB datastore: default:default.test.tes" in str(e), "The full path was not inside the error message! {0}".format(str(e))) def test_error_message_collections_query_context(self): try: self.run_cbq_query(query="SELECT * FROM tes", query_context=self.query_context) self.fail("This query should error") except Exception as e: self.assertTrue("Keyspace not found in CB datastore: default:default.test.tes" in str(e), "The full path was not inside the error message! {0}".format(str(e))) def test_error_namespace(self): try: results = self.run_cbq_query(query='select * from default.test.tes where name = "new hotel"', query_context='default:') self.fail("This query should error") except Exception as e: self.assertTrue("Keyspace not found in CB datastore: default:default.test.tes" in str(e), "The full path was not inside the error message! {0}".format(str(e))) def test_stats_collections(self): curl_output = self.shell.execute_command( "curl http://{0}:{1}/admin/stats".format(self.master.ip, self.n1ql_port)) curl = json.loads(curl_output[0][0]) starting_deletes = curl['deletes.count'] starting_selects = curl['selects.count'] starting_inserts = curl['inserts.count'] try: self.run_cbq_query(query="CREATE PRIMARY INDEX ON default:default.{0}.{1}".format(self.scope, self.collections[0])) self.run_cbq_query(query="SELECT * FROM default:default.test.test1 b WHERE b.name = 'new hotel'") self.run_cbq_query(query="SELECT * FROM test1 b WHERE b.name = 'new hotel'", query_context='default:default.test') self.run_cbq_query( query=('INSERT INTO default:default.{0}.{1}'.format(self.scope, self.collections[ 0]) + '(KEY, VALUE) VALUES ("key6", { "type" : "hotel", "name" : "new hotel" })')) self.run_cbq_query( query='DELETE FROM default:default.test.test1 LIMIT 1') curl_output = self.shell.execute_command( "curl http://{0}:{1}/admin/stats".format(self.master.ip, self.n1ql_port)) curl = json.loads(curl_output[0][0]) self.assertEqual(curl['deletes.count'], starting_deletes + 1) self.assertEqual(curl['selects.count'], starting_selects + 2) self.assertEqual(curl['inserts.count'], starting_inserts + 1) except Exception as e: self.log.error("One of the queries failed or the stats were wrong: {0}".format(str(e))) self.fail() def test_stats_collections_prepareds(self): try: self.run_cbq_query(query="PREPARE p1 AS SELECT * FROM default:default.test.test1 b WHERE b.name = 'new hotel'") self.run_cbq_query(query="PREPARE p2 AS SELECT * FROM test1 b WHERE b.name = 'new hotel'", query_context='default:default.test') self.run_cbq_query(query="execute p2", query_context='default:default.test') self.run_cbq_query(query="execute p1", query_context='default:default.test') curl_output = self.shell.execute_command("curl http://{0}:{1}/admin/stats".format(self.master.ip, self.n1ql_port)) curl = json.loads(curl_output[0][0]) self.assertEqual(curl['prepared.count'], 2) finally: self.run_cbq_query(query="DELETE from system:prepareds") def test_escaped_identifiers(self): self.fail_if_no_buckets() queries_errors = {'SELECT name FROM {0} as bucket': ('syntax error', 3000)} self.negative_common_body(queries_errors) for query_bucket in self.query_buckets: self.query = 'SELECT name FROM %s as `bucket` ORDER BY name' % query_bucket actual_result = self.run_cbq_query() expected_list = [{"name": doc["name"]} for doc in self.full_list] expected_list_sorted = sorted(expected_list, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_list_sorted) def test_prepared_encoded_rest(self): result_count = 1412 if not self.sample_bucket: self.sample_bucket = 'beer-sample' self.rest.load_sample(self.sample_bucket) self.wait_for_buckets_status({self.sample_bucket: "healthy"}, 5, 120) self.wait_for_bucket_docs({self.sample_bucket: 7303}, 5, 120) self._wait_for_index_online('beer-sample', 'beer_primary') query_bucket = self.get_collection_name(self.sample_bucket) try: query = 'create index myidx on {0}(name,country,code) where (type="brewery")'.format(query_bucket) self.run_cbq_query(query) self._wait_for_index_online('beer-sample', 'myidx') query = 'prepare s1 from SELECT name, IFMISSINGORNULL(country,999), IFMISSINGORNULL(code,999)' \ ' FROM {0} WHERE type = "brewery" AND name IS NOT MISSING'.format(query_bucket) result = self.run_cbq_query(query) encoded_plan = '"' + result['results'][0]['encoded_plan'] + '"' for server in self.servers: remote = RemoteMachineShellConnection(server) remote.stop_server() time.sleep(20) server = None for server in self.servers: remote = RemoteMachineShellConnection(server) remote.start_server() self.wait_for_buckets_status({self.sample_bucket: "healthy"}, 5, 120) self.wait_for_bucket_docs({self.sample_bucket: 7303}, 5, 120) self._wait_for_index_online('beer-sample', 'beer_primary') cmd = "%s http://%s:%s/query/service -u %s:%s -H 'Content-Type: application/json' " \ "-d '{ \"prepared\": \"s1\", \"encoded_plan\": %s }'" % ( self.curl_path, server.ip, self.n1ql_port, self.username, self.password, encoded_plan) for server in self.servers: remote = RemoteMachineShellConnection(server) result = remote.execute_command(cmd) new_list = [string.strip() for string in result[0]] concat_string = ''.join(new_list) json_output = json.loads(concat_string) self.log.info(json_output['metrics']['resultCount']) self.assertEqual(json_output['metrics']['resultCount'], result_count) finally: self.rest.delete_bucket(self.sample_bucket) self.wait_for_bucket_delete(self.sample_bucket, 5, 120) # These bugs are not planned to be fixed therefore this test isnt in any confs '''MB-19887 and MB-24303: These queries were returning incorrect results with views.''' def test_views(self): self.fail_if_no_buckets() created_indexes = [] try: idx = "ix1" self.query = "CREATE INDEX %s ON " % idx + self.query_buckets[0] + " (x,y) USING VIEW" self.run_cbq_query() created_indexes.append(idx) time.sleep(15) self.run_cbq_query("insert into " + self.query_buckets[0] + " values ('k01',{'x':10})") result = self.run_cbq_query("select x,y from " + self.query_buckets[0] + " where x > 3") self.assertTrue(result['results'][0] == {"x": 10}) self.run_cbq_query('insert into ' + self.query_buckets[0] + ' values("k02", {"x": 20, "y": 20})') self.run_cbq_query('insert into ' + self.query_buckets[0] + ' values("k03", {"x": 30, "z": 30})') self.run_cbq_query('insert into ' + self.query_buckets[0] + ' values("k04", {"x": 40, "y": 40, "z": 40})') idx2 = "iv1" self.query = "CREATE INDEX %s ON " % idx2 + self.query_buckets[0] + " (x,y,z) USING VIEW" self.run_cbq_query() created_indexes.append(idx2) expected_result = [{'x': 10}, {'x': 20, 'y': 20}, {'x': 30, 'z': 30}, {'x': 40, 'y': 40, 'z': 40}] result = self.run_cbq_query('select x,y,z from ' + self.query_buckets[0] + ' use index (iv1 using view) ' 'where x is not missing') self.assertTrue(result['results'] == expected_result) finally: for idx in created_indexes: self.query = "DROP INDEX %s ON %s USING VIEW" % (self.query_buckets[0], idx) self.run_cbq_query() def test_collections_meta_keyspace(self): results = self.run_cbq_query(query='select meta(d) from default:default.test.test1 as d') self.assertEqual(results['results'][0]['$1']['keyspace'], 'default:default.test.test1') def test_collections_meta_query_context(self): results = self.run_cbq_query(query='select meta(d) from test1 as d', query_context='default:default.test') self.assertEqual(results['results'][0]['$1']['keyspace'], 'default:default.test.test1') def test_collections_meta_keyspace_full(self): results = self.run_cbq_query(query='select meta(default.test.test1) from default:default.test.test1') self.assertEqual(results['results'][0]['$1']['keyspace'], 'default:default.test.test1') results = self.run_cbq_query(query='select meta(default:default.test.test1) from default:default.test.test1') self.assertEqual(results['results'][0]['$1']['keyspace'], 'default:default.test.test1') def test_collections_meta_id(self): results = self.run_cbq_query(query='select meta(d).id from default:default.test.test1 as d') self.assertEqual(results['results'], [{'id': 'key1'}, {'id': 'key2'}, {'id': 'key3'}, {'id': 'key4'}]) results = self.run_cbq_query(query='select meta(d).id from test1 as d', query_context='default:default.test') self.assertEqual(results['results'], [{'id': 'key1'}, {'id': 'key2'}, {'id': 'key3'}, {'id': 'key4'}]) def test_collections_meta_id_full_path(self): results = self.run_cbq_query(query='select meta(default.test.test1).id from default:default.test.test1') self.assertEqual(results['results'], [{'id': 'key1'}, {'id': 'key2'}, {'id': 'key3'}, {'id': 'key4'}]) results = self.run_cbq_query(query='select meta(default:default.test.test1).id from default:default.test.test1') self.assertEqual(results['results'], [{'id': 'key1'}, {'id': 'key2'}, {'id': 'key3'}, {'id': 'key4'}]) def test_collections_meta_cas(self): results = self.run_cbq_query(query='select meta(d).cas from default:default.test.test1 as d') self.assertEqual(results['metrics']['resultCount'], 4) results = self.run_cbq_query(query='select meta(d).cas from test1 as d', query_context='default:default.test') self.assertEqual(results['metrics']['resultCount'], 4) def test_collections_meta_cas_full(self): results = self.run_cbq_query(query='select meta(default.test.test1).cas from default:default.test.test1') self.assertEqual(results['metrics']['resultCount'], 4) results = self.run_cbq_query(query='select meta(default:default.test.test1).cas from default:default.test.test1') self.assertEqual(results['metrics']['resultCount'], 4) def test_collections_meta_expiration(self): results = self.run_cbq_query(query='select meta(d).expiration from default:default.test.test1 as d') self.assertEqual(results['results'], [{'expiration': 0}, {'expiration': 0}, {'expiration': 0}, {'expiration': 0}]) results = self.run_cbq_query(query='select meta(d).expiration from test1 as d', query_context='default:default.test') self.assertEqual(results['results'], [{'expiration': 0}, {'expiration': 0}, {'expiration': 0}, {'expiration': 0}]) def test_collections_meta_expiration_full(self): results = self.run_cbq_query(query='select meta(default.test.test1).expiration from default:default.test.test1') self.assertEqual(results['results'], [{'expiration': 0}, {'expiration': 0}, {'expiration': 0}, {'expiration': 0}]) results = self.run_cbq_query(query='select meta(default:default.test.test1).expiration from default:default.test.test1') self.assertEqual(results['results'], [{'expiration': 0}, {'expiration': 0}, {'expiration': 0}, {'expiration': 0}]) ''' This test will concurrently create and drop collections, and then give them 5 seconds to appear in system:keyspaces, if any one collection creation/deletion fails the whole test fails ''' def test_create_drop_collections(self): self.collections_helper = CollectionsN1QL(self.master) self.collections_helper.create_scope(bucket_name="default", scope_name="scope1") self.collections_helper.create_scope(bucket_name="default", scope_name="scope2") for i in range(0, 100): thread_name = threading.Thread(name='run_collection', target=self.run_create_collection,args=("scope1", "collection1" + str(i))) thread2_name = threading.Thread(name='run_collection', target=self.run_create_collection,args=("scope2", "collection2" + str(i))) thread_name.start() thread2_name.start() self.sleep(1) if len(self.creation_failure) > 0: for collection in self.creation_failure: self.log.error("Creation failed for collection: {0}".format(str(collection))) self.fail("Some collections failed to create! Check logs for more details") if len(self.collection_names) > 0: for collection in self.collection_names: delete_thread = threading.Thread(name='drop_collection', target=self.run_drop_collection, args=(collection[0], collection[1])) delete_thread.start() delete_thread.join() if len(self.deletion_failure) > 0: for collection in self.deletion_failure: self.log.error("Deletion failed for collection: {0}".format(str(collection))) self.fail("Some collections failed to drop! Check logs for more details") retry_count = 100 while retry_count > 0: if len(self.collection_names) > 0: for collection in self.collection_names: delete_thread = threading.Thread(name='drop_collection', target=self.run_drop_collection, args=(collection[0], collection[1])) delete_thread.start() if len(self.deletion_failure) > 0: for collection in self.deletion_failure: self.log.error("Deletion failed for collection: {0}".format(str(collection))) self.fail("Some collections failed to drop! Check logs for more details") self.sleep(.5) retry_count -= 1 if len(self.creation_failure) > 0: for collection in self.creation_failure: self.log.error("Creation failed for collection: {0}".format(str(collection))) self.fail("Some collections failed to create! Check logs for more details") if len(self.deletion_failure) > 0: for collection in self.deletion_failure: self.log.error("Deletion failed for collection: {0}".format(str(collection))) self.fail("Some collections failed to drop! Check logs for more details") '''Create a collection and verify that within 5 seconds it is apart of system:keyspaces, print any errors that occur''' def run_create_collection(self, scope_name='',collection_name=''): retry_count = 5 created = self.collections_helper.create_collection(bucket_name="default", scope_name=scope_name, collection_name=collection_name) while retry_count > 0: try: results = self.run_cbq_query('select * from system:keyspaces where name = "{0}"'.format(collection_name)) if results['metrics']['resultCount'] == 1: break except Exception as e: self.log.info(str(e)) continue self.sleep(1) retry_count -= 1 if not retry_count > 0: if collection_name not in self.creation_failure: self.creation_failure.append((scope_name, collection_name, "Entry not found in system:keyspaces")) if collection_name not in self.creation_failure: self.collection_names.append((scope_name, collection_name)) return '''Drop a collection and verify that within 5 seconds it is removed from system:keyspaces''' def run_drop_collection(self, scope_name='', collection_name=''): retry_count = 5 deleted = self.collections_helper.delete_collection(bucket_name="default", scope_name=scope_name, collection_name=collection_name) while retry_count > 0: try: results = self.run_cbq_query('select * from system:keyspaces where name = "{0}"'.format(collection_name)) if results['metrics']['resultCount'] == 0: break except Exception as e: if 'Keyspace not found in CB datastore' in str(e): break continue self.sleep(1) retry_count -= 1 if not retry_count > 0: if collection_name not in self.deletion_failure: self.deletion_failure.append((scope_name, collection_name, "Entry not deleted from system:keyspaces")) self.collection_names.remove((scope_name, collection_name)) return ############################################################################################## # # ALL ############################################################################################## def test_all(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'SELECT ALL job_title FROM %s ORDER BY job_title' % query_bucket actual_result = self.run_cbq_query() expected_result = [{"job_title": doc['job_title']} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result['results'], expected_result) def test_all_nested(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'SELECT ALL tasks_points.task1 FROM %s ' % query_bucket + \ 'ORDER BY tasks_points.task1' actual_result = self.run_cbq_query() expected_result = [{"task1": doc['tasks_points']['task1']} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['task1'])) self._verify_results(actual_result['results'], expected_result) self.query = 'SELECT ALL skills[0] as skill' + \ ' FROM %s ORDER BY skills[0]' % query_bucket actual_result = self.run_cbq_query() expected_result = [{"skill": doc['skills'][0]} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['skill'])) self._verify_results(actual_result['results'], expected_result) if not self.analytics: self.query = 'SELECT ALL tasks_points.* FROM %s' % query_bucket actual_result = self.run_cbq_query() expected_result = [doc['tasks_points'] for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['task1'], doc['task2'])) actual_result = sorted(actual_result['results'], key=lambda doc: (doc['task1'], doc['task2'])) self._verify_results(actual_result, expected_result) # This method is not used anywhere def set_indexer_pokemon_settings(self): projector_json = {"projector.dcp.numConnections": 1} moi_json = {"indexer.moi.useMemMgmt": True} server = self.get_nodes_from_services_map(service_type="index") rest = RestConnection(server) rest.set_index_settings(projector_json) self.log.info("{0} set".format(projector_json)) self.sleep(60) servers = self.get_nodes_from_services_map(service_type="kv", get_all_nodes=True) for server in servers: remote = RemoteMachineShellConnection(server) remote.terminate_process(process_name="projector") self.sleep(60) self.sleep(60) # self.set_indexer_logLevel() self.loglevel = "info" self.log.info("Setting indexer log level to {0}".format(self.loglevel)) server = self.get_nodes_from_services_map(service_type="index") rest = RestConnection(server) rest.set_indexer_params("logLevel", self.loglevel) self.sleep(30) rest.set_index_settings(moi_json) self.log.info("{0} set".format(moi_json)) self.sleep(30) def test_all_negative(self): queries_errors = {'SELECT ALL * FROM %s': ('syntax error', 3000)} self.negative_common_body(queries_errors) def test_keywords(self): queries_errors = {'SELECT description as DESC FROM %s order by DESC': ('syntax error', 3000)} self.negative_common_body(queries_errors) def test_distinct_negative(self): queries_errors = {'SELECT name FROM {0} ORDER BY DISTINCT name': ('syntax error', 3000), 'SELECT name FROM {0} GROUP BY DISTINCT name': ('syntax error', 3000), 'SELECT ANY tasks_points FROM {0}': ('syntax error', 3000)} self.negative_common_body(queries_errors) def test_any(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name, email FROM {0} d WHERE (ANY skill IN d.skills SATISFIES skill = 'skill2010' " \ "END) AND (ANY vm IN d.VMs SATISFIES vm.RAM = 5 END) AND NOT (job_title = 'Sales') ORDER BY" \ " name".format(query_bucket) actual_result = self.run_cbq_query() expected_result = [{"name": doc['name'], "email": doc["email"]} for doc in self.full_list if len([skill for skill in doc["skills"] if skill == 'skill2010']) > 0 and len([vm for vm in doc["VMs"] if vm["RAM"] == 5]) > 0 and doc["job_title"] != 'Sales'] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) # This test isnt used anywhere def test_any_within(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name, email FROM %s " % query_bucket + \ " d WHERE ANY vm within d.VMs SATISFIES vm.RAM = 5 END" actual_result = self.run_cbq_query() expected_result = [{"name": doc['name'], "email": doc["email"]} for doc in self.full_list if len([vm for vm in doc["VMs"] if vm["RAM"] == 5]) > 0] self._verify_results(actual_result['results'], expected_result) def test_any_no_in_clause(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name, email FROM %s d WHERE " % query_bucket + \ "(ANY skill IN d.skills SATISFIES skill = 'skill2010' end)" + \ "AND (ANY vm IN d.VMs SATISFIES vm.RAM = 5 end) " + \ "AND NOT (job_title = 'Sales') ORDER BY name" actual_result = self.run_cbq_query() expected_result = [{"name": doc['name'], "email": doc["email"]} for doc in self.full_list if len([skill for skill in doc["skills"] if skill == 'skill2010']) > 0 and len([vm for vm in doc["VMs"] if vm["RAM"] == 5]) > 0 and doc["job_title"] != 'Sales'] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) def test_prepared_any_no_in_clause(self): self.fail_if_no_buckets() if self.monitoring: self.query = "select * from system:prepareds" result = self.run_cbq_query() self.assertTrue(result['metrics']['resultCount'] == 0) for query_bucket in self.query_buckets: query_bucket = self.get_collection_name(query_bucket) self.query = "SELECT name, email FROM %s as d WHERE " % query_bucket + \ "(ANY skill IN d.skills SATISFIES skill = 'skill2010' end) AND" \ " (ANY vm IN d.VMs SATISFIES vm.RAM = 5 end) " \ "AND NOT (job_title = 'Sales') ORDER BY name" self.prepared_common_body() if self.monitoring: self.query = "select * from system:prepareds" result = self.run_cbq_query() self.assertTrue(result['metrics']['resultCount'] == 1) def test_any_external(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'SELECT name FROM %s WHERE ' % query_bucket + \ 'ANY x IN ["Support", "Management"] SATISFIES job_title = x END ' + \ 'ORDER BY name' actual_result = self.run_cbq_query() expected_result = [{"name": doc['name']} for doc in self.full_list if doc["job_title"] in ["Support", "Management"]] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) def test_every(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name FROM %s d WHERE " % query_bucket + \ "(EVERY vm IN d.VMs SATISFIES CEIL(vm.memory) > 5 END) ORDER BY name" actual_result = self.run_cbq_query() expected_result = [{"name": doc['name']} for doc in self.full_list if len([vm for vm in doc["VMs"] if math.ceil(vm['memory']) > 5]) == len(doc["VMs"])] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) def test_satisfy_negative(self): queries_errors = {'SELECT name FROM %s WHERE ANY x IN 123 SATISFIES job_title = x END': ('syntax error', 3000), 'SELECT name FROM %s WHERE ANY x IN ["Sales"] SATISFIES job_title = x': ( 'syntax error', 3000), 'SELECT job_title FROM %s WHERE ANY job_title IN ["Sales"] SATISFIES job_title = job_title ' 'END': ( 'syntax error', 3000), 'SELECT job_title FROM %s WHERE EVERY ANY x IN ["Sales"] SATISFIES x = job_title END': ( 'syntax error', 3000)} self.negative_common_body(queries_errors) def test_check_is_isnot_negative(self): queries_errors = {'SELECT * FROM %s WHERE name is foo': ('syntax error', 3000), 'SELECT * FROM %s WHERE name is not foo': ('syntax error', 3000)} self.negative_common_body(queries_errors) def test_array(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT ARRAY vm.memory FOR vm IN VMs END AS vm_memories" + \ " FROM %s WHERE VMs IS NOT NULL " % query_bucket if self.analytics: self.query = 'SELECT (SELECT VALUE vm.memory FROM VMs AS vm) AS vm_memories FROM %s WHERE VMs IS NOT ' \ 'NULL ' % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['vm_memories'])) expected_result = [{"vm_memories": [vm["memory"] for vm in doc['VMs']]} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['vm_memories'])) self._verify_results(actual_result, expected_result) # This test is not used anywhere def test_array_objects(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT VMs[*].os from %s" % query_bucket actual_result = self.run_cbq_query() actual_result = actual_result['results'] expected_result = [{"os": [vm["os"] for vm in doc['VMs']]} for doc in self.full_list] self._verify_results(actual_result, expected_result) def test_arrays_negative(self): queries_errors = {'SELECT ARRAY vm.memory FOR vm IN 123 END AS vm_memories FROM %s': ('syntax error', 3000), 'SELECT job_title, array_agg(name)[:5] as names FROM %s': ('syntax error', 3000), 'SELECT job_title, array_agg(name)[-20:-5] as names FROM %s': ('syntax error', 3000), 'SELECT job_title, array_agg(name)[a:-b] as names FROM %s': ('syntax error', 3000)} self.negative_common_body(queries_errors) # This test is not used anywhere def test_slicing(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, array_agg(name)[0:5] as names" + \ " FROM %s GROUP BY job_title" % query_bucket actual_result = self.run_cbq_query() for item in actual_result['results']: self.log.info("Result: %s" % actual_result['results']) self.assertTrue(len(item['names']) <= 5, "Slicing doesn't work") self.query = "SELECT job_title, array_agg(name)[5:] as names" + \ " FROM %s GROUP BY job_title" % query_bucket actual_result = self.run_cbq_query() tmp_groups = {doc['job_title'] for doc in self.full_list} expected_list = [{"job_title": group, "names": [x["name"] for x in self.full_list if x["job_title"] == group]} for group in tmp_groups] expected_item = None for item in actual_result['results']: for tmp_item in expected_list: if item['job_title'] == tmp_item['job_title']: expected_item = tmp_item self.log.info("Result: %s" % actual_result['results']) self.assertTrue(len(item['names']) == len(expected_item['names']), "Slicing doesn't work") self.query = "SELECT job_title, array_agg(name)[5:10] as names" + \ " FROM %s GROUP BY job_title" % query_bucket actual_result = self.run_cbq_query() for item in actual_result['results']: self.log.info("Result: %s" % actual_result['results']) self.assertTrue(len(item['names']) <= 5, "Slicing doesn't work") def test_count_prepare(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "create index idx_cover on %s(join_mo,join_day) where join_mo > 7" % query_bucket self.run_cbq_query() self.query = "SELECT count(*) AS cnt from %s " % query_bucket + \ "WHERE join_mo > 7 and join_day > 1" self.prepared_common_body() def test_leak_goroutine(self): shell = RemoteMachineShellConnection(self.master) for i in range(20): cmd = 'curl http://%s:6060/debug/pprof/goroutine?debug=2 | grep NewLexer' % self.master.ip o = shell.execute_command(cmd) new_curl = json.dumps(o) string_curl = json.loads(new_curl) self.assertTrue("curl: (7) couldn't connect to host" == str(string_curl[1][1])) cmd = "curl http://%s:8093/query/service -d 'statement=select * from 1+2+3'" % self.master.ip o = shell.execute_command(cmd) new_curl = json.dumps(o) string_curl = json.loads(new_curl) self.assertTrue(len(string_curl) == 2) cmd = 'curl http://%s:6060/debug/pprof/goroutine?debug=2 | grep NewLexer' % self.master.ip o = shell.execute_command(cmd) new_curl = json.dumps(o) string_curl = json.loads(new_curl) self.assertTrue(len(string_curl) == 2) ############################################################################################## # # COUNT ############################################################################################## def test_fast_count(self): if self.index_to_be_created: if "EQUALS" in self.index_to_be_created: self.index_to_be_created = self.index_to_be_created.replace("EQUALS", "=") self.run_cbq_query(query=self.index_to_be_created) self.wait_for_all_indexes_online() try: if "STAR" in self.query_to_be_run: self.query_to_be_run = self.query_to_be_run.replace("STAR", "*") if "EQUALS" in self.query_to_be_run: self.query_to_be_run = self.query_to_be_run.replace("EQUALS", "=") # add use primary index hint to the query to compare the GSI query to the primary index query actual_results = self.run_cbq_query(query=self.query_to_be_run) split_query = self.query_to_be_run.split("where") primary_index_query = split_query[0] + "USE INDEX(`#primary`) where" + split_query[1] expected_results = self.run_cbq_query(query=primary_index_query) self.assertEqual(actual_results['results'][0]['$1'], expected_results['results'][0]['$1']) finally: if self.load_sample: query_bucket = self.get_collection_name('`travel-sample`') self.run_cbq_query(query="DROP INDEX idx_flight_stops ON {0}".format(query_bucket)) else: query_bucket = self.get_collection_name(self.default_bucket_name) self.run_cbq_query(query="DROP INDEX idx1 ON {0}".format(query_bucket)) def test_primary_count(self): # number of documents inserted at the beginning of suite_setup random_number = 23918 RemoteMachineShellConnection(self.master) if "STAR" in self.query_to_be_run: self.query_to_be_run = self.query_to_be_run.replace("STAR", "*") actual_results = self.run_cbq_query(query=self.query_to_be_run) self.assertEqual(actual_results['results'][0]['$1'], random_number + self.docs_per_day * 2016) ############################################################################################## # # LIKE ############################################################################################## def test_like(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name FROM {0} WHERE job_title LIKE 'S%' ORDER BY name".format(query_bucket) actual_result = self.run_cbq_query() expected_result = [{"name": doc['name']} for doc in self.full_list if doc["job_title"].startswith('S')] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) self.query = "SELECT name FROM {0} WHERE job_title LIKE '%u%' ORDER BY name".format(query_bucket) actual_result = self.run_cbq_query() expected_result = [{"name": doc['name']} for doc in self.full_list if doc["job_title"].find('u') != -1] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) self.query = "SELECT name FROM {0} WHERE job_title NOT LIKE 'S%' ORDER BY name".format(query_bucket) actual_result = self.run_cbq_query() expected_result = [{"name": doc['name']} for doc in self.full_list if not doc["job_title"].startswith('S')] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) self.query = "SELECT name FROM {0} WHERE job_title NOT LIKE '_ales' ORDER BY name".format(query_bucket) actual_result = self.run_cbq_query() expected_result = [{"name": doc['name']} for doc in self.full_list if not (doc["job_title"].endswith('ales') and len(doc["job_title"]) == 5)] self.query = "SELECT name FROM {0} WHERE reverse(job_title) NOT LIKE 'sela_' " \ "ORDER BY name".format(query_bucket) actual_result1 = self.run_cbq_query() self.assertEqual(actual_result1['results'], actual_result['results']) expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) def test_like_negative(self): queries_errors = {"SELECT tasks_points FROM {0} WHERE tasks_points.* LIKE '_1%'": ('syntax error', 3000)} self.negative_common_body(queries_errors) queries_errors = {"SELECT tasks_points FROM {0} WHERE REVERSE(tasks_points.*) LIKE '%1_'": ('syntax error', 3000)} self.negative_common_body(queries_errors) def test_like_any(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name, email FROM %s d WHERE (ANY vm IN d.VMs" % query_bucket + \ " SATISFIES vm.os LIKE '%bun%'" + \ "END) AND (ANY skill IN d.skills " + \ "SATISFIES skill = 'skill2010' END) ORDER BY name" actual_result = self.run_cbq_query() expected_result = [{"name": doc['name'], "email": doc["email"]} for doc in self.full_list if len([vm for vm in doc["VMs"] if vm["os"].find('bun') != -1]) > 0 and len([skill for skill in doc["skills"] if skill == 'skill2010']) > 0] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) def test_like_every(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name, email FROM %s d WHERE (EVERY vm IN d.VMs " % query_bucket + \ "SATISFIES vm.os NOT LIKE '%cent%' END)" + \ " AND (ANY skill IN d.skills SATISFIES skill =" + \ " 'skill2010' END) ORDER BY name" actual_result = self.run_cbq_query() expected_result = [{"name": doc['name'], "email": doc["email"]} for doc in self.full_list if len([vm for vm in doc["VMs"] if vm["os"].find('cent') == -1]) == len(doc["VMs"]) and len([skill for skill in doc["skills"] if skill == 'skill2010']) > 0] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) def test_like_aliases(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name AS NAME from %s " % query_bucket + \ "AS EMPLOYEE where EMPLOYEE.name LIKE '_mpl%' ORDER BY name" actual_result = self.run_cbq_query() self.query = "select name AS NAME from %s " % query_bucket + \ "AS EMPLOYEE where reverse(EMPLOYEE.name) LIKE '%lpm_' ORDER BY name" actual_result1 = self.run_cbq_query() self.assertEqual(actual_result['results'], actual_result1['results']) expected_result = [{"NAME": doc['name']} for doc in self.full_list if doc["name"].find('mpl') == 1] expected_result = sorted(expected_result, key=lambda doc: (doc['NAME'])) self._verify_results(actual_result['results'], expected_result) def test_like_wildcards(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT email FROM %s WHERE email " % query_bucket + \ "LIKE '%@%.%' ORDER BY email" actual_result = self.run_cbq_query() self.query = "SELECT email FROM %s WHERE reverse(email) " % query_bucket + \ "LIKE '%.%@%' ORDER BY email" actual_result1 = self.run_cbq_query() self.assertEqual(actual_result['results'], actual_result1['results']) expected_result = [{"email": doc['email']} for doc in self.full_list if re.match(r'.*@.*\..*', doc['email'])] expected_result = sorted(expected_result, key=lambda doc: (doc['email'])) self._verify_results(actual_result['results'], expected_result) self.query = "SELECT email FROM %s WHERE email" % query_bucket + \ " LIKE '%@%.h' ORDER BY email" actual_result = self.run_cbq_query() expected_result = [] self._verify_results(actual_result['results'], expected_result) def test_prepared_like_wildcards(self): self.fail_if_no_buckets() if self.monitoring: self.query = "select * from system:prepareds" result = self.run_cbq_query() self.assertTrue(result['metrics']['resultCount'] == 0) for query_bucket in self.query_buckets: self.query = "SELECT email FROM %s WHERE email " % query_bucket + \ "LIKE '%@%.%' ORDER BY email" self.prepared_common_body() if self.monitoring: self.query = "select * from system:prepareds" result = self.run_cbq_query() self.assertTrue(result['metrics']['resultCount'] == 1) def test_between(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name FROM {0} WHERE join_mo BETWEEN 1 AND 6 ORDER BY name".format(query_bucket) actual_result = self.run_cbq_query() expected_result = [{"name": doc['name']} for doc in self.full_list if 1 <= doc["join_mo"] <= 6] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) self.query = "SELECT name FROM {0} WHERE join_mo NOT BETWEEN 1 AND 6 ORDER BY name".format(query_bucket) actual_result = self.run_cbq_query() expected_result = [{"name": doc['name']} for doc in self.full_list if not 1 <= doc["join_mo"] <= 6] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) def test_between_negative(self): queries_errors = {'SELECT name FROM %s WHERE join_mo BETWEEN 1 AND -10 ORDER BY name': ('syntax error', 3000), 'SELECT name FROM %s WHERE join_mo BETWEEN 1 AND a ORDER BY name': ('syntax error', 3000)} self.negative_common_body(queries_errors) ############################################################################################## # # GROUP BY ############################################################################################## def test_group_by(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT tasks_points.task1 AS task from %s " % query_bucket + \ "WHERE join_mo>7 GROUP BY tasks_points.task1 " + \ "ORDER BY tasks_points.task1" if self.analytics: self.query = "SELECT d.tasks_points.task1 AS task from %s d " % query_bucket + \ "WHERE d.join_mo>7 GROUP BY d.tasks_points.task1 " + \ "ORDER BY d.tasks_points.task1" actual_result = self.run_cbq_query() expected_result = [{"task": doc['tasks_points']["task1"]} for doc in self.full_list if doc["join_mo"] > 7] expected_result = [dict(y) for y in set(tuple(x.items()) for x in expected_result)] expected_result = sorted(expected_result, key=lambda doc: (doc['task'])) self._verify_results(actual_result['results'], expected_result) def test_group_by_having(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "from %s WHERE join_mo>7 GROUP BY tasks_points.task1 " % query_bucket + \ "HAVING COUNT(tasks_points.task1) > 0 SELECT tasks_points.task1 " + \ "AS task ORDER BY tasks_points.task1" actual_result = self.run_cbq_query() expected_result = [{"task": doc['tasks_points']["task1"]} for doc in self.full_list if doc["join_mo"] > 7] expected_result = [doc for doc in expected_result if expected_result.count(doc) > 0] expected_result = [dict(y) for y in set(tuple(x.items()) for x in expected_result)] expected_result = sorted(expected_result, key=lambda doc: (doc['task'])) self._verify_results(actual_result['results'], expected_result) def test_group_by_aggr_fn(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT tasks_points.task1 AS task from %s " % query_bucket + \ "WHERE join_mo>7 GROUP BY tasks_points.task1 " + \ "HAVING COUNT(tasks_points.task1) > 0 AND " + \ "(MIN(join_day)=1 OR MAX(join_yr=2011)) " + \ "ORDER BY tasks_points.task1" actual_result = self.run_cbq_query() if self.analytics: self.query = "SELECT d.tasks_points.task1 AS task from %s d " % query_bucket + \ "WHERE d.join_mo>7 GROUP BY d.tasks_points.task1 " + \ "HAVING COUNT(d.tasks_points.task1) > 0 AND " + \ "(MIN(d.join_day)=1 OR MAX(d.join_yr=2011)) " + \ "ORDER BY d.tasks_points.task1" tmp_groups = {doc['tasks_points']["task1"] for doc in self.full_list} expected_result = [{"task": group} for group in tmp_groups if [doc['tasks_points']["task1"] for doc in self.full_list].count(group) > 0 and (min([doc["join_day"] for doc in self.full_list if doc['tasks_points']["task1"] == group]) == 1 or max([doc["join_yr"] for doc in self.full_list if doc['tasks_points']["task1"] == group]) == 2011)] expected_result = sorted(expected_result, key=lambda doc: (doc['task'])) self._verify_results(actual_result['results'], expected_result) def test_prepared_group_by_aggr_fn(self): self.fail_if_no_buckets() if self.monitoring: self.query = "select * from system:prepareds" result = self.run_cbq_query() self.assertTrue(result['metrics']['resultCount'] == 0) for query_bucket in self.query_buckets: self.query = "SELECT tasks_points.task1 AS task from %s " % query_bucket + \ "WHERE join_mo>7 GROUP BY tasks_points.task1 " + \ "HAVING COUNT(tasks_points.task1) > 0 AND " + \ "(MIN(join_day)=1 OR MAX(join_yr=2011)) " + \ "ORDER BY tasks_points.task1" self.prepared_common_body() if self.monitoring: self.query = "select * from system:prepareds" result = self.run_cbq_query() self.assertTrue(result['metrics']['resultCount'] == 1) self.query = "delete from system:prepareds" self.run_cbq_query() self.query = "select * from system:prepareds" result = self.run_cbq_query() self.assertTrue(result['metrics']['resultCount'] == 0) def test_group_by_satisfy(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, AVG(test_rate) as avg_rate FROM %s d " % query_bucket + \ "WHERE (ANY skill IN d.skills SATISFIES skill = 'skill2010' end) " + \ "AND (ANY vm IN d.VMs SATISFIES vm.RAM = 5 end) " + \ "GROUP BY job_title ORDER BY job_title" if self.analytics: self.query = "SELECT d.job_title, AVG(d.test_rate) as avg_rate FROM %s d " % query_bucket + \ "WHERE (ANY skill IN d.skills SATISFIES skill = 'skill2010' end) " + \ "AND (ANY vm IN d.VMs SATISFIES vm.RAM = 5 end) " + \ "GROUP BY d.job_title ORDER BY d.job_title" actual_result = self.run_cbq_query() tmp_groups = {doc["job_title"] for doc in self.full_list} expected_result = [{"job_title": doc['job_title'], "test_rate": doc["test_rate"]} for doc in self.full_list if 'skill2010' in doc["skills"] and len([vm for vm in doc["VMs"] if vm["RAM"] == 5]) > 0] expected_result = [{"job_title": group, "avg_rate": math.fsum([doc["test_rate"] for doc in expected_result if doc["job_title"] == group]) / len([doc["test_rate"] for doc in expected_result if doc["job_title"] == group])} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result['results'], expected_result) def test_group_by_negative(self): queries_errors = {"SELECT tasks_points from {0} WHERE tasks_points.task2>3" + " GROUP BY tasks_points.*": ('syntax error', 3000), "from {0} WHERE join_mo>7 GROUP BY tasks_points.task1 " + "SELECT tasks_points.task1 AS task HAVING COUNT(tasks_points.task1) > 0": ('syntax error', 3000)} self.negative_common_body(queries_errors) # This test has no usages anywhere def test_groupby_first(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select job_title, (FIRST p FOR p IN ARRAY_AGG(name) END) as names from {0} group by " \ "job_title order by job_title ".format(query_bucket) actual_result = self.run_cbq_query() tmp_groups = {doc['job_title'] for doc in self.full_list} expected_list = [{"job_title": group, "names": ([x["name"] for x in self.full_list if x["job_title"] == group][0])} for group in tmp_groups] expected_result = self.sort_nested_list(expected_list) expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self.assertTrue(actual_result['results'] == expected_result) ############################################################################################## # # SCALAR FN ############################################################################################## def test_ceil(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name, ceil(test_rate) as rate from %s" % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['name'], doc['rate'])) expected_result = [{"name": doc['name'], "rate": math.ceil(doc['test_rate'])} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['name'], doc['rate'])) self._verify_results(actual_result, expected_result) self.query = "select name from %s where ceil(test_rate) > 5" % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['name'])) expected_result = [{"name": doc['name']} for doc in self.full_list if math.ceil(doc['test_rate']) > 5] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result, expected_result) def test_floor(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name, floor(test_rate) as rate from %s" % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['name'], doc['rate'])) expected_result = [{"name": doc['name'], "rate": math.floor(doc['test_rate'])} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['name'], doc['rate'])) self._verify_results(actual_result, expected_result) self.query = "select name from %s where floor(test_rate) > 5" % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['name'])) expected_result = [{"name": doc['name']} for doc in self.full_list if math.floor(doc['test_rate']) > 5] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result, expected_result) self.query = "select name from %s where floor(job_title) > 5" % query_bucket actual_result = self.run_cbq_query() self._verify_results(actual_result['results'], []) def test_greatest(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name, GREATEST(skills[0], skills[1]) as SKILL from %s" % ( query_bucket) actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['name'], doc['SKILL'])) expected_result = [{"name": doc['name'], "SKILL": (doc['skills'][0], doc['skills'][1])[doc['skills'][0] < doc['skills'][1]]} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['name'], doc['SKILL'])) self._verify_results(actual_result, expected_result) def test_least(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name, LEAST(skills[0], skills[1]) as SKILL from %s" % ( query_bucket) actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['name'], doc['SKILL'])) expected_result = [{"name": doc['name'], "SKILL": (doc['skills'][0], doc['skills'][1])[doc['skills'][0] > doc['skills'][1]]} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['name'], doc['SKILL'])) self._verify_results(actual_result, expected_result) def test_meta(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'SELECT distinct name FROM %s d WHERE META(d).`type` = "json"' % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['name'])) expected_result = [{"name": doc['name']} for doc in self.full_list] expected_result = [dict(y) for y in set(tuple(x.items()) for x in expected_result)] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result, expected_result) self.query = "SELECT distinct name FROM %s WHERE META().id IS NOT NULL" % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['name'])) self._verify_results(actual_result, expected_result) def test_meta_like(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'SELECT name FROM %s d WHERE META(d).id LIKE "%s"' % (query_bucket, "query%") actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['name'])) expected_result = [{"name": doc['name']} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result, expected_result) def test_prepared_meta_like(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'SELECT name FROM %s d WHERE META(d).id ' % query_bucket + 'LIKE "employee%"' self.prepared_common_body() if self.monitoring: self.query = 'select * from system:completed_requests' result = self.run_cbq_query() request_id = result['request_id'] self.query = 'delete from system:completed_requests where request_id = "%s"' % request_id self.run_cbq_query() result = self.run_cbq_query( 'select * from system:completed_requests where request_id = "%s"' % request_id) self.assertTrue(result['metrics']['resultCount'] == 0) def test_meta_flags(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'SELECT DISTINCT META().flags as flags FROM %s' % query_bucket actual_result = self.run_cbq_query() expected_result = [{"flags": self.item_flag}] self._verify_results(actual_result['results'], expected_result) def test_long_values(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'insert into %s values("k051", { "id":-9223372036854775808 } )' % query_bucket self.run_cbq_query() self.query = 'insert into %s values("k031", { "id":-9223372036854775807 } )' % query_bucket self.run_cbq_query() self.query = 'insert into %s values("k021", { "id":1470691191458562048 } )' % query_bucket self.run_cbq_query() self.query = 'insert into %s values("k011", { "id":9223372036854775807 } )' % query_bucket self.run_cbq_query() self.query = 'insert into %s values("k041", { "id":9223372036854775808 } )' % query_bucket self.run_cbq_query() self.query = 'select * from ' + query_bucket + ' d where meta().id = "{0}"'.format("k051") actual_result = self.run_cbq_query() print("k051 results is {0}".format(actual_result['results'][0]['d'])) # self.assertEqual(actual_result['results'][0]["default"],{'id': -9223372036854775808}) self.query = 'select * from ' + query_bucket + ' d where meta().id = "{0}"'.format("k031") actual_result = self.run_cbq_query() print("k031 results is {0}".format(actual_result['results'][0]['d'])) # self.assertEqual(actual_result['results'][0]["default"],{'id': -9223372036854775807}) self.query = 'select * from ' + query_bucket + ' d where meta().id = "{0}"'.format("k021") actual_result = self.run_cbq_query() print("k021 results is {0}".format(actual_result['results'][0]['d'])) # self.assertEqual(actual_result['results'][0]["default"],{'id': 1470691191458562048}) self.query = 'select * from ' + query_bucket + ' d where meta().id = "{0}"'.format("k011") actual_result = self.run_cbq_query() print("k011 results is {0}".format(actual_result['results'][0]['d'])) # self.assertEqual(actual_result['results'][0]["default"],{'id': 9223372036854775807}) self.query = 'select * from ' + query_bucket + ' d where meta().id = "{0}"'.format("k041") actual_result = self.run_cbq_query() print("k041 results is {0}".format(actual_result['results'][0]['d'])) # self.assertEqual(actual_result['results'][0]["default"],{'id': 9223372036854776000L}) self.query = 'delete from ' + query_bucket + ' where meta().id in ["k051","k021","k011","k041","k031"]' self.run_cbq_query() def test_meta_cas(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'select meta().cas from {0} order by meta().id limit 10'.format(query_bucket) actual_result = self.run_cbq_query() print(actual_result) def test_meta_negative(self): queries_errors = {'SELECT distinct name FROM %s WHERE META().type = "json"': ('syntax error', 3000)} self.negative_common_body(queries_errors) def test_length(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'Select name, email from %s where LENGTH(job_title) = 5' % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['name'])) expected_result = [{"name": doc['name'], "email": doc['email']} for doc in self.full_list if len(doc['job_title']) == 5] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result, expected_result) def test_upper(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'SELECT DISTINCT UPPER(job_title) as JOB from %s' % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['JOB'])) expected_result = [{"JOB": doc['job_title'].upper()} for doc in self.full_list] expected_result = [dict(y) for y in set(tuple(x.items()) for x in expected_result)] expected_result = sorted(expected_result, key=lambda doc: (doc['JOB'])) self._verify_results(actual_result, expected_result) def test_lower(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT distinct email from %s" % query_bucket + \ " WHERE LOWER(job_title) < 't'" actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['email'])) expected_result = [{"email": doc['email'].lower()} for doc in self.full_list if doc['job_title'].lower() < 't'] expected_result = [dict(y) for y in set(tuple(x.items()) for x in expected_result)] expected_result = sorted(expected_result, key=lambda doc: (doc['email'])) self._verify_results(actual_result, expected_result) def test_round(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name, round(test_rate) as rate from %s" % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['name'], doc['rate'])) expected_result = [{"name": doc["name"], "rate": round(doc['test_rate'])} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['name'], doc['rate'])) self._verify_results(actual_result, expected_result) def test_trunc(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name, TRUNC(test_rate, 0) as rate from %s" % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['name'], doc['rate'])) expected_result = [{"name": doc["name"], "rate": math.trunc(doc['test_rate'])} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['name'], doc['rate'])) self._verify_results(actual_result, expected_result) def test_first(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name, FIRST vm.os for vm in VMs end as OS from %s" % ( query_bucket) if self.analytics: self.query = "select name, VMs[0].os as OS from %s" % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['name'], doc['OS'])) expected_result = [{"name": doc["name"], "OS": doc['VMs'][0]["os"]} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['name'], doc['OS'])) self._verify_results(actual_result, expected_result) ############################################################################################## # # Substring ############################################################################################## def test_substr(self): self.fail_if_no_buckets() indices_to_test = [-100, -2, -1, 0, 1, 2, 100] for index in indices_to_test: for query_bucket in self.query_buckets: self.query = "select name, SUBSTR(email, %s) as DOMAIN from %s" % ( str(index), query_bucket) query_result = self.run_cbq_query() query_docs = query_result['results'] sorted_query_docs = sorted(query_docs, key=lambda doc: (doc['name'], doc['DOMAIN'])) expected_result = [{"name": doc["name"], "DOMAIN": self.expected_substr(doc['email'], 0, index)} for doc in self.full_list] sorted_expected_result = sorted(expected_result, key=lambda doc: ( doc['name'], doc['DOMAIN'])) self._verify_results(sorted_query_docs, sorted_expected_result) def test_substr0(self): self.fail_if_no_buckets() indices_to_test = [-100, -2, -1, 0, 1, 2, 100] for index in indices_to_test: for query_bucket in self.query_buckets: self.query = "select name, SUBSTR0(email, %s) as DOMAIN from %s" % ( str(index), query_bucket) query_result = self.run_cbq_query() query_docs = query_result['results'] sorted_query_docs = sorted(query_docs, key=lambda doc: (doc['name'], doc['DOMAIN'])) expected_result = [{"name": doc["name"], "DOMAIN": self.expected_substr(doc['email'], 0, index)} for doc in self.full_list] sorted_expected_result = sorted(expected_result, key=lambda doc: ( doc['name'], doc['DOMAIN'])) self._verify_results(sorted_query_docs, sorted_expected_result) def test_substr1(self): self.fail_if_no_buckets() indices_to_test = [-100, -2, -1, 0, 1, 2, 100] for index in indices_to_test: for query_bucket in self.query_buckets: self.query = "select name, SUBSTR1(email, %s) as DOMAIN from %s" % ( str(index), query_bucket) query_result = self.run_cbq_query() query_docs = query_result['results'] sorted_query_docs = sorted(query_docs, key=lambda doc: (doc['name'], doc['DOMAIN'])) expected_result = [{"name": doc["name"], "DOMAIN": self.expected_substr(doc['email'], 1, index)} for doc in self.full_list] sorted_expected_result = sorted(expected_result, key=lambda doc: ( doc['name'], doc['DOMAIN'])) self._verify_results(sorted_query_docs, sorted_expected_result) ############################################################################################## # # AGGR FN ############################################################################################## def test_agg_counters(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: vals = [] keys = [] for i in range(10): new_val = random.randint(0, 99) new_counter = "counter_US" + str(i) vals.append(new_val) keys.append(new_counter) self.query = 'INSERT INTO %s VALUES ("%s",%s)' % (query_bucket, new_counter, new_val) self.run_cbq_query() self.query = 'SELECT sum(d) FROM %s d USE KEYS %s;' % (query_bucket, str(keys)) actual_results = self.run_cbq_query() self.assertEqual(actual_results['results'][0]['$1'], sum(vals)) self.query = 'SELECT avg(d) FROM %s d USE KEYS %s;' % (query_bucket, str(keys)) actual_results = self.run_cbq_query() self.assertEqual(actual_results['results'][0]['$1'], float(sum(vals)) / max(len(vals), 1)) self.query = 'DELETE FROM %s USE KEYS %s;' % (query_bucket, str(keys)) actual_results = self.run_cbq_query() self.assertEqual(actual_results['results'], []) def test_sum(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT join_mo, SUM(tasks_points.task1) as points_sum" + \ " FROM %s WHERE join_mo < 5 GROUP BY join_mo " % query_bucket + \ "ORDER BY join_mo" if self.analytics: self.query = "SELECT d.join_mo, SUM(d.tasks_points.task1) as points_sum" + \ " FROM %s d WHERE d.join_mo < 5 GROUP BY d.join_mo " % query_bucket + \ "ORDER BY d.join_mo" actual_result = self.run_cbq_query() tmp_groups = {doc['join_mo'] for doc in self.full_list if doc['join_mo'] < 5} expected_result = [{"join_mo": group, "points_sum": int(math.fsum([doc['tasks_points']['task1'] for doc in self.full_list if doc['join_mo'] == group]))} for group in tmp_groups] self._verify_results(actual_result['results'], expected_result) self.query = "SELECT join_mo, SUM(test_rate) as rate FROM %s " % query_bucket + \ "as employees WHERE job_title='Sales' GROUP BY join_mo " + \ "HAVING SUM(employees.test_rate) > 0 and " + \ "SUM(test_rate) < 100000" if self.analytics: self.query = "SELECT d.join_mo, SUM(d.test_rate) as rate FROM %s d " % query_bucket + \ " WHERE d.job_title='Sales' GROUP BY d.join_mo " + \ "HAVING SUM(d.test_rate) > 0 and " + \ "SUM(d.test_rate) < 100000" actual_result = self.run_cbq_query() actual_result = [{"join_mo": doc["join_mo"], "rate": round(doc["rate"])} for doc in actual_result['results']] actual_result = sorted(actual_result, key=lambda doc: (doc['join_mo'])) tmp_groups = {doc['join_mo'] for doc in self.full_list} expected_result = [{"join_mo": group, "rate": round(math.fsum([doc['test_rate'] for doc in self.full_list if doc['join_mo'] == group and doc['job_title'] == 'Sales']))} for group in tmp_groups if math.fsum([doc['test_rate'] for doc in self.full_list if doc['join_mo'] == group and doc['job_title'] == 'Sales']) > 0 and math.fsum([doc['test_rate'] for doc in self.full_list if doc['join_mo'] == group and doc['job_title'] == 'Sales']) < 100000] expected_result = sorted(expected_result, key=lambda doc: (doc['join_mo'])) self._verify_results(actual_result, expected_result) def test_prepared_sum(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT join_mo, SUM(tasks_points.task1) as points_sum" + \ " FROM %s WHERE join_mo < 5 GROUP BY join_mo " % query_bucket + \ "ORDER BY join_mo" self.prepared_common_body() def test_sum_negative(self): queries_errors = {'SELECT join_mo, SUM(job_title) as rate FROM %s as employees' + ' WHERE job_title="Sales" GROUP BY join_mo': ('syntax error', 3000), 'SELECT join_mo, SUM(VMs) as rate FROM %s as employees' + ' WHERE job_title="Sales" GROUP BY join_mo': ('syntax error', 3000)} self.negative_common_body(queries_errors) def test_avg(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT join_mo, AVG(tasks_points.task1) as points_avg" + \ " FROM %s WHERE join_mo < 5 GROUP BY join_mo " % query_bucket + \ "ORDER BY join_mo" if self.analytics: self.query = "SELECT d.join_mo, AVG(d.tasks_points.task1) as points_avg" + \ " FROM %s d WHERE d.join_mo < 5 GROUP BY d.join_mo " % query_bucket + \ "ORDER BY d.join_mo" actual_result = self.run_cbq_query() tmp_groups = {doc['join_mo'] for doc in self.full_list if doc['join_mo'] < 5} expected_result = [{"join_mo": group, "points_avg": math.fsum([doc['tasks_points']['task1'] for doc in self.full_list if doc['join_mo'] == group]) / len([doc['tasks_points']['task1'] for doc in self.full_list if doc['join_mo'] == group])} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['join_mo'])) self._verify_results(actual_result['results'], expected_result) self.query = "SELECT join_mo, AVG(test_rate) as rate FROM %s " % query_bucket + \ "as employees WHERE job_title='Sales' GROUP BY join_mo " + \ "HAVING AVG(employees.test_rate) > 0 and " + \ "SUM(test_rate) < 100000" if self.analytics: self.query = "SELECT d.join_mo, AVG(d.test_rate) as rate FROM %s d" % query_bucket + \ " WHERE d.job_title='Sales' GROUP BY d.join_mo " + \ "HAVING AVG(d.test_rate) > 0 and " + \ "SUM(d.test_rate) < 100000" actual_result = self.run_cbq_query() actual_result = [{'join_mo': doc['join_mo'], 'rate': round(doc['rate'], 2)} for doc in actual_result['results']] actual_result = sorted(actual_result, key=lambda doc: (doc['join_mo'])) tmp_groups = {doc['join_mo'] for doc in self.full_list} expected_result = [{"join_mo": group, "rate": math.fsum([doc['test_rate'] for doc in self.full_list if doc['join_mo'] == group and doc['job_title'] == 'Sales']) / len([doc['test_rate'] for doc in self.full_list if doc['join_mo'] == group and doc['job_title'] == 'Sales'])} for group in tmp_groups if (math.fsum([doc['test_rate'] for doc in self.full_list if doc['join_mo'] == group and doc['job_title'] == 'Sales']) / len([doc['test_rate'] for doc in self.full_list if doc['join_mo'] == group and doc['job_title'] == 'Sales']) > 0) and math.fsum([doc['test_rate'] for doc in self.full_list if doc['join_mo'] == group and doc['job_title'] == 'Sales']) < 100000] expected_result = [{'join_mo': doc['join_mo'], 'rate': round(doc['rate'], 2)} for doc in expected_result] expected_result = sorted(expected_result, key=lambda doc: (doc['join_mo'])) self._verify_results(actual_result, expected_result) def test_min(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: query_bucket = self.get_collection_name(query_bucket) self.query = "SELECT join_mo, MIN(test_rate) as rate FROM %s " % query_bucket + \ "as employees WHERE job_title='Sales' GROUP BY join_mo " + \ "HAVING MIN(employees.test_rate) > 0 and " + \ "SUM(test_rate) < 100000" actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['join_mo'])) tmp_groups = {doc['join_mo'] for doc in self.full_list} expected_result = [{"join_mo": group, "rate": min([doc['test_rate'] for doc in self.full_list if doc['join_mo'] == group and doc['job_title'] == 'Sales'])} for group in tmp_groups if min([doc['test_rate'] for doc in self.full_list if doc['join_mo'] == group and doc['job_title'] == 'Sales']) > 0 and math.fsum([doc['test_rate'] for doc in self.full_list if doc['join_mo'] == group and doc['job_title'] == 'Sales']) < 100000] expected_result = sorted(expected_result, key=lambda doc: (doc['join_mo'])) self._verify_results(actual_result, expected_result) def test_max(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT join_mo, MAX(test_rate) as rate FROM %s " % query_bucket + \ "as employees WHERE job_title='Sales' GROUP BY join_mo " + \ "HAVING MAX(employees.test_rate) > 0 and " + \ "SUM(test_rate) < 100000" actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['join_mo'])) tmp_groups = {doc['join_mo'] for doc in self.full_list} expected_result = [{"join_mo": group, "rate": max([doc['test_rate'] for doc in self.full_list if doc['join_mo'] == group and doc['job_title'] == 'Sales'])} for group in tmp_groups if max([doc['test_rate'] for doc in self.full_list if doc['join_mo'] == group and doc['job_title'] == 'Sales']) > 0 and math.fsum([doc['test_rate'] for doc in self.full_list if doc['join_mo'] == group and doc['job_title'] == 'Sales']) < 100000] expected_result = sorted(expected_result, key=lambda doc: (doc['join_mo'])) self._verify_results(actual_result, expected_result) def test_array_agg_distinct(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, array_agg(DISTINCT name) as names" + \ " FROM %s GROUP BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = self.sort_nested_list(actual_list['results']) actual_result = sorted(actual_result, key=lambda doc: (doc['job_title'])) tmp_groups = {doc['job_title'] for doc in self.full_list} expected_list = [{"job_title": group, "names": {x["name"] for x in self.full_list if x["job_title"] == group}} for group in tmp_groups] expected_result = self.sort_nested_list(expected_list) expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result, expected_result) def test_array_length(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, array_length(array_agg(DISTINCT name)) as num_names" + \ " FROM %s GROUP BY job_title" % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['job_title'])) tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "num_names": len({x["name"] for x in self.full_list if x["job_title"] == group})} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result, expected_result) self.query = "SELECT job_title, array_length(array_agg(DISTINCT test_rate)) as rates" + \ " FROM %s GROUP BY job_title" % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['job_title'])) expected_result = [{"job_title": group, "rates": len({x["test_rate"] for x in self.full_list if x["job_title"] == group})} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result, expected_result) def test_array_append(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: query_bucket = self.get_collection_name(query_bucket) self.query = "SELECT job_title," + \ " array_append(array_agg(DISTINCT name), 'new_name') as names" + \ " FROM %s GROUP BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = self.sort_nested_list(actual_list['results']) actual_result = sorted(actual_result, key=lambda doc: (doc['job_title'])) tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "names": sorted(set([x["name"] for x in self.full_list if x["job_title"] == group] + ['new_name']))} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result, expected_result) self.query = "SELECT job_title," + \ " array_append(array_agg(DISTINCT name), 'new_name','123') as names" + \ " FROM %s GROUP BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = self.sort_nested_list(actual_list['results']) actual_result = sorted(actual_result, key=lambda doc: (doc['job_title'])) tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "names": sorted(set([x["name"] for x in self.full_list if x["job_title"] == group] + ['new_name'] + ['123']))} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result, expected_result) def test_prepared_array_append(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title," + \ " array_append(array_agg(DISTINCT name), 'new_name') as names" + \ " FROM %s GROUP BY job_title" % query_bucket self.prepared_common_body() def test_array_union_symdiff(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'select ARRAY_SORT(ARRAY_UNION(["skill1","skill2","skill2010","skill2011"],skills)) as ' \ 'skills_union from {0} order by meta().id limit 5'.format(query_bucket) actual_result = self.run_cbq_query() expected_result = [{'skills_union': ['skill1', 'skill2', 'skill2010', 'skill2011']}, {'skills_union': ['skill1', 'skill2', 'skill2010', 'skill2011']}, {'skills_union': ['skill1', 'skill2', 'skill2010', 'skill2011']}, {'skills_union': ['skill1', 'skill2', 'skill2010', 'skill2011']}, {'skills_union': ['skill1', 'skill2', 'skill2010', 'skill2011']}] self.assertTrue(actual_result['results'] == expected_result, f"{actual_result['results']} not matching with {expected_result}") self.query = 'select ARRAY_SORT(ARRAY_SYMDIFF(["skill1","skill2","skill2010","skill2011"],skills)) as ' \ 'skills_diff1 from {0} order by meta().id limit 5'.format(query_bucket) actual_result = self.run_cbq_query() self.assertTrue(actual_result['results'] == [{'skills_diff1': ['skill1', 'skill2']}, {'skills_diff1': ['skill1', 'skill2']}, {'skills_diff1': ['skill1', 'skill2']}, {'skills_diff1': ['skill1', 'skill2']}, {'skills_diff1': ['skill1', 'skill2']}]) self.query = 'select ARRAY_SORT(ARRAY_SYMDIFF1(skills,["skill2010","skill2011","skill2012"],' \ '["skills2010","skill2017"])) as skills_diff2 from {0} order by ' \ 'meta().id limit 5'.format(query_bucket) actual_result1 = self.run_cbq_query() self.assertTrue( actual_result1['results'] == [{'skills_diff2': ['skill2012', 'skill2017', 'skills2010']}, {'skills_diff2': ['skill2012', 'skill2017', 'skills2010']}, {'skills_diff2': ['skill2012', 'skill2017', 'skills2010']}, {'skills_diff2': ['skill2012', 'skill2017', 'skills2010']}, {'skills_diff2': ['skill2012', 'skill2017', 'skills2010']}]) self.query = 'select ARRAY_SORT(ARRAY_SYMDIFFN(skills,["skill2010","skill2011","skill2012"],' \ '["skills2010","skill2017"])) as skills_diff3 from {0} order by ' \ 'meta().id limit 5'.format(query_bucket) actual_result = self.run_cbq_query() self.assertTrue(actual_result['results'] == [{'skills_diff3': ['skill2012', 'skill2017', 'skills2010']}, {'skills_diff3': ['skill2012', 'skill2017', 'skills2010']}, {'skills_diff3': ['skill2012', 'skill2017', 'skills2010']}, {'skills_diff3': ['skill2012', 'skill2017', 'skills2010']}, {'skills_diff3': ['skill2012', 'skill2017', 'skills2010']}]) def test_let(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'select * from %s let x1 = {"name":1} order by meta().id limit 1' % query_bucket actual_result = self.run_cbq_query() if "query-testemployee10153.1877827" not in str(actual_result['results']): self.assertTrue(False, str(actual_result['results'])) self.assertTrue("'x1': {'name': 1}" in str(actual_result['results'])) def test_let_missing(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: created_indexes = [] try: self.query = 'CREATE INDEX ix1 on %s(x1)' % query_bucket self.run_cbq_query() created_indexes.append("ix1") self.query = 'INSERT INTO %s VALUES ("k01",{"x1":5, "type":"doc", "x2": "abc"}), ' \ '("k02",{"x1":5, "type":"d", "x2": "def"})' % query_bucket self.run_cbq_query() self.query = 'EXPLAIN SELECT x1, x2 FROM %s o LET o = CASE WHEN o.type = "doc" THEN o ELSE MISSING ' \ 'END WHERE x1 = 5' % query_bucket try: self.run_cbq_query(self.query) except CBQError as ex: self.assertTrue(str(ex).find("Duplicate variable o (near line 1, column 57) already in scope.") != -1 or str(ex).find("Duplicate variable o (near line 1, column 66) already in scope.") != -1, "Error is incorrect.") else: self.fail("There was no errors.") self.query = 'delete from %s use keys["k01","k02"]' % query_bucket self.run_cbq_query() finally: for idx in created_indexes: self.query = "DROP INDEX %s ON %s USING %s" % (idx, query_bucket, self.index_type) self.run_cbq_query() def test_optimized_let(self): self.fail_if_no_buckets() self.query = 'explain select name1 from ' + self.query_buckets[ 0] + ' d let name1 = substr(name[0].FirstName,0,10) WHERE name1 = "employeefi"' res = self.run_cbq_query() plan = self.ExplainPlanHelper(res) for operator in plan['~children'][2]['~child']['~children']: if operator['#operator'] == 'Filter': self.assertTrue(operator['condition'] == '(`name1` = "employeefi")' or operator['condition'] == '(substr0((((`d`.`name`)[0]).`FirstName`), 0, 10) = "employeefi")') if operator['#operator'] == 'Let': self.assertEqual(operator['bindings'], [{'expr': 'substr0((((`d`.`name`)[0]).`FirstName`), 0, 10)', 'var': 'name1'}]) if operator['#operator'] == 'InitialProject': self.assertEqual(operator['result_terms'], [{'expr': '`name1`'}]) self.query = 'select name1 from ' + self.query_buckets[ 0] + ' d let name1 = substr(name[0].FirstName,0,10) WHERE name1 = "employeefi" limit 2' res = self.run_cbq_query() self.assertEqual(res['results'], [{'name1': 'employeefi'}, {'name1': 'employeefi'}]) self.query = 'explain select name1 from ' + self.query_buckets[ 0] + ' d let name1 = substr(name[0].FirstName,0,10) WHERE name[0].MiddleName = "employeefirstname-4"' res = self.run_cbq_query() plan = self.ExplainPlanHelper(res) self.assertEqual(plan['~children'][2]['~child']['~children'], [{'#operator': 'Filter', 'condition': '((((`d`.`name`)[0]).`MiddleName`) = "employeefirstname-4")'}, {'#operator': 'Let', 'bindings': [ {'var': 'name1', 'expr': 'substr0((((`d`.`name`)[0]).`FirstName`), 0, 10)'}]}, {'#operator': 'InitialProject', 'result_terms': [{'expr': '`name1`'}]}]) self.query = 'select name1 from ' + self.query_buckets[0] + \ ' let name1 = substr(name[0].FirstName,0,10) WHERE name[0].MiddleName = "employeefirstname-4" ' \ 'limit 10 ' res = self.run_cbq_query() self.assertTrue(res['results'] == []) def test_correlated_queries(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: if query_bucket == self.default_bucket_name: try: self.query = 'create index ix1 on %s(x,id)' % query_bucket self.run_cbq_query() self.query = 'insert into %s (KEY, VALUE) VALUES ' \ '("kk02",{"x":100,"y":101,"z":102,"id":"kk02"})' % query_bucket self.run_cbq_query() self.query = 'explain select d.x from {0} d where x in (select raw d.x from {0} b ' \ 'use keys ["kk02"])'.format(query_bucket) actual_result = self.run_cbq_query() plan = self.ExplainPlanHelper(actual_result) self.assertTrue("covers" in str(plan)) self.assertTrue(plan['~children'][0]['index'] == 'ix1') self.query = 'select d.x from {0} d where x in (select raw d.x from {0} b ' \ 'use keys ["kk02"])'.format(query_bucket) actual_result = self.run_cbq_query() self.assertTrue(actual_result['results'] == [{'x': 100}]) self.query = 'explain select d.x from {0} d where x IN (select raw d.x from {0} ' \ 'b use keys[d.id])'.format(query_bucket) actual_result = self.run_cbq_query() plan = self.ExplainPlanHelper(actual_result) self.assertTrue("covers" in str(plan)) self.assertTrue(plan['~children'][0]['index'] == 'ix1') self.query = 'select d.x from {0} d where x IN (select raw d.x from {0}' \ ' b use keys[d.id])'.format(query_bucket) actual_result = self.run_cbq_query() self.assertTrue(actual_result['results'] == [{'x': 100}]) self.query = 'explain select d.x from {0} d where x IN (select raw b.x from {0} b where b.x IN (' \ 'select raw d.x from {0} c use keys["kk02"]))'.format(query_bucket) actual_result = self.run_cbq_query() plan = self.ExplainPlanHelper(actual_result) self.assertTrue("covers" in str(plan)) self.assertTrue(plan['~children'][0]['index'] == 'ix1') self.query = 'select d.x from {0} d where x IN (select raw b.x from {0} b ' \ ' where b.x IN (select raw ' \ 'd.x from {0} c use keys["kk02"]))'.format(query_bucket) actual_result = self.run_cbq_query() self.assertTrue(actual_result['results'] == [{'x': 100}]) self.query = 'explain select d.x from {0} d where x IN (select raw b.x from {0} b where b.x IN (' \ 'select raw d.x from {0} c use keys["kk02"] where d.x = b.x))'.format(query_bucket) actual_result = self.run_cbq_query() plan = self.ExplainPlanHelper(actual_result) self.assertTrue("covers" in str(plan)) self.assertTrue(plan['~children'][0]['index'] == 'ix1') self.query = 'select d.x from {0} d where x IN (select raw b.x from {0} b ' \ ' where b.x IN (select raw ' \ 'd.x from {0} c use keys["kk02"] where d.x = b.x))'.format(query_bucket) actual_result = self.run_cbq_query() self.assertTrue(actual_result['results'] == [{'x': 100}]) self.query = 'explain select d.x from {0} d where x IN (select raw b.x from {0} b where b.x IN (' \ 'select raw d.x from {0} c use keys["kk02"] where d.x = b.x))'.format(query_bucket) actual_result = self.run_cbq_query() plan = self.ExplainPlanHelper(actual_result) self.assertTrue("covers" in str(plan)) self.assertTrue(plan['~children'][0]['index'] == 'ix1') self.query = 'select d.x from {0} d where x IN (select raw b.x from {0} b' \ ' where b.x IN (select raw ' \ 'd.x from {0} c use keys["kk02"] where d.x = b.x))'.format(query_bucket) actual_result = self.run_cbq_query() self.assertTrue(actual_result['results'] == [{'x': 100}]) self.query = 'explain select d.x from {0} d where x IN (select raw b.x' \ ' from {0} b use keys["kk02"] ' \ 'where b.x IN (select raw d.x from {0} c use keys["kk02"]))'.format(query_bucket) actual_result = self.run_cbq_query() plan = self.ExplainPlanHelper(actual_result) self.assertTrue("covers" in str(plan)) self.assertTrue(plan['~children'][0]['index'] == 'ix1') self.query = 'select d.x from {0} d where x IN (select raw b.x from {0} b use keys["kk02"] ' \ 'where b.x IN (select raw d.x from {0} c use keys["kk02"]))'.format(query_bucket) actual_result = self.run_cbq_query() self.assertTrue(actual_result['results'] == [{'x': 100}]) self.query = 'explain select d.x,d.id from {0} d where x IN (select raw b.x from {0} b where ' \ 'b.x IN (select raw d.x from {0} c use keys["kk02"]))'.format(query_bucket) actual_result = self.run_cbq_query() plan = self.ExplainPlanHelper(actual_result) self.assertTrue("covers" in str(plan)) self.assertTrue(plan['~children'][0]['index'] == 'ix1') self.query = 'select d.x,d.y from {0} d where x IN (select raw b.x from {0} b where b.x ' \ 'IN (select raw d.x from {0} c use keys["kk02"]))'.format(query_bucket) actual_result = self.run_cbq_query() diffs = DeepDiff(actual_result['results'], [{'y': 101, 'x': 100}], ignore_order=True) if diffs: self.assertTrue(False, diffs) self.query = 'explain select d.x from {0} d where x IN (select raw (select raw d.x from {0}' \ ' c use keys[d.id] where d.x = b.x)[0] from {0} b ' \ 'where b.x is not null)'.format(query_bucket) self.run_cbq_query() self.assertTrue("covers" in str(plan)) self.assertTrue(plan['~children'][0]['index'] == 'ix1') self.query = 'select d.x from {0} d where x IN (select raw (select raw d.x from {0} c ' \ 'use keys[d.id] where d.x = b.x)[0] from {0} b where b.x ' \ 'is not null)'.format(query_bucket) actual_result = self.run_cbq_query() self.assertTrue(actual_result['results'] == [{'x': 100}]) self.query = 'explain select (select raw d.x from ' + self.query_buckets[0] + \ ' c use keys[d.id]) as s, d.x from ' + self.query_buckets[0] + \ ' d where x is not null' actual_result = self.run_cbq_query() plan = self.ExplainPlanHelper(actual_result) # print plan self.assertTrue("covers" in str(plan)) self.assertTrue(plan['~children'][0]['index'] == 'ix1') self.query = 'select (select raw d.x from ' + self.query_buckets[0] + \ ' c use keys[d.id]) as s, d.x from ' + self.query_buckets[0] + \ ' d where x is not null' actual_result = self.run_cbq_query() diffs = DeepDiff(actual_result['results'], [{'x': 100, 's': [100]}], ignore_order=True) self.assertEqual(diffs, {}) finally: self.query = 'delete from %s use keys["kk02"]' % query_bucket self.run_cbq_query() self.query = "DROP INDEX %s ON %s USING %s" % ("ix1", query_bucket, self.index_type) self.run_cbq_query() # This test has no uses anywhere def test_object_concat_remove(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'select object_concat({"name":"test"},{"test":123},tasks_points) as obj from %s order by ' \ 'meta().id limit 10;' % query_bucket actual_result = self.run_cbq_query() self.assertTrue(actual_result['results'] == ( [{'obj': {'test': 123, 'task1': 1, 'task2': 1, 'name': 'test'}}, {'obj': {'test': 123, 'task1': 1, 'task2': 1, 'name': 'test'}}, {'obj': {'test': 123, 'task1': 1, 'task2': 1, 'name': 'test'}}, {'obj': {'test': 123, 'task1': 1, 'task2': 1, 'name': 'test'}}, {'obj': {'test': 123, 'task1': 1, 'task2': 1, 'name': 'test'}}, {'obj': {'test': 123, 'task1': 1, 'task2': 1, 'name': 'test'}}, {'obj': {'test': 123, 'task1': 1, 'task2': 1, 'name': 'test'}}, {'obj': {'test': 123, 'task1': 1, 'task2': 1, 'name': 'test'}}, {'obj': {'test': 123, 'task1': 1, 'task2': 1, 'name': 'test'}}, {'obj': {'test': 123, 'task1': 1, 'task2': 1, 'name': 'test'}}])) self.query = 'select OBJECT_REMOVE({"abc":1,"def":2,"fgh":3},"def")' actual_result = self.run_cbq_query() self.assertTrue(actual_result['results'], ([{'$1': {'abc': 1, 'fgh': 3}}])) def test_array_concat(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title," + \ " array_concat(array_agg(name), array_agg(email)) as names" + \ " FROM %s GROUP BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = self.sort_nested_list(actual_list['results']) actual_result1 = sorted(actual_result, key=lambda doc: (doc['job_title'])) tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "names": [x["name"] for x in self.full_list if x["job_title"] == group] + [x["email"] for x in self.full_list if x["job_title"] == group]} for group in tmp_groups] expected_result1 = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result1, expected_result1) self.query = "SELECT job_title," + \ " array_concat(array_agg(name), array_agg(email),array_agg(join_day)) as names" + \ " FROM %s GROUP BY job_title limit 10" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"job_title": group, "names": [x["name"] for x in self.full_list if x["job_title"] == group] + [x["email"] for x in self.full_list if x["job_title"] == group] + [x["join_day"] for x in self.full_list if x["job_title"] == group]} for group in tmp_groups][0:10] diffs = DeepDiff(actual_result, expected_result, ignore_order=True) if diffs: self.assertTrue(False, diffs) def test_array_prepend(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title," + \ " array_prepend(1.2, array_agg(test_rate)) as rates" + \ " FROM %s GROUP BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = self.sort_nested_list(actual_list['results']) actual_result = sorted(actual_result, key=lambda doc: (doc['job_title'])) tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "rates": [x["test_rate"] for x in self.full_list if x["job_title"] == group] + [1.2]} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result, expected_result) self.query = "SELECT job_title," + \ " array_prepend(1.2,2.4, array_agg(test_rate)) as rates" + \ " FROM %s GROUP BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = self.sort_nested_list(actual_list['results']) actual_result = sorted(actual_result, key=lambda doc: (doc['job_title'])) tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "rates": [x["test_rate"] for x in self.full_list if x["job_title"] == group] + [1.2] + [2.4]} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result, expected_result) self.query = "SELECT job_title," + \ " array_prepend(['skill5', 'skill8'], array_agg(skills)) as skills_new" + \ " FROM %s GROUP BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = self.sort_nested_list(actual_list['results']) actual_result = sorted(actual_result, key=lambda doc: (doc['job_title'])) tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "skills_new": [x["skills"] for x in self.full_list if x["job_title"] == group] + [['skill5', 'skill8']]} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result, expected_result) self.query = "SELECT job_title," + \ " array_prepend(['skill5', 'skill8'],['skill9','skill10'], array_agg(skills)) as " + \ " skills_new FROM %s GROUP BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = self.sort_nested_list(actual_list['results']) actual_result = sorted(actual_result, key=lambda doc: (doc['job_title'])) tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "skills_new": [x["skills"] for x in self.full_list if x["job_title"] == group] + [['skill5', 'skill8']] + [['skill9', 'skill10']]} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result, expected_result) def test_array_remove(self): self.fail_if_no_buckets() value = 'employee-1' for query_bucket in self.query_buckets: self.query = "SELECT job_title," + \ " array_remove(array_agg(DISTINCT name), '%s') as names" % value + \ " FROM %s GROUP BY job_title ORDER BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = self.sort_nested_list(actual_list['results']) tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "names": [x["name"] for x in self.full_list if x["job_title"] == group and x["name"] != value]} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result, expected_result) value1 = 'employee-2' value2 = 'emp-2' value3 = 'employee-1' self.query = "SELECT job_title," + \ " array_remove(array_agg(DISTINCT name), '%s','%s','%s') as " % (value1, value2, value3) + \ " names FROM %s GROUP BY job_title ORDER BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "names": [x["name"] for x in self.full_list if x["job_title"] == group and x["name"] != value1 and x[ "name"] != value3]} for group in tmp_groups] self._verify_results(actual_result, expected_result) def test_array_insert(self): value1 = 'skill-20' value2 = 'skill-21' self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT array_insert(skills, 1, '%s','%s') " % (value1, value2) + \ " FROM %s limit 1" % query_bucket actual_list = self.run_cbq_query() expected_result = [{'$1': ['skill2010', 'skill-20', 'skill-21', 'skill2011']}] self.assertTrue(actual_list['results'] == expected_result) def test_array_avg(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, array_avg(array_agg(test_rate))" + \ " as rates FROM %s GROUP BY job_title ORDER BY job_title" % query_bucket actual_result = self.run_cbq_query() for doc in actual_result['results']: doc['rates'] = round(doc['rates']) tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "rates": round(sum([x["test_rate"] for x in self.full_list if x["job_title"] == group]) / float(len([x["test_rate"] for x in self.full_list if x[ "job_title"] == group])))} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result['results'], expected_result) def test_array_contains(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, array_contains(array_agg(name), 'employee-1')" + \ " as emp_job FROM %s GROUP BY job_title ORDER BY job_title" % query_bucket actual_result = self.run_cbq_query() actual_result = actual_result['results'] tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "emp_job": 'employee-1' in [x["name"] for x in self.full_list if x["job_title"] == group]} for group in tmp_groups] self._verify_results(actual_result, expected_result) def test_array_count(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, array_count(array_agg(name)) as names" + \ " FROM %s GROUP BY job_title ORDER BY job_title" % query_bucket actual_result = self.run_cbq_query() tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "names": len([x["name"] for x in self.full_list if x["job_title"] == group])} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result['results'], expected_result) def test_array_distinct(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, array_distinct(array_agg(name)) as names" + \ " FROM %s GROUP BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "names": [x["name"] for x in self.full_list if x["job_title"] == group]} for group in tmp_groups] for item in actual_result: self.assertTrue(item not in expected_result, f"{actual_result} not matching with {expected_result}") def test_array_max(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, array_max(array_agg(test_rate)) as rates" + \ " FROM %s GROUP BY job_title ORDER BY job_title" % query_bucket actual_result = self.run_cbq_query() tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "rates": max([x["test_rate"] for x in self.full_list if x["job_title"] == group])} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result['results'], expected_result) def test_array_sum(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, round(array_sum(array_agg(test_rate))) as rates" + \ " FROM %s GROUP BY job_title ORDER BY job_title" % query_bucket actual_result = self.run_cbq_query() tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "rates": round(sum([x["test_rate"] for x in self.full_list if x["job_title"] == group]))} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result['results'], expected_result) def test_array_min(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, array_min(array_agg(test_rate)) as rates" + \ " FROM %s GROUP BY job_title ORDER BY job_title" % query_bucket actual_result = self.run_cbq_query() tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "rates": min([x["test_rate"] for x in self.full_list if x["job_title"] == group])} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result['results'], expected_result) def test_array_position(self): self.query = "select array_position(['support', 'qa'], 'dev') as index_num" actual_result = self.run_cbq_query() expected_result = [{"index_num": -1}] self._verify_results(actual_result['results'], expected_result) self.query = "select array_position(['support', 'qa'], 'qa') as index_num" actual_result = self.run_cbq_query() expected_result = [{"index_num": 1}] self._verify_results(actual_result['results'], expected_result) def test_array_put(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, array_put(array_agg(distinct name), 'employee-1') as emp_job" + \ " FROM %s GROUP BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "emp_job": [x["name"] for x in self.full_list if x["job_title"] == group]} for group in tmp_groups] for item in actual_result: self.assertTrue(item not in expected_result, f"{actual_result} not matching with {expected_result}") self.query = "SELECT job_title, array_put(array_agg(distinct name), 'employee-50','employee-51') as " + \ " emp_job FROM %s GROUP BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "emp_job": [x["name"] for x in self.full_list if x["job_title"] == group] + ['employee-50'] + [ 'employee-51']} for group in tmp_groups] for item in actual_result: self.assertTrue(item not in expected_result, f"{actual_result} not matching with {expected_result}") self.query = "SELECT job_title, array_put(array_agg(distinct name), 'employee-47') as emp_job" + \ " FROM %s GROUP BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"job_title": group, "emp_job": [x["name"] for x in self.full_list if x["job_title"] == group] + ['employee-47']} for group in tmp_groups] for item in actual_result: self.assertTrue(item not in expected_result, f"{actual_result} not matching with {expected_result}") def test_array_range(self): self.query = "select array_range(0,10) as num" actual_result = self.run_cbq_query() expected_result = [{"num": list(range(10))}] self._verify_results(actual_result['results'], expected_result) def test_array_replace(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, array_replace(array_agg(name), 'employee-1', 'employee-47') as emp_job" + \ " FROM %s GROUP BY job_title ORDER BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = self.sort_nested_list(actual_list['results']) tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "emp_job": ["employee-47" if x["name"] == 'employee-1' else x["name"] for x in self.full_list if x["job_title"] == group]} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result, expected_result) def test_array_repeat(self): self.query = "select ARRAY_REPEAT(2, 2) as num" actual_result = self.run_cbq_query() expected_result = [{"num": [2] * 2}] self._verify_results(actual_result['results'], expected_result) def test_array_reverse(self): self.query = "select array_reverse([1,2,3]) as num" actual_result = self.run_cbq_query() expected_result = [{"num": [3, 2, 1]}] self._verify_results(actual_result['results'], expected_result) def test_array_sort(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, array_sort(array_agg(distinct test_rate)) as emp_job" + \ " FROM %s GROUP BY job_title ORDER BY job_title" % query_bucket actual_result = self.run_cbq_query() tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "emp_job": [x["test_rate"] for x in self.full_list if x["job_title"] == group]} for group in tmp_groups] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) for item in actual_result['results']: self.assertTrue(item not in expected_result, f"{actual_result} not matching with {expected_result}") # This test has no usages anywhere def test_poly_length(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: query_fields = ['tasks_points', 'VMs', 'skills'] for query_field in query_fields: self.query = "Select length(%s) as custom_num from %s order by custom_num" % (query_field, query_bucket) actual_result = self.run_cbq_query() expected_result = [{"custom_num": None} for _ in self.full_list] self._verify_results(actual_result['results'], expected_result) self.query = "Select poly_length(%s) as custom_num from %s order by custom_num" % ( query_field, query_bucket) actual_result = self.run_cbq_query() expected_result = [{"custom_num": len(doc[query_field])} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['custom_num'])) self._verify_results(actual_result['results'], expected_result) def test_array_agg(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, array_agg(name) as names" + \ " FROM %s GROUP BY job_title" % query_bucket actual_list = self.run_cbq_query() actual_result = self.sort_nested_list(actual_list['results']) actual_result = sorted(actual_result, key=lambda doc: (doc['job_title'])) tmp_groups = {doc['job_title'] for doc in self.full_list} expected_list = [{"job_title": group, "names": [x["name"] for x in self.full_list if x["job_title"] == group]} for group in tmp_groups] expected_result = self.sort_nested_list(expected_list) expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result, expected_result) ############################################################################################## # # EXPRESSIONS ############################################################################################## def test_case(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: query_bucket = self.get_collection_name(query_bucket) self.query = "SELECT name, CASE WHEN join_mo < 3 OR join_mo > 11 THEN 'winter'" + \ " WHEN join_mo < 6 AND join_mo > 2 THEN 'spring' " + \ "WHEN join_mo < 9 AND join_mo > 5 THEN 'summer' " + \ "ELSE 'autumn' END AS period FROM %s" % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: ( doc['name'], doc['period'])) expected_result = [{"name": doc['name'], "period": ((('autumn', 'summer')[doc['join_mo'] in [6, 7, 8]], 'spring')[doc['join_mo'] in [3, 4, 5]], 'winter') [doc['join_mo'] in [12, 1, 2]]} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['name'], doc['period'])) self._verify_results(actual_result, expected_result) def test_case_expr(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: query_bucket = self.get_collection_name(query_bucket) self.query = "SELECT name, CASE job_title WHEN 'Sales' THEN 'Marketing'" + \ "ELSE job_title END AS dept FROM %s" % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: ( doc['name'], doc['dept'])) expected_result = [{"name": doc['name'], "dept": (doc['job_title'], 'Marketing')[doc['job_title'] == 'Sales']} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['name'], doc['dept'])) self._verify_results(actual_result, expected_result) def test_case_arithm(self): self.query = "SELECT CASE WHEN 1+1=3 THEN 7+7 WHEN 2+2=5 THEN 8+8 ELSE 2 END" actual_result = self.run_cbq_query() expected_result = [{"$1": 2}] self._verify_results(actual_result['results'], expected_result) def test_in_int(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name from %s where join_mo in [1,6]" % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['name'])) expected_result = [{"name": doc['name']} for doc in self.full_list if doc['join_mo'] in [1, 6]] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result, expected_result) self.query = "select name from %s where join_mo not in [1,6]" % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: ( doc['name'])) expected_result = [{"name": doc['name']} for doc in self.full_list if not (doc['join_mo'] in [1, 6])] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result, expected_result) def test_in_str(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name from %s where job_title in ['Sales', 'Support']" % query_bucket actual_result = self.run_cbq_query() self.query = "select name from %s where REVERSE(job_title) in ['selaS', 'troppuS']" % query_bucket actual_result1 = self.run_cbq_query() self.assertEqual(actual_result['results'], actual_result1['results']) actual_result = sorted(actual_result['results'], key=lambda doc: ( doc['name'])) expected_result = [{"name": doc['name']} for doc in self.full_list if doc['job_title'] in ['Sales', 'Support']] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result, expected_result) self.query = "select name from %s where job_title not in ['Sales', 'Support']" % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: ( doc['name'])) expected_result = [{"name": doc['name']} for doc in self.full_list if not (doc['job_title'] in ['Sales', 'Support'])] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result, expected_result) def test_prepared_in_str(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name from %s where job_title in ['Sales', 'Support']" % query_bucket self.prepared_common_body() def test_logic_expr(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT tasks_points.task1 as task FROM %s WHERE " % query_bucket + \ "tasks_points.task1 > 1 AND tasks_points.task1 < 4" actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: ( doc['task'])) expected_result = [{"task": doc['tasks_points']['task1']} for doc in self.full_list if 1 < doc['tasks_points']['task1'] < 4] expected_result = sorted(expected_result, key=lambda doc: (doc['task'])) self._verify_results(actual_result, expected_result) def test_comparition_equal_int(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT tasks_points.task1 as task FROM %s WHERE " % query_bucket + "tasks_points.task1 = 4" actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: ( doc['task'])) expected_result = [{"task": doc['tasks_points']['task1']} for doc in self.full_list if doc['tasks_points']['task1'] == 4] expected_result = sorted(expected_result, key=lambda doc: (doc['task'])) self._verify_results(actual_result, expected_result) self.query = "SELECT tasks_points.task1 as task FROM %s WHERE " % query_bucket + "tasks_points.task1 == 4" actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: ( doc['task'])) self._verify_results(actual_result, expected_result) def test_comparition_equal_str(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name FROM %s WHERE " % query_bucket + "name = 'employee-4'" actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: ( doc['name'])) expected_result = [{"name": doc['name']} for doc in self.full_list if doc['name'] == 'employee-4'] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result, expected_result) self.query = "SELECT name FROM %s WHERE " % query_bucket + "name == 'employee-4'" actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: ( doc['name'])) self._verify_results(actual_result, expected_result) def test_comparition_not_equal(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT tasks_points.task1 as task FROM %s WHERE " % query_bucket + \ "tasks_points.task1 != 1 ORDER BY task" actual_result = self.run_cbq_query() actual_result = actual_result['results'] expected_result = [{"task": doc['tasks_points']['task1']} for doc in self.full_list if doc['tasks_points']['task1'] != 1] expected_result = sorted(expected_result, key=lambda doc: (doc['task'])) self._verify_results(actual_result, expected_result) def test_comparition_not_equal_more_less(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT tasks_points.task1 as task FROM %s WHERE " % query_bucket + \ "tasks_points.task1 <> 1 ORDER BY task" actual_result = self.run_cbq_query() actual_result = actual_result['results'] expected_result = [{"task": doc['tasks_points']['task1']} for doc in self.full_list if doc['tasks_points']['task1'] != 1] expected_result = sorted(expected_result, key=lambda doc: (doc['task'])) self._verify_results(actual_result, expected_result) def test_every_comparision_not_equal(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name FROM %s d WHERE " % query_bucket + \ "(EVERY vm IN d.VMs SATISFIES vm.memory != 5 END) ORDER BY name" if self.analytics: self.query = "SELECT name FROM %s d WHERE " % query_bucket + \ "(EVERY vm IN d.VMs SATISFIES vm.memory != 5 ) ORDER BY name" actual_result = self.run_cbq_query() expected_result = [{"name": doc['name']} for doc in self.full_list if len([vm for vm in doc["VMs"] if vm['memory'] != 5]) == len(doc["VMs"])] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) def test_every_comparision_not_equal_less_more(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name FROM %s d WHERE " % query_bucket + \ "(EVERY vm IN d.VMs SATISFIES vm.memory <> 5 END) ORDER BY name" if self.analytics: self.query = "SELECT name FROM %s d WHERE " % query_bucket + \ "(EVERY vm IN d.VMs SATISFIES vm.memory <> 5 ) ORDER BY name" actual_result = self.run_cbq_query() expected_result = [{"name": doc['name']} for doc in self.full_list if len([vm for vm in doc["VMs"] if vm['memory'] != 5]) == len(doc["VMs"])] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) def test_any_between(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name, email FROM %s d WHERE " % query_bucket + \ "(ANY skill IN d.skills SATISFIES skill = 'skill2010' END)" + \ " AND (ANY vm IN d.VMs SATISFIES vm.RAM between 1 and 5 END)" + \ "AND NOT (job_title = 'Sales') ORDER BY name" if self.analytics: self.query = "SELECT name, email FROM %s d WHERE " % query_bucket + \ "(ANY skill IN d.skills SATISFIES skill = 'skill2010' )" + \ " AND (ANY vm IN d.VMs SATISFIES vm.RAM between 1 and 5 )" + \ "AND NOT (job_title = 'Sales') ORDER BY name" actual_result = self.run_cbq_query() expected_result = [{"name": doc['name'], "email": doc["email"]} for doc in self.full_list if len([skill for skill in doc["skills"] if skill == 'skill2010']) > 0 and len([vm for vm in doc["VMs"] if vm["RAM"] in [1, 2, 3, 4, 5]]) > 0 and doc["job_title"] != 'Sales'] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) def test_any_less_equal(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name, email FROM %s d WHERE " % query_bucket + \ "(ANY skill IN d.skills SATISFIES skill = 'skill2010' END)" + \ " AND (ANY vm IN d.VMs SATISFIES vm.RAM <= 5 END)" + \ "AND NOT (job_title = 'Sales') ORDER BY name" if self.analytics: self.query = "SELECT name, email FROM %s d WHERE " % query_bucket + \ "(ANY skill IN d.skills SATISFIES skill = 'skill2010' )" + \ " AND (ANY vm IN d.VMs SATISFIES vm.RAM <= 5 )" + \ "AND NOT (job_title = 'Sales') ORDER BY name" actual_result = self.run_cbq_query() expected_result = [{"name": doc['name'], "email": doc["email"]} for doc in self.full_list if len([skill for skill in doc["skills"] if skill == 'skill2010']) > 0 and len([vm for vm in doc["VMs"] if vm["RAM"] <= 5]) > 0 and doc["job_title"] != 'Sales'] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) def test_any_more_equal(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name, email FROM %s d WHERE " % query_bucket + \ "(ANY skill IN d.skills SATISFIES skill = 'skill2010' END)" + \ " AND (ANY vm IN d.VMs SATISFIES vm.RAM >= 5 END)" + \ "AND NOT (job_title = 'Sales') ORDER BY name" if self.analytics: self.query = "SELECT name, email FROM %s d WHERE " % query_bucket + \ "(ANY skill IN d.skills SATISFIES skill = 'skill2010' )" + \ " AND (ANY vm IN d.VMs SATISFIES vm.RAM >= 5 )" + \ "AND NOT (job_title = 'Sales') ORDER BY name" actual_result = self.run_cbq_query() expected_result = [{"name": doc['name'], "email": doc["email"]} for doc in self.full_list if len([skill for skill in doc["skills"] if skill == 'skill2010']) > 0 and len([vm for vm in doc["VMs"] if vm["RAM"] >= 5]) > 0 and doc["job_title"] != 'Sales'] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) def test_prepared_between(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: query_bucket = self.get_collection_name(query_bucket) self.query = "SELECT name, email FROM %s d WHERE " % query_bucket + \ "(ANY skill IN d.skills SATISFIES skill = 'skill2010' END)" + \ " AND (ANY vm IN d.VMs SATISFIES vm.RAM between 1 and 5 END)" + \ "AND NOT (job_title = 'Sales') ORDER BY name" self.prepared_common_body() def test_named_prepared_between(self): self.fail_if_no_buckets() if self.monitoring: self.query = "select * from system:prepareds" result = self.run_cbq_query() self.assertTrue(result['metrics']['resultCount'] == 0) for query_bucket in self.query_buckets: self.query = "SELECT name, email FROM %s d WHERE " % query_bucket + \ "(ANY skill IN d.skills SATISFIES skill = 'skill2010' END)" + \ " AND (ANY vm IN d.VMs SATISFIES vm.RAM between 1 and 5 END)" + \ "AND NOT (job_title = 'Sales') ORDER BY name" self.prepared_common_body() if self.monitoring: self.query = "select * from system:prepareds" result = self.run_cbq_query() self.assertTrue(result['metrics']['resultCount'] == 1) name = result['results'][0]['prepareds']['name'] self.query = 'delete from system:prepareds where name = "%s" ' % name self.run_cbq_query() self.query = 'select * from system:prepareds where name = "%s" ' % name result = self.run_cbq_query() self.assertTrue(result['metrics']['resultCount'] == 0) def test_prepared_comparision_not_equal_less_more(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name FROM %s d WHERE " % query_bucket + \ "(EVERY vm IN d.VMs SATISFIES vm.memory <> 5 END) ORDER BY name" self.prepared_common_body() def test_prepared_comparision_not_equal(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name FROM %s d WHERE " % query_bucket + \ "(EVERY vm IN d.VMs SATISFIES vm.memory != 5 END) ORDER BY name" self.prepared_common_body() def test_prepared_more_equal(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name FROM %s d WHERE " % query_bucket + \ "(EVERY vm IN d.VMs SATISFIES vm.memory >= 5 END) ORDER BY name" self.prepared_common_body() def test_prepared_less_equal(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name FROM %s d WHERE " % query_bucket + \ "(EVERY vm IN d.VMs SATISFIES vm.memory <= 5 END) ORDER BY name" self.prepared_common_body() def test_let_not_equal(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select compare from %s let compare = (test_rate != 2)" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"compare": doc["test_rate"] != 2} for doc in self.full_list] self._verify_results(actual_result, expected_result) def test_let_between(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select compare from %s let compare = (test_rate between 1 and 3)" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"compare": 1 <= doc["test_rate"] <= 3} for doc in self.full_list] self._verify_results(actual_result, expected_result) def test_let_not_equal_less_more(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select compare from %s let compare = (test_rate <> 2)" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"compare": doc["test_rate"] != 2} for doc in self.full_list] self._verify_results(actual_result, expected_result) def test_let_more_equal(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select compare from %s let compare = (test_rate >= 2)" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"compare": doc["test_rate"] >= 2} for doc in self.full_list] self._verify_results(actual_result, expected_result) def test_let_less_equal(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select compare from %s let compare = (test_rate <= 2)" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"compare": doc["test_rate"] <= 2} for doc in self.full_list] self._verify_results(actual_result, expected_result) def test_comparition_equal_not_equal(self): self.fail_if_no_buckets() template = "SELECT join_day, join_mo FROM %s WHERE " + \ "join_day == 1 and join_mo != 2 ORDER BY join_day, join_mo" for query_bucket in self.query_buckets: self.query = template % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: (doc['join_day'], doc['join_mo'])) expected_result = [{"join_mo": doc['join_mo'], "join_day": doc['join_day']} for doc in self.full_list if doc['join_day'] == 1 and doc["join_mo"] != 2] expected_result = sorted(expected_result, key=lambda doc: (doc['join_day'], doc['join_mo'])) self._verify_results(actual_result, expected_result) return template def test_comparition_more_and_less_equal(self): self.fail_if_no_buckets() template = "SELECT join_yr, test_rate FROM %s WHERE join_yr >= 2010 AND test_rate <= 4" for query_bucket in self.query_buckets: self.query = template % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: ( doc['test_rate'], doc['join_yr'])) expected_result = [{"test_rate": doc['test_rate'], "join_yr": doc['join_yr']} for doc in self.full_list if doc['test_rate'] <= 4 and doc['join_yr'] >= 2010] expected_result = sorted(expected_result, key=lambda doc: (doc['test_rate'], doc['join_yr'])) self._verify_results(actual_result, expected_result) return template def test_comparition_null_missing(self): self.fail_if_no_buckets() template = "SELECT skills, VMs FROM %s WHERE " + \ "skills is not null AND VMs is not missing" for query_bucket in self.query_buckets: self.query = template % query_bucket actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: ( doc['VMs'], doc['skills'])) expected_result = [{"VMs": doc['VMs'], "skills": doc['skills']} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['VMs'], doc['skills'])) self._verify_results(actual_result, expected_result) return template def test_comparition_aggr_fns(self): self.fail_if_no_buckets() template = "SELECT count(join_yr) years, sum(test_rate) rate FROM %s" for query_bucket in self.query_buckets: self.query = template % query_bucket actual_result = self.run_cbq_query() actual_result = actual_result['results'] expected_result = [{"years": len([doc['join_yr'] for doc in self.full_list]), "rate": sum([doc['test_rate'] for doc in self.full_list])}] self.assertTrue(round(actual_result[0]['rate']) == round(expected_result[0]['rate'])) self.assertTrue((actual_result[0]['years']) == (expected_result[0]['years'])) return template # This test has no uses anywhere def test_comparition_meta(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT meta(d).id, meta(d).type FROM %s d" % query_bucket actual_result = self.run_cbq_query() actual_result = actual_result['results'] def test_comparition_more_less_equal(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT tasks_points.task1 as task FROM %s WHERE " % query_bucket + \ "tasks_points.task1 >= 1 AND tasks_points.task1 <= 4" actual_result = self.run_cbq_query() actual_result = sorted(actual_result['results'], key=lambda doc: ( doc['task'])) expected_result = [{"task": doc['tasks_points']['task1']} for doc in self.full_list if 1 <= doc['tasks_points']['task1'] <= 4] expected_result = sorted(expected_result, key=lambda doc: (doc['task'])) self._verify_results(actual_result, expected_result) def test_comparition_expr(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT tasks_points.task1 as task FROM %s WHERE " % query_bucket + \ "tasks_points.task1 > tasks_points.task1" actual_result = self.run_cbq_query() self._verify_results(actual_result['results'], []) def test_arithm(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, SUM(test_rate) % COUNT(distinct join_yr)" + \ " as avg_per_year from {0} group by job_title".format(query_bucket) if self.analytics: self.query = "SELECT d.job_title, SUM(d.test_rate) % COUNT(d.join_yr)" + \ " as avg_per_year from {0} d group by d.job_title".format(query_bucket) actual_result = self.run_cbq_query() actual_result = [{"job_title": doc["job_title"], "avg_per_year": round(doc["avg_per_year"], 2)} for doc in actual_result['results']] actual_result = sorted(actual_result, key=lambda doc: (doc['job_title'])) tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "avg_per_year": math.fsum([doc['test_rate'] for doc in self.full_list if doc['job_title'] == group]) % len({doc['join_yr'] for doc in self.full_list if doc['job_title'] == group})} for group in tmp_groups] expected_result = [{"job_title": doc["job_title"], "avg_per_year": round(doc["avg_per_year"], 2)} for doc in expected_result] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result, expected_result) self.query = "SELECT job_title, (SUM(tasks_points.task1) +" + \ " SUM(tasks_points.task2)) % COUNT(distinct join_yr) as avg_per_year" + \ " from {0} group by job_title".format(query_bucket) if self.analytics: self.query = "SELECT d.job_title, (SUM(d.tasks_points.task1) +" + \ " SUM(d.tasks_points.task2)) % COUNT(d.join_yr) as avg_per_year" + \ " from {0} d group by d.job_title".format(query_bucket) actual_result = self.run_cbq_query() actual_result = [{"job_title": doc["job_title"], "avg_per_year": round(doc["avg_per_year"], 2)} for doc in actual_result['results']] actual_result = sorted(actual_result, key=lambda doc: ( doc['job_title'])) tmp_groups = {doc['job_title'] for doc in self.full_list} expected_result = [{"job_title": group, "avg_per_year": (math.fsum([doc['tasks_points']['task1'] for doc in self.full_list if doc['job_title'] == group]) + math.fsum([doc['tasks_points']['task2'] for doc in self.full_list if doc['job_title'] == group])) % len({doc['join_yr'] for doc in self.full_list if doc['job_title'] == group})} for group in tmp_groups] expected_result = [{"job_title": doc["job_title"], "avg_per_year": int(round(doc["avg_per_year"], 2))} for doc in expected_result] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'])) self._verify_results(actual_result, expected_result) # https://issues.couchbase.com/browse/MB-29401 def test_sum_large_negative_numbers(self): self.fail_if_no_buckets() self.run_cbq_query( "insert into " + self.query_buckets[0] + " (KEY, VALUE) VALUES ('doc1',{ 'f1' : -822337203685477580 })") self.run_cbq_query( "insert into " + self.query_buckets[0] + " (KEY, VALUE) VALUES ('doc2',{ 'f1' : -822337203685477580 })") self.query = "select SUM(f1) from " + self.query_buckets[0] + " " result = self.run_cbq_query() found_result = result['results'][0]['$1'] expected_result = -1644674407370955160 self.assertEqual(found_result, expected_result) self.run_cbq_query( "insert into " + self.query_buckets[0] + " (KEY, VALUE) VALUES ('doc3',{ 'f2' : -822337203685477580 })") self.run_cbq_query("insert into " + self.query_buckets[0] + " (KEY, VALUE) VALUES ('doc4',{ 'f2' : 10 })") self.query = "select SUM(f2) from " + self.query_buckets[0] + " " result = self.run_cbq_query() found_result = result['results'][0]['$1'] expected_result = -822337203685477570 self.assertEqual(found_result, expected_result) ############################################################################################## # # EXPLAIN ############################################################################################## def test_explain(self): self.fail_if_no_buckets() for _ in self.query_buckets: res = self.run_cbq_query() self.log.info(res) plan = self.ExplainPlanHelper(res) self.assertTrue(plan["~children"][0]["index"] == "#primary", "Type should be #primary, but is: %s" % plan["~children"][0]["index"]) ############################################################################################## # # EXPLAIN WITH A PARTICULAR INDEX ############################################################################################## # Test has no usages anywhere def test_explain_particular_index(self, index): self.fail_if_no_buckets() for _ in self.query_buckets: res = self.run_cbq_query() self.log.info(res) plan = self.ExplainPlanHelper(res) self.assertTrue(plan['~children'][2]['~child']['~children'][0]['scan']['index'] == index, "wrong index used") ############################################################################################### # # EXPLAIN WITH UNION SCAN: Covering Indexes ############################################################################################## # Test has no usages anywhere def test_explain_union(self, index): self.fail_if_no_buckets() for _ in self.query_buckets: res = self.run_cbq_query() plan = self.ExplainPlanHelper(res) if "IN" in self.query: self.assertTrue(plan["~children"][0]["~children"][0]["#operator"] == "DistinctScan", "DistinctScan Operator is not used by this query") else: self.assertTrue(plan["~children"][0]["~children"][0]["#operator"] == "UnionScan", "UnionScan Operator is not used by this query") if plan["~children"][0]["~children"][0]["scan"]["#operator"] == "IndexScan": self.log.info("IndexScan Operator is also used by this query in scans") else: self.log.error("IndexScan Operator is not used by this query, Covering Indexes not used properly") self.fail("IndexScan Operator is not used by this query, Covering Indexes not used properly") if plan["~children"][0]["~children"][0]["scan"]["index"] == index: self.log.info("Query is using specified index") else: self.log.info("Query is not using specified index") ############################################################################################## # # DATETIME ############################################################################################## def test_clock_millis(self): self.query = "select clock_millis() as now" res = self.run_cbq_query() self.assertFalse("error" in str(res).lower()) def test_clock_str(self): self.query = "select clock_str() as now" now = datetime.datetime.now() res = self.run_cbq_query() expected = "%s-%02d-%02dT" % (now.year, now.month, now.day) self.assertTrue(res["results"][0]["now"].startswith(expected), "Result expected: %s. Actual %s" % (expected, res["results"])) def test_date_add_millis(self): self.query = "select date_add_millis(clock_millis(), 100, 'day') as now" now = time.time() res = self.run_cbq_query() self.assertTrue((res["results"][0]["now"] > now * 1000 + 100 * 24 * 60 * 60), "Result expected to be in: [%s ... %s]. Actual %s" % ( now * 1000 + 100 * 24 * 60 * 60, (now + 10) * 1000 + 100 * 24 * 60 * 60, res["results"])) def test_date_add_str(self): self.query = "select date_add_str(clock_utc(), 10, 'day') as now" now = datetime.datetime.utcnow() + datetime.timedelta(days=10) res = self.run_cbq_query() expected = "%s-%02d-%02dT%02d:" % (now.year, now.month, now.day, now.hour) expected_delta = "%s-%02d-%02dT%02d:" % (now.year, now.month, now.day, now.hour + 1) self.assertTrue( res["results"][0]["now"].startswith(expected) or res["results"][0]["now"].startswith(expected_delta), "Result expected: %s. Actual %s" % (expected, res["results"])) def test_date_diff_millis(self): self.query = "select date_diff_millis(clock_millis(), date_add_millis(clock_millis(), 100, 'day'), 'day') as " \ "now " res = self.run_cbq_query() self.assertTrue(res["results"][0]["now"] == -100, "Result expected: %s. Actual %s" % (-100, res["results"])) def test_date_diff_str(self): self.query = 'select date_diff_str("2014-08-24T01:33:59", "2014-08-24T07:33:59", "minute") as now' res = self.run_cbq_query() self.assertTrue(res["results"][0]["now"] == -360, "Result expected: %s. Actual %s" % (-360, res["results"])) self.query = 'select date_diff_str("2014-08-24T01:33:59", "2014-08-24T07:33:59", "hour") as now' res = self.run_cbq_query() self.assertTrue(res["results"][0]["now"] == -6, "Result expected: %s. Actual %s" % (-6, res["results"])) def test_now(self): self.query = "select now_str() as now" now = datetime.datetime.now() today = date.today() res = self.run_cbq_query() expected = "%s-%02d-%02dT" % (today.year, today.month, today.day,) self.assertFalse("error" in str(res).lower()) def test_hours(self): self.query = 'select date_part_str(now_utc(), "hour") as hour, ' + \ 'date_part_str(now_utc(),"minute") as minute, date_part_str(' + \ 'now_utc(),"second") as sec, date_part_str(now_utc(),"millisecond") as msec' now = datetime.datetime.utcnow() res = self.run_cbq_query() self.assertTrue(res["results"][0]["hour"] == now.hour or res["results"][0]["hour"] == (now.hour + 1), "Result for hours expected: %s. Actual %s" % (now.hour, res["results"])) self.assertTrue("minute" in res["results"][0], "No minute field") self.assertTrue("sec" in res["results"][0], "No second field") self.assertTrue("msec" in res["results"][0], "No msec field") def test_where(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'select name, join_yr, join_mo, join_day from %s' % query_bucket + \ ' where date_part_str(now_str(),"month") < join_mo AND date_part_str(now_str(),"year")' + \ ' > join_yr AND date_part_str(now_str(),"day") < join_day' actual_result = self.run_cbq_query() actual_result = sorted(actual_result["results"], key=lambda doc: (doc['name'], doc['join_yr'], doc['join_mo'], doc['join_day'])) today = date.today() expected_result = [{"name": doc['name'], "join_yr": doc['join_yr'], "join_mo": doc['join_mo'], "join_day": doc['join_day']} for doc in self.full_list if doc['join_yr'] < today.year and doc['join_mo'] > today.month and doc['join_day'] > today.day] expected_result = sorted(expected_result, key=lambda doc: (doc['name'], doc['join_yr'], doc['join_mo'], doc['join_day'])) self._verify_results(actual_result, expected_result) def test_prepared_date_where(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'select name, join_yr, join_mo, join_day from %s' % query_bucket + \ ' where date_part_str(now_str(),"month") < join_mo AND date_part_str(now_str(),"year")' + \ ' > join_yr AND date_part_str(now_str(),"day") < join_day' self.prepared_common_body() def test_now_millis(self): self.query = "select now_millis() as now" now = time.time() res = self.run_cbq_query() self.assertFalse("error" in str(res).lower()) def test_str_to_millis(self): now_millis = time.time() now_time = datetime.datetime.fromtimestamp(now_millis) now_millis = now_millis * 1000 try: now_time_zone = round( (round((datetime.datetime.now() - datetime.datetime.utcnow()).total_seconds()) // 1800) // 2) except AttributeError as ex: raise Exception("Test requires python 2.7 : SKIPPING TEST") now_time_str = "%s-%02d-%02d" % (now_time.year, now_time.month, now_time.day) self.query = "select str_to_millis('%s') as now" % now_time_str res = self.run_cbq_query() self.assertTrue(res["results"][0]["now"] < now_millis and (res["results"][0]["now"] > (now_millis - 5184000000)), "Result expected to be in: [%s ... %s]. Actual %s" % ( now_millis - 5184000000, now_millis, res["results"])) def test_millis_to_str(self): now_millis = time.time() now_time = datetime.datetime.utcfromtimestamp(now_millis) expected = "%s-%02d-%02dT%02d:%02d" % (now_time.year, now_time.month, now_time.day, now_time.hour, now_time.minute) self.query = "select millis_to_utc(%s) as now" % (now_millis * 1000) res = self.run_cbq_query() self.assertTrue(res["results"][0]["now"].startswith(expected), "Result expected: %s. Actual %s" % (expected, res["results"])) def test_date_part_millis(self): now_millis = time.time() now_time = datetime.datetime.utcfromtimestamp(now_millis) now_millis = now_millis * 1000 self.query = 'select date_part_millis(%s, "hour", "UTC") as hour, ' % now_millis + \ 'date_part_millis(%s,"minute", "UTC") as minute, date_part_millis(' % now_millis + \ '%s,"second") as sec, date_part_millis(%s,"millisecond", "UTC") as msec' % (now_millis, now_millis) res = self.run_cbq_query() self.assertTrue(res["results"][0]["hour"] == now_time.hour, "Result expected: %s. Actual %s" % (now_time.hour, res["results"])) self.assertTrue(res["results"][0]["minute"] == now_time.minute, "Result expected: %s. Actual %s" % (now_time.minute, res["results"])) self.assertTrue(res["results"][0]["sec"] == now_time.second, "Result expected: %s. Actual %s" % (now_time.second, res["results"])) self.assertTrue("msec" in res["results"][0], "There are no msec in results") def test_where_millis(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select join_yr, join_mo, join_day, name from %s" % query_bucket + \ " where join_mo < 10 and join_day < 10 and str_to_millis(tostr(join_yr) || '-0'" + \ " || tostr(join_mo) || '-0' || tostr(join_day)) < now_millis()" actual_result = self.run_cbq_query() actual_result = sorted(actual_result["results"], key=lambda doc: (doc['name'], doc['join_yr'], doc['join_mo'], doc['join_day'])) expected_result = [{"name": doc['name'], "join_yr": doc['join_yr'], "join_mo": doc['join_mo'], "join_day": doc['join_day']} for doc in self.full_list if doc['join_mo'] < 10 and doc['join_day'] < 10] expected_result = sorted(expected_result, key=lambda doc: (doc['name'], doc['join_yr'], doc['join_mo'], doc['join_day'])) self._verify_results(actual_result, expected_result) def test_order_by_dates(self): self.fail_if_no_buckets() orders = ["asc", "desc"] for order in orders: for query_bucket in self.query_buckets: self.query = "select millis_to_str(str_to_millis('2010-01-01')) as date" actual_result = self.run_cbq_query() self.assertTrue(actual_result["results"][0]["date"][:10] == '2010-01-01', 'Actual result %s' % actual_result) self.query = "select join_yr, join_mo, join_day," \ " millis_to_str(str_to_millis(tostr(join_yr) || '-0' ||" + \ " tostr(join_mo) || '-0' || tostr(join_day))) as date from %s" % query_bucket + \ " where join_mo < 10 and join_day < 10 ORDER BY date %s" % order actual_result = self.run_cbq_query() actual_result = ([{"date": doc["date"][:10], "join_yr": doc['join_yr'], "join_mo": doc['join_mo'], "join_day": doc['join_day']} for doc in actual_result["results"]]) expected_result = [{"date": '%s-0%s-0%s' % (doc['join_yr'], doc['join_mo'], doc['join_day']), "join_yr": doc['join_yr'], "join_mo": doc['join_mo'], "join_day": doc['join_day']} for doc in self.full_list if doc['join_mo'] < 10 and doc['join_day'] < 10] expected_result = sorted(expected_result, key=lambda doc: (doc['date']), reverse=(order == 'desc')) self._verify_results(actual_result, expected_result) ############################################################################################## # # TYPE FNS ############################################################################################## def test_type(self): self.fail_if_no_buckets() types_list = [("name", "string"), ("tasks_points", "object"), ("some_wrong_key", "missing"), ("skills", "array"), ("VMs[0].RAM", "number"), ("true", "boolean"), ("test_rate", "number"), ("test.test[0]", "missing")] for query_bucket in self.query_buckets: for name_item, type_item in types_list: self.query = 'SELECT TYPENAME(%s) as type_output FROM %s' % ( name_item, query_bucket) actual_result = self.run_cbq_query() for doc in actual_result['results']: self.assertTrue(doc["type_output"] == type_item, "Expected type for %s: %s. Actual: %s" % ( name_item, type_item, doc["type_output"])) self.log.info("Type for %s(%s) is checked." % (name_item, type_item)) def test_check_types(self): self.fail_if_no_buckets() types_list = [("name", "ISSTR", True), ("skills[0]", "ISSTR", True), ("test_rate", "ISSTR", False), ("VMs", "ISSTR", False), ("false", "ISBOOL", True), ("join_day", "ISBOOL", False), ("VMs", "ISARRAY", True), ("VMs[0]", "ISARRAY", False), ("skills[0]", "ISARRAY", False), ("skills", "ISARRAY", True)] for query_bucket in self.query_buckets: for name_item, fn, expected_result in types_list: self.query = 'SELECT %s(%s) as type_output FROM %s' % ( fn, name_item, query_bucket) actual_result = self.run_cbq_query() for doc in actual_result['results']: self.assertTrue(doc["type_output"] == expected_result, "Expected output for fn %s( %s) : %s. Actual: %s" % ( fn, name_item, expected_result, doc["type_output"])) self.log.info("Fn %s(%s) is checked. (%s)" % (fn, name_item, expected_result)) def test_types_in_satisfy(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name FROM %s d WHERE " % query_bucket + \ "(EVERY vm IN d.VMs SATISFIES ISOBJ(vm) END) AND" + \ " ISSTR(email) ORDER BY name" if self.analytics: self.query = "SELECT name FROM %s d WHERE " % query_bucket + \ "(EVERY vm IN d.VMs SATISFIES ISOBJ(vm) ) AND" + \ " ISSTR(email) ORDER BY name" actual_result = self.run_cbq_query() expected_result = [{"name": doc['name']} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['name'])) self._verify_results(actual_result['results'], expected_result) def test_to_num(self): self.query = 'SELECT tonum("12.12") - tonum("0.12") as num' actual_result = self.run_cbq_query() self.assertTrue(actual_result['results'][0]['num'] == 12, "Expected: 12. Actual: %s" % (actual_result['results'])) self.log.info("TONUM is checked") def test_to_str(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT TOSTR(join_mo) month FROM %s" % query_bucket actual_result = self.run_cbq_query() actual_result = actual_result['results'] self.query = "SELECT REVERSE(TOSTR(join_mo)) rev_month FROM %s" % query_bucket actual_result1 = self.run_cbq_query() actual_result2 = actual_result1['results'] expected_result = [{"month": str(doc['join_mo'])} for doc in self.full_list] expected_result2 = [{"rev_month": str(doc['join_mo'])[::-1]} for doc in self.full_list] self._verify_results(actual_result, expected_result) self._verify_results(actual_result2, expected_result2) def test_to_bool(self): self.query = 'SELECT tobool("true") as boo' actual_result = self.run_cbq_query() self.assertTrue(actual_result['results'][0]['boo'], "Expected: true. Actual: %s" % (actual_result['results'])) self.log.info("TOBOOL is checked") # Test has no usages anywhere def test_to_array(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT job_title, toarray(name) as names" + \ " FROM %s" % query_bucket actual_list = self.run_cbq_query() actual_result = sorted(actual_list['results'], key=lambda doc: (doc['job_title'], doc['names'])) expected_result = [{"job_title": doc["job_title"], "names": [doc["name"]]} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['job_title'], doc['names'])) self._verify_results(actual_result, expected_result) ############################################################################################## # # CONCATENATION ############################################################################################## def test_concatenation(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT name || \" \" || job_title as employee" + \ " FROM %s" % query_bucket actual_list = self.run_cbq_query() actual_result = sorted(actual_list['results'], key=lambda doc: (doc['employee'])) expected_result = [{"employee": doc["name"] + " " + doc["job_title"]} for doc in self.full_list] expected_result = sorted(expected_result, key=lambda doc: (doc['employee'])) self._verify_results(actual_result, expected_result) def test_concatenation_where(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'SELECT name, skills' + \ ' FROM %s WHERE skills[0]=("skill" || "2010")' % query_bucket actual_list = self.run_cbq_query() self.query = 'SELECT name, skills' + \ ' FROM %s WHERE reverse(skills[0])=("0102" || "lliks")' % query_bucket actual_list1 = self.run_cbq_query() actual_result = actual_list['results'] actual_result2 = actual_list1['results'] expected_result = [{"name": doc["name"], "skills": doc["skills"]} for doc in self.full_list if doc["skills"][0] == 'skill2010'] self._verify_results(actual_result, expected_result) self._verify_results(actual_result, actual_result2) ############################################################################################## # # SPLIT ############################################################################################## def test_select_split_fn(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT SPLIT(email, '@')[0] as login" + \ " FROM %s" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"login": doc["email"].split('@')[0]} for doc in self.full_list] self._verify_results(actual_result, expected_result) def test_split_where(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'SELECT name FROM %s' % query_bucket + \ ' WHERE SPLIT(email, \'-\')[0] = SPLIT(name, \'-\')[1]' actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"]} for doc in self.full_list if doc["email"].split('-')[0] == doc["name"].split('-')[1]] self._verify_results(actual_result, expected_result) ############################################################################################## # # UNION ############################################################################################## def test_union(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: query_bucket = self.get_collection_name(query_bucket) self.query = "select name from %s union select email from %s" % (query_bucket, query_bucket) actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"]} for doc in self.full_list] expected_result.extend([{"email": doc["email"]} for doc in self.full_list]) expected_result = [dict(y) for y in set(tuple(x.items()) for x in expected_result)] self._verify_results(actual_result, expected_result) def test_prepared_union(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: query_bucket = self.get_collection_name(query_bucket) self.query = "select name from %s union select email from %s" % (query_bucket, query_bucket) self.prepared_common_body() def test_union_multiply_buckets(self): self.assertTrue(len(self.buckets) > 1, 'This test needs more than one bucket') self.query = "select name from %s union select email from %s" % (self.buckets[0].name, self.buckets[1].name) actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"]} for doc in self.full_list] expected_result.extend([{"email": doc["email"]} for doc in self.full_list]) expected_result = [dict(y) for y in set(tuple(x.items()) for x in expected_result)] self._verify_results(actual_result, expected_result) def test_union_all(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: query_bucket = self.get_collection_name(query_bucket) self.query = "select name from %s union all select email from %s" % (query_bucket, query_bucket) actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"]} for doc in self.full_list] expected_result.extend([{"email": doc["email"]} for doc in self.full_list]) self._verify_results(actual_result, expected_result) def test_union_all_multiply_buckets(self): self.assertTrue(len(self.buckets) > 1, 'This test needs more than one bucket') self.query = "select name from %s union all select email from %s" % (self.query_buckets[0], self.query_buckets[1]) actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"]} for doc in self.full_list] expected_result.extend([{"email": doc["email"]} for doc in self.full_list]) self._verify_results(actual_result, expected_result) def test_union_where(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name from %s union select email from %s where join_mo > 2" % (query_bucket, query_bucket) actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"]} for doc in self.full_list] expected_result.extend([{"email": doc["email"]} for doc in self.full_list if doc["join_mo"] > 2]) expected_result = [dict(y) for y in set(tuple(x.items()) for x in expected_result)] self._verify_results(actual_result, expected_result) def test_union_where_covering(self): created_indexes = [] ind_list = ["one", "two"] index_name = "one" self.fail_if_no_buckets() for query_bucket, bucket in zip(self.query_buckets, self.buckets): for ind in ind_list: index_name = "coveringindex{0}".format(ind) if ind == "one": self.query = "CREATE INDEX {0} ON {1}(name, email, join_mo) USING {2}".format(index_name, query_bucket, self.index_type) elif ind == "two": self.query = "CREATE INDEX {0} ON {1}(email, join_mo) USING {2}".format(index_name, query_bucket, self.index_type) self.run_cbq_query() self._wait_for_index_online(bucket, index_name) created_indexes.append(index_name) for query_bucket in self.query_buckets: self.query = "explain select name from {0} where name is not null union select email from {0} where email " \ "is not null and join_mo >2 ".format(query_bucket) if self.covering_index: self.check_explain_covering_index(index_name[0]) self.query = "select name from {0} where name is not null union select email from {0} where email is not " \ "null and join_mo >2".format(query_bucket) actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"]} for doc in self.full_list] expected_result.extend([{"email": doc["email"]} for doc in self.full_list if doc["join_mo"] > 2]) expected_result = [dict(y) for y in set(tuple(x.items()) for x in expected_result)] self._verify_results(actual_result, expected_result) for index_name in created_indexes: try: self.query = "DROP INDEX {0} ON {1} USING {2}".format(index_name, query_bucket, self.index_type) self.run_cbq_query() except Exception as e: self.log.error("Drop index failed {0}".format(str(e))) self.query = "CREATE PRIMARY INDEX ON {0}".format(query_bucket) self.run_cbq_query() self.sleep(15, 'wait for index') self.query = "select name from {0} where name is not null union select email from {0} where email is not " \ "null and join_mo >2".format(query_bucket) result = self.run_cbq_query() diffs = DeepDiff(actual_result, result['results'], ignore_order=True) if diffs: self.assertTrue(False, diffs) #self.assertEqual(actual_result, sorted(result['results'])) self.query = "DROP PRIMARY INDEX ON {0}".format(query_bucket) self.run_cbq_query() def test_union_aggr_fns(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select count(name) as names from %s union select count(email) as " \ "emails from %s" % (query_bucket, query_bucket) actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"names": len(self.full_list)}] expected_result.extend([{"emails": len(self.full_list)}]) expected_result = [dict(y) for y in set(tuple(x.items()) for x in expected_result)] self._verify_results(actual_result, expected_result) def test_union_aggr_fns_covering(self): created_indexes = [] ind_list = ["one", "two"] index_name = "one" self.fail_if_no_buckets() for query_bucket, bucket in zip(self.query_buckets, self.buckets): for ind in ind_list: index_name = "coveringindex%s" % ind if ind == "one": self.query = "CREATE INDEX %s ON %s(name, email, join_day) USING %s" % (index_name, query_bucket, self.index_type) elif ind == "two": self.query = "CREATE INDEX %s ON %s(email) USING %s" % (index_name, query_bucket, self.index_type) self.run_cbq_query() self._wait_for_index_online(bucket, index_name) created_indexes.append(index_name) for query_bucket in self.query_buckets: self.query = "explain select count(name) as names from %s where join_day is not null union select count(" \ "email) as emails from %s where email is not null" % (query_bucket, query_bucket) if self.covering_index: self.check_explain_covering_index(index_name) self.query = "select count(name) as names from %s where join_day is not null union select count(email) " \ " as emails from %s where email is not null" % (query_bucket, query_bucket) actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"names": len(self.full_list)}] expected_result.extend([{"emails": len(self.full_list)}]) expected_result = [dict(y) for y in set(tuple(x.items()) for x in expected_result)] self._verify_results(actual_result, expected_result) for index_name in created_indexes: self.query = "DROP INDEX %s ON %s USING %s" % (index_name, query_bucket, self.index_type) self.run_cbq_query() self.query = "CREATE PRIMARY INDEX ON %s" % query_bucket self.run_cbq_query() self.sleep(15, 'wait for index') self.query = "select count(name) as names from %s where join_day is not null union select count(email) " \ " as emails from %s where email is not null" % ( query_bucket, query_bucket) result = self.run_cbq_query() self.assertEqual(actual_result, sorted(result['results'])) self.query = "DROP PRIMARY INDEX ON %s" % query_bucket self.run_cbq_query() # ############# META NEW ################### def test_meta_basic(self): created_indexes = [] ind_list = ["one"] index_name = "one" self.fail_if_no_buckets() for query_bucket, bucket in zip(self.query_buckets, self.buckets): for ind in ind_list: index_name = "metaindex%s" % ind if ind == "one": self.query = "CREATE INDEX %s ON %s(meta().id,meta().cas) USING %s" % ( index_name, query_bucket, self.index_type) self.run_cbq_query() self._wait_for_index_online(bucket, index_name) created_indexes.append(index_name) for query_bucket, bucket in zip(self.query_buckets, self.buckets): self.query = "explain select meta().id, meta().cas from {0} where meta().id is not null order by meta(" \ ").id limit 10".format(query_bucket) if self.covering_index: self.check_explain_covering_index(index_name[0]) self.query = "select meta().id, meta().cas from {0} where meta().id is not null order by " \ "meta().id limit 10".format(query_bucket) actual_list = self.run_cbq_query() actual_result = actual_list['results'] for index_name in created_indexes: self.query = "DROP INDEX %s ON %s USING %s" % (index_name, query_bucket, self.index_type) self.run_cbq_query() self.covering_index = False self.query = "CREATE PRIMARY INDEX ON %s" % query_bucket self.run_cbq_query() self._wait_for_index_online(bucket, '#primary') self.query = "select meta().id, meta().cas from {0} use index(`#primary`) where meta().id is not null " \ "order by meta().id limit 10".format(query_bucket) expected_list = self.run_cbq_query() diffs = DeepDiff(actual_result, expected_list['results'], ignore_order=True) if diffs: self.assertTrue(False, diffs) self.query = "DROP PRIMARY INDEX ON %s" % query_bucket self.run_cbq_query() def test_meta_where(self): created_indexes = [] ind_list = ["one"] index_name = "one" self.fail_if_no_buckets() for query_bucket, bucket in zip(self.query_buckets, self.buckets): for ind in ind_list: index_name = "meta_where%s" % ind if ind == "one": self.query = "CREATE INDEX {0} ON {1}(meta().id,meta().cas) where meta().id like " \ "'query-testemployee6%' USING {2}".format(index_name, query_bucket, self.index_type) self.run_cbq_query() self._wait_for_index_online(bucket, index_name) created_indexes.append(index_name) for query_bucket, bucket in zip(self.query_buckets, self.buckets): self.query = "explain select meta().id, meta().cas from {0} where meta().id like 'query-testemployee6%' " \ "order by meta().id limit 10".format( query_bucket) if self.covering_index: self.check_explain_covering_index(index_name[0]) self.query = "select meta().id, meta().cas from {0} where meta().id like 'query-testemployee6%' order by " \ "meta().id limit 10".format(query_bucket) actual_list = self.run_cbq_query() actual_result = actual_list['results'] for index_name in created_indexes: self.query = "DROP INDEX %s ON %s USING %s" % (index_name, query_bucket, self.index_type) self.run_cbq_query() self.covering_index = False self.query = "CREATE PRIMARY INDEX ON %s" % query_bucket self.run_cbq_query() self._wait_for_index_online(bucket, '#primary') self.query = "select meta().id, meta().cas from {0} where meta().id like 'query-testemployee6%' order by " \ "meta().id limit 10".format(query_bucket) expected_list = self.run_cbq_query() diffs = DeepDiff(actual_result, expected_list['results'], ignore_order=True) if diffs: self.assertTrue(False, diffs) self.query = "DROP PRIMARY INDEX ON %s" % query_bucket self.run_cbq_query() def test_meta_ambiguity(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "create index idx on %s(META())" % query_bucket self.run_cbq_query() self.query = "create index idx2 on {0}(META())".format(query_bucket) self.run_cbq_query() self.query = "SELECT META() as meta_c FROM %s ORDER BY meta_c limit 10" % query_bucket actual_result = self.run_cbq_query() self.assertTrue(actual_result['status'] == "success") self.query = "SELECT META(test) as meta_c FROM %s as test ORDER BY meta_c limit 10" % query_bucket actual_result = self.run_cbq_query() self.assertTrue(actual_result['status'] == "success") self.query = "SELECT META(t1).id as id FROM " + self.query_buckets[0] + " t1 JOIN " + \ self.query_buckets[0] + " t2 ON KEYS t1.id;" self.assertTrue(actual_result['status'] == "success") self.query = "drop index idx ON %s" % query_bucket self.run_cbq_query() self.query = "drop index idx2 ON %s" % query_bucket self.run_cbq_query() def test_meta_where_greater_than(self): created_indexes = [] ind_list = ["one"] index_name = "one" self.fail_if_no_buckets() for query_bucket, bucket in zip(self.query_buckets, self.buckets): for ind in ind_list: index_name = "meta_where%s" % ind if ind == "one": self.query = "CREATE INDEX {0} ON {1}(meta().id,meta().cas) where meta().id >10 USING {2}".format( index_name, query_bucket, self.index_type) self.run_cbq_query() self._wait_for_index_online(bucket, index_name) created_indexes.append(index_name) for query_bucket, bucket in zip(self.query_buckets, self.buckets): self.query = "explain select meta().id, meta().cas from {0} where meta().id >10 order by meta().id".format( query_bucket) if self.covering_index: self.check_explain_covering_index(index_name[0]) self.query = "select meta().id, meta().cas from {0} where meta().id >10 order by meta().id limit 10".format( query_bucket) actual_list = self.run_cbq_query() actual_result = actual_list['results'] for index_name in created_indexes: self.query = "DROP INDEX %s ON %s USING %s" % (index_name, query_bucket, self.index_type) self.run_cbq_query() self.covering_index = False self.query = "CREATE PRIMARY INDEX ON %s" % query_bucket self.run_cbq_query() self._wait_for_index_online(bucket, '#primary') self.query = "select meta().id, meta().cas from {0} use index(`#primary`) where meta().id > 10 order by " \ "meta().id limit 10".format(query_bucket) expected_list = self.run_cbq_query() diffs = DeepDiff(actual_result, expected_list['results'], ignore_order=True) if diffs: self.assertTrue(False, diffs) self.query = "DROP PRIMARY INDEX ON %s" % query_bucket self.run_cbq_query() def test_meta_partial(self): created_indexes = [] ind_list = ["one"] index_name = "one" self.fail_if_no_buckets() for query_bucket, bucket in zip(self.query_buckets, self.buckets): for ind in ind_list: index_name = "meta_where%s" % ind if ind == "one": self.query = "CREATE INDEX {0} ON {1}(meta().id, name) where meta().id >10 USING {2}".format( index_name, query_bucket, self.index_type) # if self.gsi_type: # self.query += "WITH {'index_type': 'memdb'}" self.run_cbq_query() self._wait_for_index_online(bucket, index_name) created_indexes.append(index_name) for query_bucket, bucket in zip(self.query_buckets, self.buckets): self.query = "explain select meta().id, name from {0} where meta().id >10 and name is not null order by " \ "meta().id limit 10".format(query_bucket) if self.covering_index: self.check_explain_covering_index(index_name[0]) self.query = "select meta().id, name from {0} where meta().id >10 and name is not null order by " \ "meta().id limit 10".format(query_bucket) actual_list = self.run_cbq_query() actual_result = actual_list['results'] for index_name in created_indexes: self.query = "DROP INDEX %s ON %s USING %s" % (index_name, query_bucket, self.index_type) self.run_cbq_query() self.covering_index = False self.query = "CREATE PRIMARY INDEX ON %s" % query_bucket self.run_cbq_query() self._wait_for_index_online(bucket, '#primary') self.query = "select meta().id, name from {0} use index(`#primary`) where meta().id > 10 and name is not " \ "null order by meta().id limit 10".format(query_bucket) expected_list = self.run_cbq_query() diffs = DeepDiff(actual_result, expected_list['results'], ignore_order=True) if diffs: self.assertTrue(False, diffs) self.query = "DROP PRIMARY INDEX ON %s" % query_bucket self.run_cbq_query() def test_meta_non_supported(self): created_indexes = [] ind_list = ["one"] index_name = "one" self.fail_if_no_buckets() for query_bucket in self.query_buckets: for ind in ind_list: index_name = "meta_cas_%s" % ind if ind == "one": queries_errors = {'CREATE INDEX ONE ON ' + self.query_buckets[0] + ' (meta().cas) using GSI': ( 'syntax error', 3000), 'CREATE INDEX ONE ON ' + self.query_buckets[0] + ' (meta().flags) using GSI': ( 'syntax error', 3000), 'CREATE INDEX ONE ON ' + self.query_buckets[ 0] + ' (meta().expiration) using GSI': ( 'syntax error', 3000), 'CREATE INDEX ONE ON ' + self.query_buckets[0] + ' (meta().cas) using VIEW': ( 'syntax error', 3000)} def test_meta_negative_namespace(self): created_indexes = [] ind_list = ["one"] index_name = "one" self.fail_if_no_buckets() for query_bucket in self.query_buckets: for ind in ind_list: index_name = "meta_cas_%s" % ind if ind == "one": queries_errors = { 'CREATE INDEX TWO ON ' + self.query_buckets[0] + ' (meta(invalid).id) using GSI': ( 'syntax error', 3000), 'CREATE INDEX THREE ON ' + self.query_buckets[0] + ' (meta(invalid).id) using VIEW': ( 'syntax error', 3000), 'CREATE INDEX FOUR ON ' + self.query_buckets[0] + ' (meta()) using GSI': ('syntax error', 3000), 'CREATE INDEX FIVE ON ' + self.query_buckets[0] + ' (meta()) using VIEW': ( 'syntax error', 3000)} self.negative_common_body(queries_errors) # ####################### META NEW END ###################################### def test_intersect(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name from %s intersect select name from %s s where s.join_day>5" % ( query_bucket, query_bucket) actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"]} for doc in self.full_list if doc['join_day'] > 5] expected_result = [dict(y) for y in set(tuple(x.items()) for x in expected_result)] self._verify_results(actual_result, expected_result) def test_intersect_covering(self): created_indexes = [] ind_list = ["one", "two"] index_name = "one" self.fail_if_no_buckets() for query_bucket, bucket in zip(self.query_buckets, self.buckets): for ind in ind_list: index_name = "coveringindex{0}".format(ind) if ind == "one": self.query = "CREATE INDEX {0} ON {1}(job_title, name) USING {2}".format(index_name, query_bucket, self.index_type) elif ind == "two": self.query = "CREATE INDEX {0} ON {1}(join_day, name) USING {2}".format(index_name, query_bucket, self.index_type) self.run_cbq_query() self._wait_for_index_online(bucket, index_name) created_indexes.append(index_name) for query_bucket, bucket in zip(self.query_buckets, self.buckets): self.query = "explain select name from {0} where job_title='Engineer' intersect select name from {0} s where s.join_day>5".format(query_bucket) if self.covering_index: self.check_explain_covering_index(index_name) self.query = "select name from {0} where job_title='Engineer' intersect select name from {0} s where s.join_day>5".format(query_bucket) actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"]} for doc in self.full_list if doc['join_day'] > 5] expected_result = [dict(y) for y in set(tuple(x.items()) for x in expected_result)] self._verify_results(actual_result, expected_result) for ind in ind_list: index_name = "coveringindex{0}".format(ind) try: self.query = "DROP INDEX {0} ON {1} USING {2}".format(index_name, query_bucket, self.index_type) self.run_cbq_query() except Exception as e: self.log.error("Drop index failed {0}".format(str(e))) self.query = "CREATE PRIMARY INDEX ON {0}".format(query_bucket) self.run_cbq_query() self._wait_for_index_online(bucket, '#primary') self.query = "select name from {0} where job_title='Engineer' intersect select name from {0} s where s.join_day>5".format(query_bucket, query_bucket) expected_list = self.run_cbq_query() diffs = DeepDiff(actual_result, expected_list['results'], ignore_order=True) if diffs: self.assertTrue(False, diffs) self.query = "DROP PRIMARY INDEX ON {0}".format(query_bucket) self.run_cbq_query() def test_intersect_all(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name from %s intersect all select name from %s s where s.join_day>5" % ( query_bucket, query_bucket) actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"]} for doc in self.full_list if doc['join_day'] > 5] self._verify_results(actual_result, expected_result) def test_prepared_intersect(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name from %s intersect all select name from %s s where s.join_day>5" % ( query_bucket, query_bucket) self.prepared_common_body() def test_except_secondsetempty(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "drop primary index on %s USING %s" % (query_bucket, self.primary_indx_type) self.run_cbq_query() try: self.query = "(select id keyspace_id from system:keyspaces) except (select indexes.keyspace_id from " \ "system:indexes) " actual_list = self.run_cbq_query() bucket_names = [] for bucket in self.buckets: bucket_names.append(bucket.name) count = 0 for _ in self.query_buckets: if actual_list['results'][count]['keyspace_id'] in bucket_names: count += 1 else: self.log.error("Wrong keyspace id returned or empty keyspace id returned") finally: for query_bucket in self.query_buckets: self.query = "create primary index on %s" % query_bucket self.run_cbq_query() def test_except(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name from %s except select name from %s s where s.join_day>5" % ( query_bucket, query_bucket) actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"]} for doc in self.full_list if not doc['join_day'] > 5] expected_result = [dict(y) for y in set(tuple(x.items()) for x in expected_result)] self._verify_results(actual_result, expected_result) def test_except_all(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name from %s except all select name from %s s where s.join_day>5" % ( query_bucket, query_bucket) actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"]} for doc in self.full_list if not doc['join_day'] > 5] self._verify_results(actual_result, expected_result) ############################################################################################## # # WITHIN ############################################################################################## def test_within_list_object(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name, VMs from %s WHERE 5 WITHIN VMs" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"], "VMs": doc["VMs"]} for doc in self.full_list if len([vm for vm in doc["VMs"] if vm["RAM"] == 5])] self._verify_results(actual_result, expected_result) def test_prepared_within_list_object(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: query_bucket = self.get_collection_name(query_bucket) self.query = "select name, VMs from %s WHERE 5 WITHIN VMs" % query_bucket self.prepared_common_body() def test_within_list_of_lists(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name, VMs from %s where name within [['employee-2', 'employee-4']," \ " ['employee-5']] " % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"], "VMs": doc["VMs"]} for doc in self.full_list if doc["name"] in ['employee-2', 'employee-4', 'employee-5']] self._verify_results(actual_result, expected_result) def test_within_object(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name, tasks_points from %s WHERE 1 WITHIN tasks_points" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"], "tasks_points": doc["tasks_points"]} for doc in self.full_list if doc["tasks_points"]["task1"] == 1 or doc["tasks_points"]["task2"] == 1] self._verify_results(actual_result, expected_result) def test_within_array(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = " select name, skills from %s where 'skill2010' within skills" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"], "skills": doc["skills"]} for doc in self.full_list if 'skill2010' in doc["skills"]] self._verify_results(actual_result, expected_result) ############################################################################################## # # RAW ############################################################################################## def test_raw(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select raw name from %s " % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] self.query = "select raw reverse(reverse(name)) from %s " % query_bucket actual_list1 = self.run_cbq_query() actual_result1 = actual_list1['results'] expected_result = [doc["name"] for doc in self.full_list] self._verify_results(actual_result, expected_result) self._verify_results(actual_result, actual_result1) def test_raw_limit(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select raw skills[0] from %s limit 5" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [doc["skills"][0] for doc in self.full_list][:5] self._verify_results(actual_result, expected_result) def test_raw_order(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select raw name from {0} order by name {1}".format(query_bucket, "desc") actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [doc["name"] for doc in self.full_list] diffs = DeepDiff(actual_result, expected_result, ignore_order=True) if diffs: self.assertTrue(False, diffs) self.query = "select raw name from {0} order by name {1}".format(query_bucket, "asc") actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [doc["name"] for doc in self.full_list] self._verify_results(actual_result, expected_result) self.query = "select raw meta().id from {0} order by meta().id {1}".format(query_bucket, "asc") actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = sorted(actual_result) self.assertEqual(actual_result, expected_result) self.query = "select raw meta().id from {0} order by meta().id {1}".format(query_bucket, "desc") actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = sorted(actual_result, reverse=True) self.assertEqual(actual_result, expected_result) def test_push_limit(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = 'insert into %s(KEY, VALUE) VALUES ("f01", {"f1":"f1"})' % query_bucket self.run_cbq_query() self.query = 'insert into %s(KEY, VALUE) VALUES ("f02", {"f1":"f1","f2":"f2"})' % query_bucket self.run_cbq_query() self.query = 'create index if1 on %s(f1)' % query_bucket self.query = 'select q.id, q.f1,q.f2 from (select meta().id, f1,f2 from %s where f1="f1") q where q.f2 = ' \ '"f2" limit 1' % query_bucket result = self.run_cbq_query() self.assertTrue(result['metrics']['resultCount'] == 1) self.query = 'delete from %s use keys["f01","f02"]' % query_bucket self.run_cbq_query() ############################################################################################## # # Number fns ############################################################################################## # This test has no usages anywhere def test_abs(self): for query_bucket in self.query_buckets: self.query = "select join_day from %s where join_day > abs(-10)" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [doc["join_day"] for doc in self.full_list if doc["join_day"] > abs(-10)] self._verify_results(actual_result, expected_result) # This test has no usages anywhere def test_acos(self): self.query = "select degrees(acos(0.5))" actual_list = self.run_cbq_query() expected_result = [{'$1': 60}] self._verify_results(actual_list['results'], expected_result) # Test has no usages anywhere def test_asin(self): self.query = "select degrees(asin(0.5))" actual_list = self.run_cbq_query() expected_result = [{'$1': 30}] self._verify_results(actual_list['results'], expected_result) # Test has no usages anywhere def test_tan(self): self.query = "select tan(radians(45))" actual_list = self.run_cbq_query() expected_result = [{'$1': 1}] self._verify_results(actual_list['results'], expected_result) # This test has no usages anywhere def test_ln(self): self.query = "select ln(10) = ln(2) + ln(5)" actual_list = self.run_cbq_query() expected_result = [{'$1': True}] self._verify_results(actual_list['results'], expected_result) # This test has no usages anywhere def test_power(self): self.query = "select power(sin(radians(33)), 2) + power(cos(radians(33)), 2)" actual_list = self.run_cbq_query() expected_result = [{'$1': 1}] self._verify_results(actual_list['results'], expected_result) # Test has no usages anywhere def test_sqrt(self): self.query = "select sqrt(9)" actual_list = self.run_cbq_query() expected_result = [{'$1': 3}] self._verify_results(actual_list['results'], expected_result) # This test has no uses anywhere def test_sign(self): self.query = "select sign(-5)" actual_list = self.run_cbq_query() expected_result = [{'$1': -1}] self._verify_results(actual_list['results'], expected_result) self.query = "select sign(5)" actual_list = self.run_cbq_query() expected_result = [{'$1': 1}] self._verify_results(actual_list['results'], expected_result) self.query = "select sign(0)" actual_list = self.run_cbq_query() expected_result = [{'$1': 0}] self._verify_results(actual_list['results'], expected_result) ############################################################################################## # # CONDITIONAL FNS ############################################################################################## def test_nanif(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select join_day, join_mo, NANIF(join_day, join_mo) as equality" + \ " from %s" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"join_day": doc["join_day"], "join_mo": doc["join_mo"], "equality": doc["join_day"] if doc["join_day"] != doc["join_mo"] else 'NaN'} for doc in self.full_list] self._verify_results(actual_result, expected_result) def test_posinf(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select join_day, join_mo, POSINFIF(join_day, join_mo) as equality" + \ " from %s" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"join_day": doc["join_day"], "join_mo": doc["join_mo"], "equality": doc["join_day"] if doc["join_day"] != doc["join_mo"] else '+Infinity'} for doc in self.full_list] self._verify_results(actual_result, expected_result) ############################################################################################## # # String FUNCTIONS ############################################################################################## def test_uuid(self): self.query = "select uuid() as uuid" actual_list = self.run_cbq_query() self.assertTrue('uuid' in actual_list['results'][0] and actual_list['results'][0]['uuid'], 'UUid is not working') def test_string_fn_negative(self): queries_errors = {'select name from %s when contains(VMs, "Sale")': ('syntax error', 3000), 'select TITLE(test_rate) as OS from %s': ('syntax error', 3000), 'select REPEAT(name, -2) as name from %s': ('syntax error', 3000), 'select REPEAT(name, a) as name from %s': ('syntax error', 3000), } self.negative_common_body(queries_errors) def test_contains(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name from %s where contains(job_title, 'Sale')" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] self.query = "select name from %s where contains(reverse(job_title), reverse('Sale'))" % query_bucket actual_list1 = self.run_cbq_query() actual_result1 = actual_list1['results'] diffs = DeepDiff(actual_result, actual_result1, ignore_order=True) if diffs: self.assertTrue(False, diffs) expected_result = [{"name": doc["name"]} for doc in self.full_list if doc['job_title'].find('Sale') != -1] self._verify_results(actual_result, expected_result) def test_initcap(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select INITCAP(VMs[0].os) as OS from %s" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"OS": (doc["VMs"][0]["os"][0].upper() + doc["VMs"][0]["os"][1:])} for doc in self.full_list] self._verify_results(actual_result, expected_result) def test_title(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select TITLE(VMs[0].os) as OS from %s" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] self.query = "select TITLE(REVERSE(VMs[0].os)) as rev_os from %s" % query_bucket actual_list1 = self.run_cbq_query() actual_result1 = actual_list1['results'] expected_result = [{"OS": (doc["VMs"][0]["os"][0].upper() + doc["VMs"][0]["os"][1:])} for doc in self.full_list] expected_result1 = [{"rev_os": (doc["VMs"][0]["os"][::-1][0].upper() + doc["VMs"][0]["os"][::-1][1:])} for doc in self.full_list] self._verify_results(actual_result, expected_result) self._verify_results(actual_result1, expected_result1) def test_prepared_title(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select TITLE(VMs[0].os) as OS from %s" % query_bucket self.prepared_common_body() def test_position(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select POSITION(VMs[1].name, 'vm') pos from %s" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"pos": (doc["VMs"][1]["name"].find('vm'))} for doc in self.full_list] self._verify_results(actual_result, expected_result) self.query = "select POSITION(VMs[1].name, 'server') pos from %s" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"pos": (doc["VMs"][1]["name"].find('server'))} for doc in self.full_list] self._verify_results(actual_result, expected_result) test_word = 'california' for letter in test_word: actual = self.run_position_query(test_word, letter) expected = test_word.find(letter) self.assertEqual(actual, expected) letter = '' actual = self.run_position_query(test_word, letter) expected = test_word.find(letter) self.assertEqual(actual, expected) letter = 'd' actual = self.run_position_query(test_word, letter) expected = test_word.find(letter) self.assertEqual(actual, expected) def test_position0(self): test_word = 'california' for letter in test_word: actual = self.run_position_query(test_word, letter, position_type='0') expected = test_word.find(letter) self.assertEqual(actual, expected) letter = '' actual = self.run_position_query(test_word, letter, position_type='0') expected = test_word.find(letter) self.assertEqual(actual, expected) letter = 'd' actual = self.run_position_query(test_word, letter, position_type='0') expected = test_word.find(letter) self.assertEqual(actual, expected) def test_position1(self): test_word = 'california' for letter in test_word: actual = self.run_position_query(test_word, letter, position_type='1') expected = test_word.find(letter) + 1 self.assertEqual(actual, expected) letter = '' actual = self.run_position_query(test_word, letter, position_type='1') expected = test_word.find(letter) + 1 self.assertEqual(actual, expected) letter = 'd' actual = self.run_position_query(test_word, letter, position_type='1') expected = test_word.find(letter) + 1 self.assertEqual(actual, expected) def test_regex_contains(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select email from %s where REGEXP_CONTAINS(email, '-m..l')" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] self.query = "select email from %s where REGEXP_CONTAINS(reverse(email), 'l..m-')" % query_bucket actual_list1 = self.run_cbq_query() actual_result1 = actual_list1['results'] diffs = DeepDiff(actual_result, actual_result1, ignore_order=True) if diffs: self.assertTrue(False, diffs) actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"email": doc["email"]} for doc in self.full_list if len(re.compile('-m..l').findall(doc['email'])) > 0] self._verify_results(actual_result, expected_result) def test_regex_like(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select email from %s where REGEXP_LIKE(email, '.*-mail.*')" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"email": doc["email"]} for doc in self.full_list if re.compile('.*-mail.*').search(doc['email'])] self._verify_results(actual_result, expected_result) def test_regex_position(self): test_word = 'california' for letter in test_word: actual = self.run_regex_query(test_word, letter) expected = test_word.find(letter) self.assertEqual(actual, expected) letter = '' actual = self.run_regex_query(test_word, letter) expected = test_word.find(letter) self.assertEqual(actual, expected) letter = 'd' actual = self.run_regex_query(test_word, letter) expected = test_word.find(letter) self.assertEqual(actual, expected) def test_regex_position0(self): test_word = 'california' for letter in test_word: actual = self.run_regex_query(test_word, letter, regex_type='0') expected = test_word.find(letter) self.assertEqual(actual, expected) letter = '' actual = self.run_regex_query(test_word, letter, regex_type='0') expected = test_word.find(letter) self.assertEqual(actual, expected) letter = 'd' actual = self.run_regex_query(test_word, letter, regex_type='0') expected = test_word.find(letter) self.assertEqual(actual, expected) def test_regex_position1(self): test_word = 'california' for letter in test_word: actual = self.run_regex_query(test_word, letter, regex_type='1') expected = test_word.find(letter) + 1 self.assertEqual(actual, expected) letter = '' actual = self.run_regex_query(test_word, letter, regex_type='1') expected = test_word.find(letter) + 1 self.assertEqual(actual, expected) letter = 'd' actual = self.run_regex_query(test_word, letter, regex_type='1') expected = test_word.find(letter) self.assertEqual(actual, expected) def test_regex_replace(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name, REGEXP_REPLACE(email, '-mail', 'domain') as mail from %s" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"], "mail": doc["email"].replace('-mail', 'domain')} for doc in self.full_list] self._verify_results(actual_result, expected_result) self.query = "select name, REGEXP_REPLACE(email, 'e', 'a', 2) as mail from %s" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"], "mail": doc["email"].replace('e', 'a', 2)} for doc in self.full_list] self._verify_results(actual_result, expected_result) def test_replace(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name, REPLACE(email, 'a', 'e', 1) as mail from %s" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"], "mail": doc["email"].replace('a', 'e', 1)} for doc in self.full_list] self._verify_results(actual_result, expected_result) def test_repeat(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select REPEAT(name, 2) as name from %s" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"] * 2} for doc in self.full_list] self._verify_results(actual_result, expected_result) ############################################################################################## # # LET ############################################################################################## def test_let_nums(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select test_r, test_r > 2 compare from %s let test_r = (test_rate / 2)" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"test_r": doc["test_rate"] / 2, "compare": (doc["test_rate"] / 2) > 2} for doc in self.full_list] self._verify_results(actual_result, expected_result) def test_prepared_let_nums(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select test_r, test_r > 2 compare from %s let test_r = (test_rate / 2)" % query_bucket self.prepared_common_body() def test_let_string(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "select name, join_date as date from %s let join_date = tostr(join_yr) || '-' || tostr(" \ "join_mo)" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] expected_result = [{"name": doc["name"], "date": '%s-%s' % (doc['join_yr'], doc['join_mo'])} for doc in self.full_list] self._verify_results(actual_result, expected_result) self.query = "select name, join_date as date from %s let join_date = reverse(tostr(join_yr)) || '-' || " \ "reverse(tostr(join_mo)) order by name, meta().id limit 10" % query_bucket actual_list2 = self.run_cbq_query() actual_result2 = actual_list2['results'] expected_result2 = [{'date': '1102-9', 'name': 'employee-1'}, {'date': '1102-9', 'name': 'employee-1'}, {'date': '1102-9', 'name': 'employee-1'}, {'date': '1102-9', 'name': 'employee-1'}, {'date': '1102-9', 'name': 'employee-1'}, {'date': '1102-9', 'name': 'employee-1'}, {'date': '0102-4', 'name': 'employee-1'}, {'date': '0102-4', 'name': 'employee-1'}, {'date': '0102-4', 'name': 'employee-1'}, {'date': '0102-4', 'name': 'employee-1'}] self._verify_results(actual_result2, expected_result2) def test_letting(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT join_mo, sum_test from %s WHERE join_mo>7 group by join_mo letting sum_test = sum(" \ "tasks_points.task1)" % query_bucket if self.analytics: self.query = "SELECT d.join_mo, sum_test from %s d WHERE d.join_mo>7 group by d.join_mo letting " \ "sum_test = sum(d.tasks_points.task1)" % query_bucket actual_list = self.run_cbq_query() actual_result = actual_list['results'] tmp_groups = {doc['join_mo'] for doc in self.full_list if doc['join_mo'] > 7} expected_result = [{"join_mo": group, "sum_test": sum([x["tasks_points"]["task1"] for x in self.full_list if x["join_mo"] == group])} for group in tmp_groups] self._verify_results(actual_result, expected_result) def test_prepared_letting(self): self.fail_if_no_buckets() for query_bucket in self.query_buckets: self.query = "SELECT join_mo, sum_test from %s WHERE join_mo>7 group by join_mo letting sum_test = sum(" \ "tasks_points.task1)" % query_bucket self.prepared_common_body() # https://issues.couchbase.com/browse/MB-26086 def check_special_symbols(self): self.fail_if_no_buckets() symbols = ['~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '-', '+', '=', '{', '[', '}', ']', '|', '.', ':', ';', '"', '<', ',', '>', '.', '?', '/'] errors_simple = {} errors_complex = {} query = "INSERT INTO " + self.query_buckets[0] + " VALUES ('simple', {" for i in range(len(symbols)): query += "'a" + symbols[i] + "b':1" if i < len(symbols) - 1: query += "," query += "})" self.run_cbq_query(query) for i in range(len(symbols)): query = "SELECT `a" + symbols[i] + "b` FROM " + self.query_buckets[0] + " USE KEYS ['simple'] WHERE `a" + \ symbols[i] + "b` IS NOT MISSING" result = self.run_cbq_query(query) if result['metrics']['resultCount'] < 1: errors_simple[symbols[i]] = query # Assuming I have only 3 special characters: ~!@ the resulting query will be like # INSERT INTO default VALUES ('complex', {'a~b':{'a~b':12, 'a!b':12, 'a@b':12}, # 'a!b':{'a~b':12, 'a!b':12, 'a@b':12}, # 'a@b':{'a~b':12, 'a!b':12, 'a@b':12 }}) query = "INSERT INTO " + self.query_buckets[0] + " VALUES ('complex', {" for i in range(len(symbols)): query += "'a" + symbols[i] + "b':{" for j in range(len(symbols)): query += "'a" + symbols[j] + "b':12" if j < len(symbols) - 1: query += "," else: query += "}" if i < len(symbols) - 1: query += "," query += "})" self.run_cbq_query(query) for i in range(len(symbols)): for j in range(len(symbols)): query = "SELECT `a" + symbols[i] + "b`.`a" + symbols[j] + \ "b` FROM " + self.query_buckets[0] + " USE KEYS ['complex'] WHERE `a" + symbols[i] + \ "b`.`a" + symbols[j] + "b` IS NOT MISSING" result = self.run_cbq_query(query) if result['metrics']['resultCount'] < 1: errors_complex[str(symbols[i]) + str(symbols[j])] = query self.assertEqual(len(errors_simple) + len(errors_complex), 0)
from __future__ import annotations import random from typing import Match import aiosqlite from bot.config import Config from bot.data import command from bot.data import esc from bot.data import format_msg from bot.permissions import is_moderator from bot.permissions import is_subscriber async def ensure_giveaway_tables_exist(db: aiosqlite.Connection) -> None: await db.execute( 'CREATE TABLE IF NOT EXISTS giveaway (' ' active BIT NOT NULL,' ' PRIMARY KEY (active)' ')', ) await db.execute( 'CREATE TABLE IF NOT EXISTS giveaway_users (user TEXT NOT NULL)', ) await db.commit() @command('!giveawaystart', secret=True) async def givewawaystart(config: Config, match: Match[str]) -> str | None: if not is_moderator(match) and match['user'] != match['channel']: return None async with aiosqlite.connect('db.db') as db: await ensure_giveaway_tables_exist(db) await db.execute('INSERT OR REPLACE INTO giveaway VALUES (1)') await db.commit() return format_msg( match, 'giveaway started! use !giveaway to enter (subs only)', ) @command('!giveaway', secret=True) async def giveaway(config: Config, match: Match[str]) -> str: if not is_subscriber(match): return format_msg(match, 'not a subscriber! subscribe to enter') async with aiosqlite.connect('db.db') as db: await ensure_giveaway_tables_exist(db) async with db.execute('SELECT active FROM giveaway') as cursor: row = await cursor.fetchone() if row is None or not row[0]: return format_msg(match, 'no current giveaway active!') await ensure_giveaway_tables_exist(db) query = 'INSERT OR REPLACE INTO giveaway_users VALUES (?)' await db.execute(query, (match['user'],)) await db.commit() return format_msg(match, f'{esc(match['user'])} has been entered!') @command('!giveawayend', secret=True) async def giveawayend(config: Config, match: Match[str]) -> str | None: if not is_moderator(match) and match['user'] != match['channel']: return None async with aiosqlite.connect('db.db') as db: await ensure_giveaway_tables_exist(db) async with db.execute('SELECT active FROM giveaway') as cursor: row = await cursor.fetchone() if row is None or not row[0]: return format_msg(match, 'no current giveaway active!') query = 'SELECT user FROM giveaway_users' async with db.execute(query) as cursor: users = [user for user, in await cursor.fetchall()] if users: await db.execute('INSERT OR REPLACE INTO giveaway VALUES (0)') await db.commit() await db.execute('DROP TABLE giveaway_users') await db.execute('DROP TABLE giveaway') await db.commit() if not users: return format_msg(match, 'no users entered giveaway!') winner = random.choice(users) return format_msg(match, f'!giveaway winner is {esc(winner)}')
from __future__ import annotations import random from typing import Match import aiosqlite from bot.config import Config from bot.data import command from bot.data import esc from bot.data import format_msg from bot.permissions import is_moderator from bot.permissions import is_subscriber async def ensure_giveaway_tables_exist(db: aiosqlite.Connection) -> None: await db.execute( 'CREATE TABLE IF NOT EXISTS giveaway (' ' active BIT NOT NULL,' ' PRIMARY KEY (active)' ')', ) await db.execute( 'CREATE TABLE IF NOT EXISTS giveaway_users (user TEXT NOT NULL)', ) await db.commit() @command('!giveawaystart', secret=True) async def givewawaystart(config: Config, match: Match[str]) -> str | None: if not is_moderator(match) and match['user'] != match['channel']: return None async with aiosqlite.connect('db.db') as db: await ensure_giveaway_tables_exist(db) await db.execute('INSERT OR REPLACE INTO giveaway VALUES (1)') await db.commit() return format_msg( match, 'giveaway started! use !giveaway to enter (subs only)', ) @command('!giveaway', secret=True) async def giveaway(config: Config, match: Match[str]) -> str: if not is_subscriber(match): return format_msg(match, 'not a subscriber! subscribe to enter') async with aiosqlite.connect('db.db') as db: await ensure_giveaway_tables_exist(db) async with db.execute('SELECT active FROM giveaway') as cursor: row = await cursor.fetchone() if row is None or not row[0]: return format_msg(match, 'no current giveaway active!') await ensure_giveaway_tables_exist(db) query = 'INSERT OR REPLACE INTO giveaway_users VALUES (?)' await db.execute(query, (match['user'],)) await db.commit() return format_msg(match, f'{esc(match["user"])} has been entered!') @command('!giveawayend', secret=True) async def giveawayend(config: Config, match: Match[str]) -> str | None: if not is_moderator(match) and match['user'] != match['channel']: return None async with aiosqlite.connect('db.db') as db: await ensure_giveaway_tables_exist(db) async with db.execute('SELECT active FROM giveaway') as cursor: row = await cursor.fetchone() if row is None or not row[0]: return format_msg(match, 'no current giveaway active!') query = 'SELECT user FROM giveaway_users' async with db.execute(query) as cursor: users = [user for user, in await cursor.fetchall()] if users: await db.execute('INSERT OR REPLACE INTO giveaway VALUES (0)') await db.commit() await db.execute('DROP TABLE giveaway_users') await db.execute('DROP TABLE giveaway') await db.commit() if not users: return format_msg(match, 'no users entered giveaway!') winner = random.choice(users) return format_msg(match, f'!giveaway winner is {esc(winner)}')