text:
#Imports
import logging
import discord
from discord.ext import commands
from discord_slash import SlashCommand, SlashContext
import os
from dotenv import load_dotenv
from PIL import Image
import numpy
import cv2
from copy import deepcopy
from moviepy.editor import VideoFileClip
import random

# pylint: disable=no-member

#Load Bot
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
slash = SlashCommand(bot) # sync_commands=True

#Game Containers
sc_yr = False

class Scotland_Yard:
    '''
    The Scotland Yard game manager
    '''
    def __init__(self, channel):
        self.channel = channel
        self.rnd = 0
        self.red = False
        self.blue = False
        self.yellow = False
        self.orange = False
        self.green = False
        self.black = False
        self.players = []
        self.mr_x_candidates = []
        self.playercount = 6
        self.name="Scotland Yard"
        self.started = False
        self.start = 0
        self.moves = {
            "red": [],
            "blue": [],
            "yellow": [],
            "green": [],
            "orange": [],
            "black": []
        }
        self.wait_for_black = False

    def assign(self, color, who):
        if color == "red":
            self.red = who
        elif color == "blue":
            self.blue = who
        elif color == "yellow":
            self.yellow = who
        elif color == "green":
            self.green = who
        elif color == "orange":
            self.orange = who

    def make_bots(self):
        if self.red == False:
            self.red = "red bot"
        if self.blue == False:
            self.blue= "blue bot"
        if self.yellow == False:
            self.yellow = "yellow bot"
        if self.orange == False:
            self.orange = "orange bot"
        if self.green == False:
            self.green = "green bot"

    def get_player(self, color):
        if color == "red":
            return self.red
        elif color == "blue":
            return self.blue
        elif color == "yellow":
            return self.yellow
        elif color == "green":
            return self.green
        elif color == "orange":
            return self.orange
    def __iter__(self):
        return self

    def __next__(self):
        if self.start < 5:
            colors = {
                0: self.red,
                1: self.blue,
                2: self.yellow,
                3: self.green,
                4: self.orange
            }
            self.start += 1
            return colors[self.start - 1]
        else:
            self.start = 0
            raise StopIteration

#TODO Command for joining as mr_X candidate
#TODO Command for switching channel
#TODO Leave Game before and during game
#TODO DISPLAY colors
@slash.slash(name="blep")
async def _blep(ctx: SlashContext, animal, only_smol: bool=False):
    await ctx.author.send(f"test {type(only_smol)}")
    await ctx.send("Test")

@slash.slash(name="start")
async def _start(ctx: SlashContext, game: str, play_along: bool=False, *args):
    global sc_yr
    logger.info("Starting game!")
    if sc_yr != False:
        logger.warning('Game already running')
        await ctx.send(f"{ctx.author.mention} A game has already started! Use /join to join the current game")
        return
    if game == "Scotland Yard":
        logger.info("Starting scotland yard")
        sc_yr = Scotland_Yard(ctx.channel)
        await ctx.send(f"A {game}-Game has been created!")
        if play_along:
            logger.info(f"Adding {ctx.author} to the game")
            sc_yr.players.append(ctx.author)
            sc_yr.mr_x_candidates.append(ctx.author)
            logger.info(f"Added {ctx.author} to the game")
        await send_player_list(ctx, sc_yr.players)
    else:
        logging.critical("Game not found!")
        await ctx.send(f"{ctx.author.mention} Game not found!")

@slash.slash(name="join")
async def _join(ctx: SlashContext, eligible=True, who=False, *args):
    global sc_yr
    if not await check_game(ctx, sc_yr):
        return
    if len(sc_yr.players) < sc_yr.playercount:
        if who:
            if who not in sc_yr.players:
                logger.info(f"Adding {who} to the player list")
                sc_yr.players.append(who)
                if eligible:
                    logger.info(f"Adding {who} to the Mr X. list")
                    sc_yr.mr_x_candidates.append(who)
                await ctx.send(f"{who.mention} has been added to the player list")
            else:
                logger.warning(f"{who} is already in game")
                await ctx.send(f"{ctx.author.mention} This player is already a participant!")
        else:
            if ctx.author not in sc_yr.players:
                sc_yr.players.append(ctx.author)
                logger.info(f"Added {ctx.author} to the player list")
                if eligible:
                    sc_yr.mr_x_candidates.append(ctx.author)
                    logger.info(f"Adding {ctx.author} to the Mr X. list")
                await ctx.send(f"{ctx.author.mention} You've been added to the player list")
            else:
                logger.warning(f"{ctx.author} is already in game")
                await ctx.send(f"{ctx.author.mention} You're already a participant!")
        await send_player_list(ctx, sc_yr.players)
        if len(sc_yr.players) == sc_yr.playercount:
            logger.info("auto confirm")
            if await conf_embed(sc_yr.channel, sc_yr):
                logger.info("Starting game from auto confirm")
                await start_game()
    else:
        logger.warning("List is Already Full")
        await sc_yr.channel.send(f"{ctx.author.mention} The list is already full!")

@slash.slash(name="confirm")
async def _confirm(ctx: SlashContext):
    global sc_yr
    logger.info("Starting confirm")
    if not await check_game(ctx, sc_yr):
        logger.warning("Confirm failed")
        return
    if await conf_embed(ctx, sc_yr):
        logger.info("Confirm accepted")
        await start_game()
    else:
        logger.info("Confirm denied")

@slash.slash(name="pick")
async def _pick(ctx: SlashContext, color, who=False, *args):
    global sc_yr
    who = who if who else ctx.author
    if not sc_yr.started:
        await ctx.send("The game hasn't started yet!")
    elif who in sc_yr:
        await ctx.send(f"{who.mention} already has a color!")
    elif who not in sc_yr.players:
        await ctx.send(f"{who.mention} is not an participant!")
    elif sc_yr.get_player(color):
        await ctx.send(f"{color.capitalize()} has been assigned already!")
    else:
        logger.info(f"Assigning {color} to {who}")
        sc_yr.assign(color, who)
        await ctx.send(f"{who.mention} has been assigned the color {color}")
        if len(list(filter(lambda x: x == False, list(iter(sc_yr))))) <= sc_yr.playercount - len(sc_yr.players):
            sc_yr.make_bots()
            logger.info("Made Bots")
            await sc_yr.channel.send("The remaining colors were assigned to the bots!")
            await assign_pos()
        else:
            logger.info("Waiting for other people to pick a color")

@slash.slash(name="colors")
async def _colors(ctx: SlashContext):
    global sc_yr
    logger.info("Attemting to print colors")
    embed = discord.Embed(title="Colors", color=discord.Color.from_rgb(128, 128, 128))
    value = str(sc_yr.red) if sc_yr.red else "Not assigned"
    embed.add_field(name=":red_circle:", value=value, inline=True)
    value = str(sc_yr.blue) if sc_yr.blue else "Not assigned"
    embed.add_field(name=":blue_circle:", value=value, inline=True)
    value = str(sc_yr.yellow) if sc_yr.yellow else "Not assigned"
    embed.add_field(name=":yellow_circle:", value=value, inline=True)
    value = str(sc_yr.green) if sc_yr.green else "Not assigned"
    embed.add_field(name=":green_circle:", value=value, inline=True)
    value = str(sc_yr.orange) if sc_yr.orange else "Not assigned"
    embed.add_field(name=":orange_circle:", value=value, inline=True)
    value = str(sc_yr.black) if sc_yr.black else "Not assigned"
    embed.add_field(name=":black_circle:", value=value, inline=True)
    await ctx.send(embed=embed)

@slash.slash(name="move")
async def _move(ctx: SlashContext, pos: int, color: str=False, boost: int=False):
    if not 0 < pos < 200:
        await ctx.send(f"{ctx.author.mention} That position is invalid!")
    global sc_yr
    colors = ['red', 'blue', 'yellow', 'green', 'orange']
    who = ctx.author
    if color:
        who = sc_yr.get_player(color)
    logger.info(f"Moving {who}")
    if sc_yr.wait_for_black and who == sc_yr.black:
        logger.info(f"{who} is Mr. X")
        # if sc_yr.channel == ctx.channel:

        #     ctx.delete()

        sc_yr.moves['black'].append(pos)
        sc_yr.wait_for_black = False
        logger.info(f"{who} was moved")
        if boost:
            logger.info(f"Boosting {who}")
            for c in colors:
                logger.info(f"Duplicating {c}'s position")
                sc_yr.moves[c].append(sc_yr.moves[c][-1])
            sc_yr.moves['black'].append(boost)
            sc_yr.rnd += 1
            logger.info(f"{who} was boosted")
        await ctx.send("Mr. X has moved! It's your turn, detectives!")

    elif not sc_yr.wait_for_black:
        logger.info("Moving detective")
        players = [sc_yr.red, sc_yr.blue, sc_yr.yellow, sc_yr.green, sc_yr.orange]
        for i in range(5):
            player = players[i]
            logger.info(f"{i}, {player}")
            if player == who:
                logger.info(f"Found author: {sc_yr.rnd}, {len(sc_yr.moves[colors[i]])}")
                if sc_yr.rnd >= len(sc_yr.moves[colors[i]]):
                    sc_yr.moves[colors[i]].append(pos)
                    msg = who if type(who) == type("") else who.mention
                    await ctx.send(f"{msg} was moved to {pos}")
                    logger.info(f"{who} was moved to {pos}")
                    if all(len(e) > sc_yr.rnd for e in sc_yr.moves.values()):
                        logger.info("All detectives moved")
                        await sc_yr.channel.send("All detectives have moved!")
                        await play_round()
                else:
                    await ctx.send(f"{who.mention} Has already made a move")
                return
        logger.info(f"{sc_yr.wait_for_black}, {who in sc_yr}")
        await ctx.send("It's not your turn!")
    else:
        logger.info(f"{sc_yr.wait_for_black}, {who in sc_yr}")
        await ctx.send("It's not your turn!")

@slash.slash(name="end")
async def _end(ctx: SlashContext):
    global sc_yr
    await ctx.send("Alright, ending game")
    for c, m in sc_yr.moves.items():
        while len(m) <= sc_yr.rnd:
            sc_yr.moves[c].append(sc_yr.moves[c][-1])
    logger.info("Ending game")
    await end_game()

@bot.command()
async def tes(ctx):
    await ctx.send(ctx.guild.id)

async def check_game(ctx, game):
    if not game:
        await ctx.send(f"{ctx.author.mention} No game has been started yet, use /start to start a new game!")
        return False
    elif game.started:
        await ctx.send(f"{ctx.author.mention} The game has already started, use /replace to replace a player or a bot!")
        #TODO: REPLACE PLAYER
    return True

async def send_player_list(ctx, players):
    if len(players) > 0:
        embed = discord.Embed(title="Current players", color=discord.Color.from_rgb(255, 0, 255))
        value = ""
        for p in players:
            value += str(p) + "\n"
        embed.add_field(name="Player list", value=value, inline=False)
        await ctx.send(embeds=[embed])
    else:
        await ctx.send("Currently no players participating in the game!")

async def conf_embed(ctx, sc_yr):
    embed = discord.Embed(title="Game Details", color=discord.Color.from_rgb(0, 0, 255))
    embed.add_field(name="Game", value=sc_yr.name)
    value = ""
    for p in sc_yr.players:
        value += str(p) + "\n"
    embed.add_field(name="Player list", value=value, inline=False)
    value = ""
    cand = sc_yr.mr_x_candidates if len(sc_yr.mr_x_candidates) > 0 else sc_yr.players
    for p in cand:
        value += str(p) + "\n"
    embed.add_field(name="Mr. X Candidates", value=value, inline=False)
    await ctx.send(embeds=[embed])
    if len(sc_yr.players) != sc_yr.playercount:
        await ctx.send("NOTE: Missing players will be represented by bots")
    await ctx.send("Start game? (y/n)")
    msg = await bot.wait_for("message")
    if msg.content.lower() in ["y", "yes", "ye"]:
        await ctx.send(embed=discord.Embed(title="LET THE GAME BEGIN!", color=discord.Color.from_rgb(0,255,0)))
        return True
    elif msg.content.lower() in ["n", "no"]:
        await ctx.send("Fine, I'll wait. Use /confirm to start the game, whenever you are ready!")
    else:
        await ctx.send("I'll take that as a no. Use /confirm to start the game, whenever you are ready!")
    return False

async def start_game():
    #TODO start game
    global sc_yr
    logger.info("Game started!")
    sc_yr.started = True
    cand = sc_yr.mr_x_candidates.copy() if len(sc_yr.mr_x_candidates) > 0 else sc_yr.players.copy()
    sc_yr.black = random.choice(cand)
    cand.remove(sc_yr.black)
    await sc_yr.channel.send(embed=discord.Embed(title=f"{sc_yr.black} IS THE CHOSEN ONE!\nREMAINING PEASANTS, CHOOSE YOUR COLOR", color=discord.Color.from_rgb(255, 0, 0)))

async def assign_pos():
    global sc_yr
    pos = [197, 132, 94, 103, 26, 141, 112, 91, 155, 34, 29, 50, 53, 198, 174, 13, 138, 117]
    end_msg = ""
    embed = discord.Embed(title="Starting Positions")
    for i in sc_yr.moves.keys():
        start = random.choice(pos)
        pos.remove(start)
        sc_yr.moves[i].append(start)
        if i == "black":
            logger.info("Sending station to Mr. X")
            await sc_yr.black.send(f"You're starting at station number {start}")
            logger.info("Sent station to Mr. X")
        else:
            msg = sc_yr.get_player(i)
            logger.info(f"player type: {type(msg)}")
            msg = i if type(msg) == type("") else str(msg)
            embed.add_field(name=f"{msg}", value=f"{start}", inline=False)
            #end_msg += f"{msg} starts at {start}\n\n"
    await sc_yr.channel.send(embed=embed)
    await play_round()

async def play_round():
    logger.info("Starting round")
    global sc_yr
    logger.info("Testing whether Mr X. has been found")
    colors = ['red', 'blue', 'yellow', 'green', 'orange']
    if any(sc_yr.moves['black'][-1] == sc_yr.moves[c][-1] and not c == 'black' for c in colors):
        await sc_yr.channel.send(embed=discord.Embed(title="Mr. X has been caught! Congratulations", color=discord.Color.from_rgb(0, 255, 0)))
        logger.info("Testing whether Mr X. has been found")
        await end_game()
        return
    sc_yr.rnd += 1
    if sc_yr.rnd >= 25:
        await sc_yr.channel.send(embed=discord.Embed(title="Mr. X has escaped! Missions failed, detectives", color=discord.Color.from_rgb(255, 0, 0)))
        await end_game()
        return
    sc_yr.wait_for_black = True
    await sc_yr.channel.send("Waiting for Mr. X's move...")
    #sc_yr.black.send("Make your move here!")
    #TODO continue

async def end_game():
    dic = dict()
    global player_images
    global MAP
    global sc_yr
    for i, e in enumerate(sc_yr.moves.values()):
        dic[player_images[i]] = e
    try:
        await sc_yr.channel.send("Creating video")
        loop = asyncio.get_event_loop()
        await loop.run_in_executor(None, make_video, MAP, dic)
        await sc_yr.channel.send("The video has been created")
        await loop.run_in_executor(None, convert_avi_to_mp4, "project.avi", "final")
    except:
        pass
    else:
        sc_yr = False

class Img:
    '''
    Image Class containing the image
    '''
    generator = 0
    def __init__(self, img, x_size=0, y_size=0, pos_x=0, pos_y=0):
        '''
        Initialize instance
        '''
        if not Img.generator:
            Img.generator = Img.generate()
        self.id = next(Img.generator)
        if isinstance(img, Image.Image):
            self.image = img
        if isinstance(img, Img):
            self.image = img.image
            self.pos_x = img.pos_x
            self.pos_y = img.pos_y
        else:
            self.image = Image.open(img)
            self.pos_x = pos_x
            self.pos_y = pos_y
            if x_size and y_size:
                self.image = self.image.resize((x_size, y_size))

    @staticmethod
    def generate():
        '''
        Generate unique id
        '''
        i = 0
        while True:
            yield i
            i += 1

    def __add__(self, other):
        '''
        Merge images when adding
        '''
        s = deepcopy(self)
        o = deepcopy(other)
        s.image.paste(o.image, (round(o.pos_x), round(o.pos_y)), o.image)
        return s

    def __hash__(self):
        '''
        Defined to enable the use as a key in a dictionary
        '''
        return hash(self.id)

    def __eq__(self, other):
        '''
        Defined to enable the use as a key in a dictionary
        '''
        if isinstance(other, self.__class__):
            return self.id == other.id
        return NotImplemented

    def convert(self):
        '''
        Convert from RGB to BGR format
        '''
        pil_image = self.image.convert('RGB')
        open_cv_image = numpy.array(pil_image)
        # Convert RGB to BGR
        self.image = open_cv_image[:, :, ::-1].copy()
        return self

    def move(self, x, y):
        '''
        Reassign position
        '''
        self.pos_x = x
        self.pos_y = y

def make_video(MAP, dic):
    '''
    Creates video
    '''

    #Convert stations to coordinates
    logger.info('Converting stations')
    for img, stations in dic.items():
        dic[img] = assign_coordinates(stations, img)
    logger.info('Finished converting stations')

    #Get length of longest list
    moves = max(len(e) for e in dic.values())
    images = []
    frame = MAP

    #Make image of starting positions
    for img, pos_list in dic.items():
        img.move(*pos_list[0])
        frame = frame + img

    for x in range(5):
        images.append(deepcopy(frame))

    #Make frames of every move
    for m in range(moves - 1):
        move_list = dict()
        for img, pos_list in dic.items():
            try:
                temp_move = (pos_list[m], pos_list[m + 1])
                move_list[img] = temp_move
            except IndexError:
                pass
        logger.info(f'Visualizing move {m}')
        images.extend(make_move(move_list, MAP))
        logger.info(f'Finished visualizing move {m}')

    #Creating videowriter
    logger.info('Creating Videowriter')
    out = cv2.VideoWriter('project.avi', cv2.VideoWriter_fourcc(*'DIVX'), 25, (MAP.image.width, MAP.image.height))
    logger.info('Created Videowriter')

    #Writing video
    logger.info('Writing video')
    for i in range(len(images)):
        x = images[i]
        x = x.convert()
        out.write(x.image)
    logger.info('Finished writing video')
    out.release()

def make_move(li, MAP):
    '''
    Create images of a single move
    '''
    splitted_moves = dict()
    for img, pos_list in li.items():
        splitted_moves[img] = split(pos_list)
    frames = []
    for i in range(max(len(e) for e in splitted_moves.values())):
        frame = MAP
        for img, pos_list in splitted_moves.items():
            img.move(*pos_list[i])
            frame = frame + img
        frames.append(frame)
    return frames

destinations = {
    1: (1373, 121),
    2: (1983, 76),
    3: (2375, 87),
    4: (2611, 71),
    5: (3568, 92),
    6: (3863, 94),
    7: (4166, 107),
    8: (1254, 257),
    9: (1492, 271),
    10: (2183, 258),
    11: (2362, 291),
    12: (2511, 264),
    13: (2784, 243),
    14: (3063, 189),
    15: (3353, 163),
    16: (3630, 262),
    17: (4147, 353),
    18: (1115, 370),
    19: (1337, 400),
    20: (1628, 336),
    21: (1913, 453),
    22: (2372, 499),
    23: (2600, 381),
    24: (2952, 387),
    25: (3104, 428),
    26: (3337, 252),
    27: (3378, 390),
    28: (3484, 340),
    29: (3872, 422),
    30: (4245, 399),
    31: (1206, 479),
    32: (1526, 561),
    33: (1783, 519),
    34: (2201, 564),
    35: (2447, 630),
    36: (2546, 649),
    37: (2706, 504),
    38: (3031, 519),
    39: (3179, 485),
    40: (3433, 588),
    41: (3544, 549),
    42: (4156, 554),
    43: (1055, 608),
    44: (1390, 674),
    45: (1614, 722),
    46: (1822, 654),
    47: (1990, 618),
    48: (2252, 732),
    49: (2628, 744),
    50: (2783, 639),
    51: (3107, 656),
    52: (3275, 608),
    53: (3463, 719),
    54: (3589, 682),
    55: (3878, 677),
    56: (4260, 709),
    57: (1158, 735),
    58: (1481, 774),
    59: (1548, 853),
    60: (1671, 833),
    61: (1885, 865),
    62: (1998, 826),
    63: (2276, 970),
    64: (2445, 937),
    65: (2620, 898),
    66: (2727, 876),
    67: (2909, 846),
    68: (3139, 794),
    69: (3349, 777),
    70: (3609, 824),
    71: (3838, 822),
    72: (4080, 842),
    73: (1157, 866),
    74: (1272, 1003),
    75: (1428, 958),
    76: (1633, 948),
    77: (1770, 1052),
    78: (1931, 1032),
    79: (2051, 1008),
    80: (2327, 1064),
    81: (2558, 1103),
    82: (2642, 1042),
    83: (2869, 1013),
    84: (3019, 941),
    85: (3151, 893),
    86: (3382, 979),
    87: (3624, 1036),
    88: (3729, 1063),
    89: (3819, 986),
    90: (3990, 987),
    91: (4225, 988),
    92: (1069, 1111),
    93: (1084, 1210),
    94: (1290, 1167),
    95: (1386, 1152),
    96: (1870, 1224),
    97: (1976, 1187),
    98: (2115, 1141),
    99: (2247, 1160),
    100: (2478, 1228),
    101: (2713, 1137),
    102: (3000, 1017),
    103: (3188, 997),
    104: (3390, 1090),
    105: (3918, 1134),
    106: (4127, 1175),
    107: (4273, 1173),
    108: (3864, 1362),
    109: (2030, 1389),
    110: (2190, 1234),
    111: (2289, 1358),
    112: (2345, 1316),
    113: (2576, 1313),
    114: (2739, 1263),
    115: (2989, 1184),
    116: (3389, 1322),
    117: (3661, 1425),
    118: (3394, 1480),
    119: (4201, 1544),
    120: (1065, 1640),
    121: (1178, 1641),
    122: (1342, 1632),
    123: (1752, 1621),
    124: (1995, 1574),
    125: (2413, 1428),
    126: (2863, 1349),
    127: (3163, 1424),
    128: (3551, 1889),
    129: (3634, 1512),
    130: (2359, 1585),
    131: (2475, 1500),
    132: (2736, 1485),
    133: (3036, 1620),
    134: (3252, 1551),
    135: (3738, 1597),
    136: (4127, 1755),
    137: (1617, 1767),
    138: (2069, 1673),
    139: (2334, 1681),
    140: (2735, 1651),
    141: (3113, 1672),
    142: (3389, 1726),
    143: (3638, 1696),
    144: (1093, 1929),
    145: (1216, 1920),
    146: (1378, 1908),
    147: (1499, 1873),
    148: (1664, 1855),
    149: (1802, 1834),
    150: (1965, 1783),
    151: (2040, 1857),
    152: (2148, 1775),
    153: (2219, 1871),
    154: (2491, 1800),
    155: (2591, 1920),
    156: (2783, 1918),
    157: (2941, 1929),
    158: (3203, 1826),
    159: (3220, 2192),
    160: (3750, 1926),
    161: (3969, 1904),
    162: (4276, 1899),
    163: (1359, 1995),
    164: (1527, 2000),
    165: (1842, 2050),
    166: (2169, 1978),
    167: (2425, 2026),
    168: (2519, 2089),
    169: (2785, 2050),
    170: (2917, 2069),
    171: (3907, 2437),
    172: (3464, 2055),
    173: (3808, 2161),
    174: (4098, 2082),
    175: (4254, 2193),
    176: (1048, 2166),
    177: (1188, 2126),
    178: (1432, 2105),
    179: (1720, 2145),
    180: (1900, 2179),
    181: (2082, 2132),
    182: (2179, 2153),
    183: (2355, 2076),
    184: (2653, 2193),
    185: (2865, 2329),
    186: (3071, 2287),
    187: (3382, 2214),
    188: (3682, 2221),
    189: (1190, 2361),
    190: (1343, 2443),
    191: (1533, 2285),
    192: (1577, 2490),
    193: (2034, 2306),
    194: (2084, 2379),
    195: (2224, 2369),
    196: (2424, 2248),
    197: (2453, 2384),
    198: (3203, 2495),
    199: (3714, 2487),
}

def assign_coordinates(li, img):
    '''
    Converts station number to coordinates
    '''
    global destinations

    for i in range(len(li)):
        try:
            x = destinations[li[i]]
            li[i] = (round(x[0] - img.image.width / 2),round(x[1] - img.image.height / 2))
        except:
            logger.critical("Destination couldn't be assigned")
    return li

def split(li):
    '''
    Splits the vector in smaller splits
    '''
    split = 20 #Divide vecotr in how many sections
    extra = 5 #Add how many extra frames at the end

    #Determine step per frame
    step_x = (li[1][0] - li[0][0]) / split
    step_y = (li[1][1] - li[0][1]) / split

    #Define starting coordinates
    start_x = li[0][0]
    start_y = li[0][1]

    splits = []

    #Add smaller splits to list
    for i in range(1, split + 1):
        splits.append((i * step_x + start_x, i * step_y + start_y))

    #Add extra coordinates, which will serve as pausing frames
    for i in range(extra):
        splits.append(li[1])
    return splits

def check():
    '''
    Prints a red player on every station, to check whether the coordinates are accurate
    '''
    global destinations
    global RED
    global MAP

    frame = MAP
    for pos in destinations.values():
        RED.move(pos[0] - 40, pos[1] - 40)
        frame = frame + RED
    frame.image.show()

def convert_avi_to_mp4(avi_file_path, output_name):
    os.popen("ffmpeg -i {input} -ac 2 -b:v 2000k -c:a aac -c:v libx264 -b:a 160k -vprofile high -bf 0 -strict experimental -f mp4 {output}.mp4".format(input = avi_file_path, output = output_name))
    return True

if __name__ == '__main__':
    #logger setup
    logger = logging.getLogger('discord')
    logger.setLevel(logging.INFO)
    handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
    handler.setFormatter(logging.Formatter('[%(levelname)s] - %(asctime)s:%(name)s: %(message)s'))
    logger.addHandler(handler)

    logger.info('-----------New Boot-----------')

    #Load environment variables
    load_dotenv()
    logger.info('Loading environment variables')
    AUTH_TOKEN = os.getenv('TOKEN')
    logger.info('Finished loading environment variables')

    #Load images
    logger.info('Loading assets')
    MAP = Img('Assets\\Map.jpg')
    RED = Img('Assets\\Red.png', 80, 80)
    BLUE = Img('Assets\\Blue.png', 80, 80)
    YELLOW = Img('Assets\\Yellow.png', 80, 80)
    GREEN = Img('Assets\\Green.png', 80, 80)
    ORANGE = Img('Assets\\Orange.png', 80, 80)
    BLACK = Img('Assets\\White.png', 80, 80)
    logger.info('Finished loading assets')

    player_images=[RED, BLUE, YELLOW, GREEN, ORANGE, BLACK]

    #check()
    bot.run(AUTH_TOKEN)

    #clip = (VideoFileClip("project.avi"))
    #clip.write_gif("output.gif")

max_stars_repo_name: TheLegendOfLonk/GameBot

max_issues_repo_name: TheLegendOfLonk/GameBot

max_forks_repo_name: TheLegendOfLonk/GameBot


text:
#!/usr/bin/env python

""" Adjancecy list to GraphML converter

Long Description
"""

import sys
import argparse
import networkx as nx

__author__ = "Albert Farres"
__copyright__ = "Copyright 2018, Albert Farres"
#__credits__ = [""]
__license__ = "MIT"
__version__ = "0.0.1"
__maintainer__ = "Albert Farres"
__email__ = "albertfc@gmail.com"
__status__ = "Development"

debug = False

def get_args( ):
	parser = argparse.ArgumentParser( description="Adjancecy list to GraphML converter." )
	parser.add_argument( "-i", "--in-file", help="Input file.", type=argparse.FileType( 'r' ), default=sys.stdin )
	parser.add_argument( "-o", "--out-file", help="Output file. Default stdout.", type=argparse.FileType( 'w' ), default=sys.stdout )
	parser.add_argument(  "--debug", action="store_true" )
	return parser.parse_args( )

def main( args ):
	args.in_file.readline()
	#colors = map( int, args.in_file.readline().split() )
	colors = args.in_file.readline().split()

	G = nx.read_adjlist( args.in_file )

	colors_dict = {}
	idx = 1
	for c in colors:
		colors_dict[str(idx)] = {'calor': c}
		idx += 1
	nx.set_node_attributes( G, colors_dict )

	nx.write_graphml( G, args.out_file )

if __name__=='__main__':
	args = get_args( )
	debug = args.debug
	if debug:
		print args
	main( args )

ext: py

max_stars_repo_path: Data Structures/unique-colors/adj2ml.py

max_stars_repo_name: albertfc/hackerrank

max_issues_repo_path: Data Structures/unique-colors/adj2ml.py

max_issues_repo_name: albertfc/hackerrank

max_forks_repo_path: Data Structures/unique-colors/adj2ml.py

max_forks_repo_name: albertfc/hackerrank

reason: import networkx


text:
#   Copyright 2020 The PyMC Developers
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

import logging
import numpy as np
import scipy
import theano
import theano.tensor as tt
from ..ode import utils
from ..exceptions import ShapeError, DtypeError

_log = logging.getLogger('pymc3')
floatX = theano.config.floatX

class DifferentialEquation(theano.Op):
    """
    Specify an ordinary differential equation

    .. math::
        \dfrac{dy}{dt} = f(y,t,p) \quad y(t_0) = y_0

    Parameters
    ----------

    func: callable
        Function specifying the differential equation. Must take arguments y (n_states,), t (scalar), p (n_theta,)
    times: array
        Array of times at which to evaluate the solution of the differential equation.
    n_states: int
        Dimension of the differential equation.  For scalar differential equations, n_states=1.
        For vector valued differential equations, n_states = number of differential equations in the system.
    n_theta: int
        Number of parameters in the differential equation.
    t0: float
        Time corresponding to the initial condition

    .. code-block:: python

        def odefunc(y, t, p):
            #Logistic differential equation
            return p[0] * y[0] * (1 - y[0])

        times = np.arange(0.5, 5, 0.5)

        ode_model = DifferentialEquation(func=odefunc, times=times, n_states=1, n_theta=1, t0=0)
    """
    _itypes = [
        tt.TensorType(floatX, (False,)),                  # y0 as 1D floatX vector
        tt.TensorType(floatX, (False,))                   # theta as 1D floatX vector
    ]
    _otypes = [
        tt.TensorType(floatX, (False, False)),            # model states as floatX of shape (T, S)
        tt.TensorType(floatX, (False, False, False)),     # sensitivities as floatX of shape (T, S, len(y0) + len(theta))
    ]
    __props__ = ("func", "times", "n_states", "n_theta", "t0")

    def __init__(self, func, times, *, n_states, n_theta, t0=0):
        if not callable(func):
            raise ValueError("Argument func must be callable.")
        if n_states < 1:
            raise ValueError("Argument n_states must be at least 1.")
        if n_theta <= 0:
            raise ValueError("Argument n_theta must be positive.")

        # Public
        self.func = func
        self.t0 = t0
        self.times = tuple(times)
        self.n_times = len(times)
        self.n_states = n_states
        self.n_theta = n_theta
        self.n_p = n_states + n_theta

        # Private
        self._augmented_times = np.insert(times, 0, t0).astype(floatX)
        self._augmented_func = utils.augment_system(func, self.n_states, self.n_theta)
        self._sens_ic = utils.make_sens_ic(self.n_states, self.n_theta, floatX)

        # Cache symbolic sensitivities by the hash of inputs
        self._apply_nodes = {}
        self._output_sensitivities = {}

    def _system(self, Y, t, p):
        """This is the function that will be passed to odeint. Solves both ODE and sensitivities.

        Args:
            Y: augmented state vector (n_states + n_states + n_theta)
            t: current time
            p: parameter vector (y0, theta)
        """
        dydt, ddt_dydp = self._augmented_func(Y[:self.n_states], t, p, Y[self.n_states:])
        derivatives = np.concatenate([dydt, ddt_dydp])
        return derivatives

    def _simulate(self, y0, theta):
        # Initial condition comprised of state initial conditions and raveled sensitivity matrix
        s0 = np.concatenate([y0, self._sens_ic])

        # perform the integration
        sol = scipy.integrate.odeint(
            func=self._system, y0=s0, t=self._augmented_times, args=(np.concatenate([y0, theta]),)
        ).astype(floatX)
        # The solution
        y = sol[1:, :self.n_states]

        # The sensitivities, reshaped to be a sequence of matrices
        sens = sol[1:, self.n_states:].reshape(self.n_times, self.n_states, self.n_p)

        return y, sens

    def make_node(self, y0, theta):
        inputs = (y0, theta)
        _log.debug('make_node for inputs {}'.format(hash(inputs)))
        states = self._otypes[0]()
        sens = self._otypes[1]()

        # store symbolic output in dictionary such that it can be accessed in the grad method
        self._output_sensitivities[hash(inputs)] = sens
        return theano.Apply(self, inputs, (states, sens))

    def __call__(self, y0, theta, return_sens=False, **kwargs):
        if isinstance(y0, (list, tuple)) and not len(y0) == self.n_states:
            raise ShapeError('Length of y0 is wrong.', actual=(len(y0),), expected=(self.n_states,))
        if isinstance(theta, (list, tuple)) and not len(theta) == self.n_theta:
            raise ShapeError('Length of theta is wrong.', actual=(len(theta),), expected=(self.n_theta,))

        # convert inputs to tensors (and check their types)
        y0 = tt.cast(tt.unbroadcast(tt.as_tensor_variable(y0), 0), floatX)
        theta = tt.cast(tt.unbroadcast(tt.as_tensor_variable(theta), 0), floatX)
        inputs = [y0, theta]
        for i, (input_val, itype) in enumerate(zip(inputs, self._itypes)):
            if not input_val.type == itype:
                raise ValueError('Input {} of type {} does not have the expected type of {}'.format(i, input_val.type, itype))

        # use default implementation to prepare symbolic outputs (via make_node)
        states, sens = super(theano.Op, self).__call__(y0, theta, **kwargs)

        if theano.config.compute_test_value != 'off':
            # compute test values from input test values
            test_states, test_sens = self._simulate(
                y0=self._get_test_value(y0),
                theta=self._get_test_value(theta)
            )

            # check types of simulation result
            if not test_states.dtype == self._otypes[0].dtype:
                raise DtypeError('Simulated states have the wrong type.', actual=test_states.dtype, expected=self._otypes[0].dtype)
            if not test_sens.dtype == self._otypes[1].dtype:
                raise DtypeError('Simulated sensitivities have the wrong type.', actual=test_sens.dtype, expected=self._otypes[1].dtype)

            # check shapes of simulation result
            expected_states_shape = (self.n_times, self.n_states)
            expected_sens_shape = (self.n_times, self.n_states, self.n_p)
            if not test_states.shape == expected_states_shape:
                raise ShapeError('Simulated states have the wrong shape.', test_states.shape, expected_states_shape)
            if not test_sens.shape == expected_sens_shape:
                raise ShapeError('Simulated sensitivities have the wrong shape.', test_sens.shape, expected_sens_shape)

            # attach results as test values to the outputs
            states.tag.test_value = test_states
            sens.tag.test_value = test_sens

        if return_sens:
            return states, sens
        return states

    def perform(self, node, inputs_storage, output_storage):
        y0, theta = inputs_storage[0], inputs_storage[1]
        # simulate states and sensitivities in one forward pass
        output_storage[0][0], output_storage[1][0] = self._simulate(y0, theta)

    def infer_shape(self, node, input_shapes):
        s_y0, s_theta = input_shapes
        output_shapes = [(self.n_times, self.n_states), (self.n_times, self.n_states, self.n_p)]
        return output_shapes

    def grad(self, inputs, output_grads):
        _log.debug('grad w.r.t. inputs {}'.format(hash(tuple(inputs))))

        # fetch symbolic sensitivity output node from cache
        ihash = hash(tuple(inputs))
        if ihash in self._output_sensitivities:
            sens = self._output_sensitivities[ihash]
        else:
            _log.debug('No cached sensitivities found!')
            _, sens = self.__call__(*inputs, return_sens=True)
        ograds = output_grads[0]

        # for each parameter, multiply sensitivities with the output gradient and sum the result
        # sens is (n_times, n_states, n_p)
        # ograds is (n_times, n_states)
        grads = [
            tt.sum(sens[:,:,p] * ograds)
            for p in range(self.n_p)
        ]

        # return separate gradient tensors for y0 and theta inputs
        result = tt.stack(grads[:self.n_states]), tt.stack(grads[self.n_states:])
        return result

reason: import numpy,import scipy,import theano


text:
import torch
import os
import numpy as np

ckpt_dir = './checkpoint'
live_srcc = []
csiq_srcc = []
tid_srcc = []
bid_srcc = []
clive_srcc = []
koniq10k_srcc = []
kadid10k_srcc = []

index_cache = []

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
total = 779 + 866 + 1162 + 586 + 10073 + 10125
weight = [779/total, 866/total, 1162/total, 586/total, 10073/total, 10125/total]

for i in range(0, 10):
    ckpt_session = os.path.join(ckpt_dir, str(i+1))
    ckpt = torch.load(os.path.join(ckpt_session, 'DataParallel-00011.pt'), map_location=device)

    live_results = ckpt['test_results_srcc']['live']
    csiq_results = ckpt['test_results_srcc']['csiq']
    tid_results = ckpt['test_results_srcc']['tid2013']
    bid_results = ckpt['test_results_srcc']['bid']
    clive_results = ckpt['test_results_srcc']['clive']
    koniq10k_results = ckpt['test_results_srcc']['koniq10k']
    kadid10k_results = ckpt['test_results_srcc']['kadid10k']

    weighted_results = np.array(live_results)*weight[0] + np.array(csiq_results)*weight[1] + \
                       np.array(bid_results)*weight[3] + np.array(clive_results)*weight[2] + \
                       np.array(koniq10k_results)*weight[4] + np.array(kadid10k_results)*weight[5]

    weighted_results = weighted_results.tolist()

    best_index = weighted_results.index(max(weighted_results))

    index_cache.append(best_index)

    live_srcc.append(live_results[best_index])
    csiq_srcc.append(csiq_results[best_index])
    tid_srcc.append(tid_results[best_index])
    bid_srcc.append(bid_results[best_index])
    clive_srcc.append(clive_results[best_index])
    koniq10k_srcc.append(koniq10k_results[best_index])
    kadid10k_srcc.append(kadid10k_results[best_index])

print('live median srcc: %f' % np.median(np.array(live_srcc)))
print('csiq median srcc: %f' % np.median(np.array(csiq_srcc)))
print('tid median srcc: %f' % np.median(np.array(tid_srcc)))
print('bid median srcc: %f' % np.median(np.array(bid_srcc)))
print('clive median srcc: %f' % np.median(np.array(clive_srcc)))
print('koniq10k median srcc: %f' % np.median(np.array(koniq10k_srcc)))
print('kadid10k median srcc: %f' % np.median(np.array(kadid10k_srcc)))
print(index_cache)

weighted_srcc = np.median(live_srcc) * weight[0] + np.median(csiq_srcc) * weight[1] + \
                   np.median(bid_srcc) * weight[3] + np.median(clive_srcc) * weight[2] + \
                   np.median(koniq10k_srcc) * weight[4] + np.median(kadid10k_srcc) * weight[5]

print('weighted_srcc: %f' % weighted_srcc)

reason: import numpy


text:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# coerbuoy1benchmark.py - Control benchmark COERbuoy1
# 2020/2021 COER Laboratory, Maynooth University
# in cooperation with CorPower Ocean AB
#
# Author:
# Simon H. Thomas, simon.thomas.2021@mumail.ie
"""
Created on Tue Aug 24 14:15:37 2021

@author: Simon H. Thomas
"""

import numpy as np;
import pandas;
from scipy.interpolate import interp1d;
import xml.etree.ElementTree as xml;
from datetime import date;
import os;

pkg_dir=os.path.dirname(__file__);

##Definitions
x_limit=3.5;
omega_cut_off=3.5;

# Regular wave (Height, period, name, control)
def reg_wave(H,p,n,ctrl):
    import COERbuoy;
    print("Regular wave")
    H=float(H)*1.4;
    p=float(p);
    t0=np.max([p*2,0]);#4
    if (p<6):
        t0=p*4;
    t2=np.max([t0+p*3,0]);#6
    t=np.arange(0,t2,1/(omega_cut_off))
    y=H/2*np.sin(2*np.pi/p*t)
    return COERbuoy.start_simu(time=t,wave=y,name=n, t0=t0, control=ctrl )#/(9.81*9.81*1000/(32*np.pi)*H**2*p)

# Brettschneider wave (significant wave height, energy period, name, control)
def brettschneider_wave(Hs,p,n,ctrl):
    import COERbuoy;
    print("Brettschneider wave")
    Hs=float(Hs);
    p=float(p);
    omega=np.linspace(0.001,4,200);
    omega_m=2*np.pi/(p/0.856);
    S=5/16*(omega_m**4)/(omega**5)*(Hs**2)*np.exp(-5*(omega_m**4)/4/(omega**4))
    t0=np.max([p*3,120]);
    t2=np.max([t0+p*3]);#6
    t=np.arange(0,t2,1/(omega_cut_off/np.pi))
    np.random.seed(6)#Maybe replace by fixed phase vector; has to guaranteed that rnadom sequecne is always the same
    phase=np.random.rand(omega.size)*2*np.pi;
    y=np.sum(np.sqrt(2*S*(omega[1]-omega[0]))*np.sin(omega*t.reshape(t.size,1)+phase),1)

    return COERbuoy.start_simu(time=t,wave=y,name=n, t0=t0, control=ctrl )

# Brettschneider wave (significant wave height, energy period, name, control, WEC parameter file)
def brettschneider2_wave(Hs,p,n,ctrl):
    import COERbuoy;
    print("Brettschneider wave")
    omega=np.linspace(0.001,4,200);
    omega_m=2*np.pi/(p/0.856);
    S=5/16*(omega_m**4)/(omega**5)*(Hs**2)*np.exp(-5*(omega_m**4)/4/(omega**4))
    t0=np.max([p*3,120]);
    t2=np.max([t0+p*6]);
    t=np.arange(0,t2,1/(omega_cut_off/np.pi))
    np.random.seed(6)#Maybe replace by fixed phase vector; Has to guaranteed that random sequecne is always the same
    phase=np.random.rand(omega.size)*2*np.pi;
    y=np.sum(np.sqrt(2*S*(omega[1]-omega[0]))*np.sin(omega*t.reshape(t.size,1)+phase),1)

    return COERbuoy.start_simu(time=t,wave=y,name=n, t0=t0, control=ctrl)

def quartil (a, p):
    a=np.abs(a);
    b=np.sort(a);
    aa=np.sum(a);
    if (aa==0):
        return 0;
    return b[np.argmax(np.cumsum(b)/aa>p)];

def benchmark(ctrl,easy):
    print("Benchmark COERbuoy1")

    #Write settings file
    if (easy):
        with open("coerbuoy_settings.txt","w") as f:
            f.write("""{"hydro":"Floater_BEM",\n"WECfolder":"""+'"'+os.path.join(pkg_dir,"coerbuoy1").replace("\\","/")+'"'+""",\n"resolution":0.01\n,"status_message":[1,1,1,1,1,1,1,1]}""");
    else:
        with open("coerbuoy_settings.txt","w") as f:
            f.write("""{"hydro":"Floater_BEM",\n"WECfolder":"""+'"'+os.path.join(pkg_dir,"coerbuoy1").replace("\\","/")+'"'+""",
"resolution":0.01,
"status_message":[1,0,0,1,1,1,1,1]}""");

    power=0;
    x_lim=x_limit;#dyn_wec.x_lim;

    folder=os.path.join(pkg_dir,"benchmark");

    import COERbuoy;
    def power (T,H):
        #Calculate (theoretical) absorbed power with constrained complex-conjugate control
        w=2*np.pi/T;
        fe1=[5.02E+05,4.96E+05,4.84E+05,4.68E+05,4.48E+05,4.24E+05,3.98E+05,3.71E+05,3.43E+05,3.16E+05,2.89E+05,2.64E+05,2.40E+05,2.19E+05,1.98E+05,1.80E+05,1.63E+05,1.47E+05,1.33E+05,1.21E+05,1.09E+05,9.87E+04,8.92E+04,8.04E+04,7.11E+04,7.98E+04,6.39E+04,5.76E+04,5.24E+04,4.78E+04,4.37E+04,4.00E+04]
        R1=[1.32E+02,1.03E+03,3.30E+03,7.31E+03,1.31E+04,2.03E+04,2.84E+04,3.68E+04,4.48E+04,5.20E+04,5.81E+04,6.29E+04,6.63E+04,6.84E+04,6.92E+04,6.90E+04,6.79E+04,6.60E+04,6.36E+04,6.07E+04,5.75E+04,5.40E+04,5.03E+04,4.61E+04,3.98E+04,7.11E+04,4.38E+04,3.90E+04,3.55E+04,3.25E+04,2.98E+04,2.73E+04]

        w1=np.linspace(0.1,3.2,len(fe1));
        f_fe=interp1d(w1,fe1,fill_value='extrapolate',bounds_error=False);
        f_R=interp1d(w1,R1,fill_value='extrapolate',bounds_error=False);

        fe=f_fe(w);
        R=f_R(w);

        Fe=1.4*H/2*fe;
        Pmax1=Fe**2/(8*R);
        u1=Fe/(2*R);
        if (u1>3.5):
          u=w*3.5;
          Pmax1=u**2/2*(Fe/u-R);

        return Pmax1;

    fktdict={"regular_wave":reg_wave,
         "bretschneider_wave":brettschneider_wave}

    #define tests:
    #regular wave: 0-3
    #irregular waves 4-8
    #modelling errors irregular waves 8-11
    fkt=["regular_wave","regular_wave","regular_wave","regular_wave","bretschneider_wave","bretschneider_wave","bretschneider_wave","bretschneider_wave","bretschneider_wave","bretschneider_wave","bretschneider_wave","bretschneider_wave","bretschneider_wave","bretschneider_wave","bretschneider_wave","bretschneider_wave","bretschneider_wave","bretschneider_wave","bretschneider_wave","bretschneider_wave","bretschneider_wave","bretschneider_wave","bretschneider_wave","bretschneider_wave","bretschneider_wave","bretschneider_wave","bretschneider_wave","bretschneider_wave"]

    heights=[1,1,3,3]*6;
    periods=[6,9,9,12]*6;

    rand1=[0,0,0,0,0,0,0,0,0.893,0.332,0.821,0.042,0.108,0.301,0.167,0.323,0.666,0.667,0.398,0.379,0.017,0.12,0.69,0.874]
    rand2=[0,0,0,0,0,0,0,0,0.595,0.5298,0.419,0.335,0.622,0.337,0.99,0.132,0.500,0.287,0.22,0.50,0.636,0.636,0.08,0.68]
    rand3=[0,0,0,0,0,0,0,0,0.438,0.736,0.518,0.579,0.645,0.84,0.29,0.99,0.547,0.959,0.356,0.517,0.988,0.204,0.976,0.04]
    rand4=[0,0,0,0,0,0,0,0,0.990,0.82,0.821,0.413,0.876,0.02,0.2,0.012,0.447,0.652,0.711,0.255,0.764,0.966,0.54,0.43]

    rand1=rand1[:6*4];

    cw=np.zeros(len(rand1));

    rng=np.random.default_rng();
    arr=np.arange(len(rand1));
    rng.shuffle(arr);
    #regular, irregular tests (normal+modelling errors test)
    for j1 in arr:
        print(j1);
        #if False:
        f=open(os.path.join(pkg_dir,"coerbuoy1","floater.txt"),"w");
        f.write("""{"geo":[{"type":"cone","coord":[-4.5,0,-2,3]},
{"type":"cone","coord":[-2,3,-1,3.7]},
{"type":"cone","coord":[-1,3.7,0,4]},
{"type":"cone","coord":[0,4,1,3.7]},
{"type":"cone","coord":[1,3.7,2,3]},
{"type":"cone","coord":[2,3,4.5,0]}],
"negative_spring_force":"""+str(500000*(1+rand1[j1]*0.2))+""",
"negative_spring_length":1.85,
"negative_spring_stroke":5,
"viscous_drag_coefficient_heave":0.2,
"viscous_drag_coefficient_surge":0.2,
"mass_fraction_floater":0.8,
"generator_Rc":3,
"generator_c_L":60,
"generator_c_lambda":4000,
"generator_I_s":300,
"heave_only":"""+str(easy)+""",
"friction_force_static":"""+str(30000*(1+rand2[j1]*0.2))+""",
"friction_force_kinetic":15000,
"friction_damping":"""+str(7500*(1+rand3[j1]*0.4))+""",
"angle_limit":15,
"l_mooring":"""+str(20*(1+rand4[j1]*0.2))+""",
"angle_limit":15
}""");
        f.close();

        print("Write to "+os.path.join(folder,"benchmark"+str(j1)+".csv"));
        cw[j1]=cw[j1]+1/3*fktdict[fkt[j1]](heights[j1],periods[j1],os.path.join(folder,"benchmark"+str(j1)+".csv"),ctrl)/power(periods[j1],heights[j1]);
    print(cw)
    constraint_score=np.zeros(len(rand1));
    power_score=np.zeros(len(rand1));
    total_score=np.zeros(len(rand1));
    max_x=np.zeros(len(rand1));
    max_v=np.zeros(len(rand1));
    max_f=np.zeros(len(rand1));
    #cw=[0.28016265, 0.12318111, 0.08283574, 0.05843654, 0.07473666, 0.03710698, 0.02122793, 0.05248458, 0.07473666, 0.03710698, 0.02122793, 0.02384048, 0.07473666, 0.03710698, 0.02122793, 0.02384048, 0.07473666, 0.02488943, 0.02122793, 0.02384048, 0.07473666, 0.03710698, 0.02122793, 0.02384048]

    for i in range(len(rand1)):
        a=np.array(pandas.read_csv(os.path.join(folder,"benchmark"+str(i)+".csv"), header=1))
        t=a[:,0];
        h=a[:,2];
        v=a[:,3];
        #p=a[:,-1];

        ##Scoring
        #constraint score
        constraint_score[i]=1-(t[1]-t[0])*np.sum(np.abs(h)>x_lim)/(t[-1]-t[0]);
        #power score
        power_score[i]=cw[i];

        v=quartil(a[:,3],0.95);
        f=quartil(a[:,-2],0.95);

        #max. state
        max_x[i]=np.max(h);
        max_v[i]=np.max(v);
        max_f[i]=np.max(f);

    #average the 4 runs for the modelling error test
    for j in np.arange(4):
        power_score[8+j]      = np.mean(power_score[8+j::4]);
        constraint_score[8+j] = np.mean(constraint_score[8+j::4]);
        total_score[8+j]      = np.mean(total_score[8+j::4]);

    power_score=power_score.round(3);
    constraint_score=constraint_score.round(3);
    total_score = power_score*(constraint_score);

    row0=["category","state1","state2","state3","state4","power","constraints","score"]
    row1=["regular_waves"]+total_score[:4].tolist()+[np.mean(power_score[:4]),np.mean(constraint_score[:4]),np.mean(total_score[:4])]
    row2=["irregular_waves"]+total_score[4:8].tolist()+[np.mean(power_score[4:8]),np.mean(constraint_score[4:8]),np.mean(total_score[4:8])]
    row3=["error_modelling"]+total_score[8:12].tolist()+[np.mean(power_score[8:12]),np.mean(constraint_score[8:12]),np.mean(total_score[8:12])]
    row4=["total",0,0,0,0,np.mean(power_score[:12]),np.mean(constraint_score[:12]),np.mean(total_score[:12])]

    pDf=pandas.DataFrame(np.vstack([row1,row2,row3,row4]),columns=row0)
    pDf.round(2).to_csv("benchmark_total.csv",index=False)

    power_score=(power_score).round(2);
    constraint_score=(constraint_score).round(2);
    total_score=(total_score).round(2);
    #total_score1=[];
    #for idx,t in enumerate(total_score):
    #    total_score1.append(str((int)(t*100))+"%");

    cert = xml.parse(pkg_dir+"/cert_raw.svg");
    ro=cert.getroot();

    today=date.today();
    if easy==2:
        ctrl=ctrl+" (easy mode)"
    dic={'controller':"for "+ctrl+ ", issued on "+ today.strftime("%d.%m.%y")+".",
         'info':"Work in progress",

         's_power11':power_score[0],'s_con11':constraint_score[0],'score11':total_score[0],
         's_power12':power_score[1],'s_con12':constraint_score[1],'score12':total_score[1],
         's_power13':power_score[2],'s_con13':constraint_score[2],'score13':total_score[2],
         's_power14':power_score[3],'s_con14':constraint_score[3],'score14':total_score[3],
         's_power1':np.mean(power_score[:4]).round(2),'s_con1':np.mean(constraint_score[:4]).round(2),'score1':np.mean(total_score[:4]).round(2),

         's_power21':power_score[0+4],'s_con21':constraint_score[0+4],'score21':total_score[0+4],
         's_power22':power_score[1+4],'s_con22':constraint_score[1+4],'score22':total_score[1+4],
         's_power23':power_score[2+4],'s_con23':constraint_score[2+4],'score23':total_score[2+4],
         's_power24':power_score[3+4],'s_con24':constraint_score[3+4],'score24':total_score[3+4],
         's_power2':np.mean(power_score[4:8]).round(2),'s_con2':np.mean(constraint_score[4:8]).round(2),'score2':np.mean(total_score[4:8]).round(2),

         's_power31':power_score[0+8],'s_con31':constraint_score[0+8],'score31':total_score[0+8],
         's_power32':power_score[1+8],'s_con32':constraint_score[1+8],'score32':total_score[1+8],
         's_power33':power_score[2+8],'s_con33':constraint_score[2+8],'score33':total_score[2+8],
         's_power34':power_score[3+8],'s_con34':constraint_score[3+8],'score34':total_score[3+8],
         's_power3':np.mean(power_score[8:12]).round(2),'s_con3':np.mean(constraint_score[8:12]).round(2),'score3':np.mean(total_score[8:12]).round(2),

         's_power':np.mean(power_score[:12]).round(2),'s_con':np.mean(constraint_score[:12]).round(2),'score':np.mean(total_score[:12]).round(2)};

    for a1 in ro.iter('{http://www.w3.org/2000/svg}text'):
        cd = [b1 for b1 in a1];

        #a.text=str(dic[a.attrib['id']]);
        if (a1.attrib['id'] in dic):
          try:
              cd[0].text=format(dic[a1.attrib['id']],".2f");
          except:
              cd[0].text=(dic[a1.attrib['id']]);

        print(a1.attrib)
    cert.write("certificate"+ctrl+"_"+today.strftime("%d%m%y")+".svg")
    return power;

def run():
    ctrl="help";
    print("Welcome to the COERbuoy1 benchmark tool!")
    print("2021 by the Centre of Ocean Energy Research at Maynooth University")
    print("\nThis tool aims to test controller for Wave Energy Converter with a realisic numerical model.\n")
    print("\nPlease select a controller to test.")
    print("Enter help for examples and further information.")

    #print("\nFor example type python3 <filename.py> or py <filename.py> if your controller is written in python")
    while (ctrl == "help"):
        ctrl=input();
        if ctrl == "help":
            print("The controller you are referring to should be in the folder "+os.getcwd()+", or use absolute filenames.\n")
            print("Run a controller written in python:\npython <filename.py>\npython3 <filename.py>\npy <filename>")
            print("Run a controller written in octave:\noctave <filename.m>")
            print("\nSpecial commands:\nTCP - opens a TCP socket\nlinear - enter test with a linear damping\nhelp - show help\nexit - close program")

    if (ctrl != "exit"):
        print(ctrl)
        benchmark(ctrl,0);

if __name__ == "__main__":
    run();

max_stars_repo_name: SiHeTh/COERbuoyOne

max_issues_repo_name: SiHeTh/COERbuoyOne

max_forks_repo_name: SiHeTh/COERbuoyOne

reason: import numpy,from scipy


text:
import matplotlib.pyplot as plt
import pymc3 as pm
import numpy as np
import pandas as pd
import seaborn as sns
from pymc3.glm import GLM
import os
import tkinter as tk
from tkinter import filedialog

print('Running on PyMC3 v{}'.format(pm.__version__))
plt.style.use('seaborn-darkgrid')
import pickle # python3

"""Data"""
raw_df = pd.read_pickle('temp_synthetic_v3_1')

df1 = pd.read_csv("C:\\Users\\ht20\\Documents\\Files\\Generated_Network_Dataset_v3.1\\GridNetworks\\List_of_Configurations.txt",
                 header=0, sep="\t")
df1 = df1.assign(topology='Grid')
df2 = pd.read_csv("C:\\Users\\ht20\\Documents\\Files\\Generated_Network_Dataset_v3.1\\ScaleFreeNetworks\\List_of_Configurations.txt",
                 header=0, sep="\t")
df2 = df2.assign(topology='ScaleFree')
df3 = pd.read_csv("C:\\Users\\ht20\\Documents\\Files\\Generated_Network_Dataset_v3.1\\RandomNetworks\\List_of_Configurations.txt",
                 header=0, sep="\t")
df3 = df3.assign(topology='Random')
config_info = pd.concat([df1,df2,df3])

raw_df=pd.merge(raw_df, config_info,
             left_on=['Magnitude','topology'],
             right_on=['Config Number','topology'])

topo='Grid'
auc = 'MCA'
outputName = topo+'_'+auc

# raw_df = raw_df[(raw_df['topology']==topo)& (raw_df['auction_type']==auc)]
# df = pd.DataFrame({'nNodes': raw_df[' No. Nodes'], 'topoParam': raw_df[' Topology Parameter'],
#                    'Pint':  raw_df[' Interconnection Prob'], 'Pdam': raw_df[' Damage Prob'],
#                    'ResCap': raw_df[' Resource Cap'],'nLayers': raw_df[' No. Layers'],
#                    'y': raw_df['lambda_U'].astype('float')})
# df = df[df['y']!='nan']
# normalized_df=(df-df.mean())/df.std()

# # Modeling
# priors = {"Intercept": pm.Normal.dist(mu=0, sd=10),
#           "Regressor": pm.Normal.dist(mu=0, sd=10)}

# with pm.Model() as model_glm:
#     family = pm.glm.families.StudentT()
#     GLM.from_formula('y ~ nNodes+Pint+Pdam+ResCap+topoParam+nLayers', normalized_df, family=family, priors=priors)
#     trace = pm.sample(cores=1, draws = 2000, tune=1000)

# # Save Output and model
# pm.stats.summary(trace).to_csv('output/Output_'+outputName+'.csv')

# # Write model and results to file
# with open('output/model'+outputName+'.pkl', 'wb') as buff:
#     pickle.dump({'model': model_glm, 'trace': trace}, buff)

with open('output/model'+outputName+'.pkl', 'rb') as buff:
    data = pickle.load(buff)

basic_model, trace = data['model'], data['trace']

# Plots
plt.close('all')
#pm.traceplot(trace, combined=False)
#pm.plot_posterior(trace)
#pm.forestplot(trace)
#pm.autocorrplot(trace)

axInt = pm.densityplot(trace)
plt.close('all')
plt.figure(figsize=(5, 3))
#plt.rc('text', usetex=True)
#plt.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})
for i in range(1,len(axInt)-1):
    line = axInt[i].lines[0]
    xy = line.get_xydata()
    ax = plt.plot(xy[:,0], xy[:,1], linewidth=1)
    ax = plt.fill(xy[:,0], xy[:,1], alpha=0.75)
plt.legend([r'$N$',r'$P_i$',r'$P_d$',r'$R_c$',r'$\Upsilon$',r'$L$'], loc=1, frameon =True,framealpha=0.5)
plt.ylim(ymin=0)
plt.xlabel(r'$\beta_i$')
plt.ylabel(r'Probability')
plt.savefig('output/PosteriorDist_'+outputName+'.pdf', dpi=600)
plt.show()

reason: import numpy,import pymc3,from pymc3


text:
import numpy as np

def uniform(count=1, dimensionality=2):
    samples = np.zeros((count, dimensionality))
    for i in range(count):
        X = np.random.normal(0, 1, dimensionality + 2)
        X /= np.linalg.norm(X)
        samples[i, :] = X[0:dimensionality]

    return samples

max_stars_repo_name: maljovec/samply

max_issues_repo_name: maljovec/samply

max_forks_repo_name: maljovec/samplers


text:
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import numpy as np
from numpy.lib.stride_tricks import as_strided
import paddle
import unittest

from op_test import OpTest

def frame_from_librosa(x, frame_length, hop_length, axis=-1):
    if axis == -1 and not x.flags["C_CONTIGUOUS"]:
        x = np.ascontiguousarray(x)
    elif axis == 0 and not x.flags["F_CONTIGUOUS"]:
        x = np.asfortranarray(x)

    n_frames = 1 + (x.shape[axis] - frame_length) // hop_length
    strides = np.asarray(x.strides)

    if axis == -1:
        shape = list(x.shape)[:-1] + [frame_length, n_frames]
        strides = list(strides) + [hop_length * x.itemsize]

    elif axis == 0:
        shape = [n_frames, frame_length] + list(x.shape)[1:]
        strides = [hop_length * x.itemsize] + list(strides)

    else:
        raise ValueError("Frame axis={} must be either 0 or -1".format(axis))

    return as_strided(x, shape=shape, strides=strides)

def stft_np(x, window, n_fft, hop_length, **kwargs):
    frames = frame_from_librosa(x, n_fft, hop_length)
    frames = np.multiply(frames.transpose([0, 2, 1]),
                         window).transpose([0, 2, 1])
    res = np.fft.rfft(frames, axis=1)
    return res

class TestStftOp(OpTest):

    def setUp(self):
        self.op_type = "stft"
        self.shape, self.type, self.attrs = self.initTestCase()
        self.inputs = {
            'X': np.random.random(size=self.shape).astype(self.type),
            'Window': np.hamming(self.attrs['n_fft']).astype(self.type),
        }
        self.outputs = {
            'Out':
            stft_np(x=self.inputs['X'],
                    window=self.inputs['Window'],
                    **self.attrs)
        }

    def initTestCase(self):
        input_shape = (2, 100)
        input_type = 'float64'
        attrs = {
            'n_fft': 50,
            'hop_length': 15,
            'normalized': False,
            'onesided': True,
        }
        return input_shape, input_type, attrs

    def test_check_output(self):
        paddle.enable_static()
        self.check_output(check_eager=True)
        paddle.disable_static()

    def test_check_grad_normal(self):
        paddle.enable_static()
        self.check_grad(['X'], 'Out', check_eager=True)
        paddle.disable_static()

if __name__ == '__main__':
    unittest.main()

reason: import numpy,from numpy


text:
#!/usr/bin/env python

''' ---------------- About the script ----------------

Assignment 3: Finding text using edge detection

This script uses computer vision to extract language-like objects, such as letters and punctuation from the image. To accomplish this task several operations are executed: drawing region of interest, cropping the image, using Canny edge detection to 'find' every letter, contouring letters. After each operation the script saves a .jpg image in the data folder.

Example:
    $ python edge_detection.py

'''

"""---------------- Importing libraries ----------------
"""

import os
import sys
sys.path.append(os.path.join(".."))
import cv2
import numpy as np
import matplotlib.pyplot as plt

"""---------------- Main script ----------------
"""

def main():
    # Defining the path to image
    im_name = os.path.join("..", "data", "Memorial_IMG.jpg")
    # Reading the image
    image = cv2.imread(im_name)

    """------ Drawing Region of Interest (ROI) ------

    First, I find out the dimensions of the image so I know the scale and can decide what dimensions I should start with drawing the region
    of interest. Then, I set the start and end points for the x and y axis of the rectagle (ROI) by trial and error.
    I use this command: cv2.rectangle(image, start_point, end_point, color, thickness)

    """

    # Drawing a rectangle ROI around the text
    image_ROI = cv2.rectangle(image, (1400, 880), (2855, 2800), (0, 225, 0), 6)
    # Defining the directory where to save the image with RIO
    output_path_ROI = os.path.join("..", "data", "image_with_ROI.jpg")
    # Saving the image with RIO
    cv2.imwrite(output_path_ROI, image_ROI)
    # Printing that .jpg file has been saved
    print(f"\n[INFO] Image with ROI is saved in directory {output_path_ROI}")

    """------ Cropping the image within ROI ------

    To crop the image part within ROI I used simple slicing with indexing

    """

    # Cropping the image
    image_cropped = image_ROI[880:2800, 1400:2855]
    # Defining the directory where to save the cropped image
    output_path_cropped = os.path.join("..", "data", "image_cropped.jpg")
    # Saving the cropped image
    cv2.imwrite(output_path_cropped, image_cropped)
    # Printing that .jpg file has been saved
    print(f"\n[INFO] Cropped image within ROI is saved in directory {output_path_cropped}")

    """------ Canny edge detection ------

    Using the cropped image, I am applying Canny edge detection to 'find' every letter in the image

    Steps:

    - Image turned into greyscale
    - Applied Gaussian Blur
    - Applied Canny edge detection

    """

    # Making image greyscale for a better edge detection
    grey_image = cv2.cvtColor(image_cropped, cv2.COLOR_BGR2GRAY)
    # Appplying Gaussian Blur to remove the noise in the image
    blurred = cv2.GaussianBlur(grey_image, (5,5), 0)
    # Canny edge detection with minVal and maxVal
    canny = cv2.Canny(blurred, 115, 160)

    '''
    Above I experiment with two threshold values of cv2.Canny: minVal and maxVal, to reduce as much noise as possible while detecting as
    many letters as possible.
    Any edges with intensity gradient more than maxVal are sure to be edges and those below minVal are sure to be non-edges, so
    discarded. Those who lie between these two thresholds are classified edges or non-edges based on their connectivity. If they
    are connected to “sure-edge” pixels, they are considered to be part of edges. Otherwise, they are also discarded. '''

    # Defining the directory where to save the image after I applied canny edge detection
    output_path_canny = os.path.join("..", "data", "image_canny.jpg")
    # Saving the image
    cv2.imwrite(output_path_canny, canny)
    # Printing that .jpg file has been saved
    print(f"\n[INFO] Image with applied canny edge detection is saved in directory {output_path_canny}")

    """------ Finding letters´ contours ------

    Here I draw green contours around each detected letter

    """

    # Using cv2.findContours to find all the contours from the canny image
    (contours, _) = cv2.findContours(canny.copy(), # using a copy rather than an original image
                    cv2.RETR_EXTERNAL, # taking only the external structures and not for e.g. the edges within each coin
                    cv2.CHAIN_APPROX_SIMPLE # approximated contours
                    )

    # Original cropped image overlayed with contours
    image_letters = cv2.drawContours(image_cropped.copy(), # draw contours on original cropped
                        contours,      # list of contours
                        -1,            # which contours to draw
                        (0, 255, 0),   # contour colour
                        2)             # contour pixel width

    # Defining the directory where to save the contoured image
    output_path_contour = os.path.join("..", "data", "image_letters.jpg")
    # saving the cropped image
    cv2.imwrite(output_path_contour, image_letters)
    # Printing that .jpg file has been saved
    print(f"\n[INFO] Contoured image is saved in directory {output_path_contour}")

    # Final message to the user
    print(f"Success, the script was executed! Check 'data' folder for the output images!")

# Define behaviour when called from command line
if __name__=="__main__":
    main()


text:
import numpy as np
from abc import ABC, abstractmethod

class BaseGame(ABC):
    """
    Base Interface for Environment/Game.
    """

    @abstractmethod
    def step(self, actions):
        pass

    @abstractmethod
    def reset(self):
        pass

    @abstractmethod
    def render(self):
        pass

    @abstractmethod
    def get_rewards(self):
        pass

    @staticmethod
    @abstractmethod
    def get_game_list():
        pass

max_stars_repo_name: alvaro-serra/malib

max_issues_repo_name: Taospirit/malib

max_forks_repo_name: Taospirit/malib


text:
"""
Using the Rplot style sheet
========================================

This example shows the use of Rplot style sheet
"""

import numpy as np
import matplotlib.pyplot as plt
# make matplotlib to use the Rplot style sheet
plt.style.use('Rplot')

# data
y = np.sin(np.linspace(0, 2 * np.pi));
x = np.linspace(0,len(y),len(y));

# initialize a figure with proper figure size and the axis
Figure = plt.figure(figsize=(8,3));
Figure_Axis = plt.subplot(111)

# plot the data
Figure_Axis.plot(x,y, 'r-o',label="Legend");

# set axis labels
Figure_Axis.set_xlabel(r'Time [s]');
Figure_Axis.set_ylabel(r'Acceleration [g]');

# set tick mark spacing
plt.yticks(np.arange(min(y), max(y)+1, 0.5));
plt.xticks(np.arange(min(x), max(x)+1, 10));

# set x and y limit
Figure_Axis.set_xlim([0,50]);
Figure_Axis.set_ylim([-1,1]);

# enable grid lines
Figure_Axis.grid(b=True, which='major', color='k', linestyle='-')
Figure_Axis.grid(b=True, which='minor', color='k', linestyle='-', alpha=0.2)

# show the legend on the top outside the figure
Figure_Axis.legend(bbox_to_anchor=(0,1.02,1,0.2), loc="lower left",mode="expand", borderaxespad=0, ncol=5);

# have a tight layout to remove spaces
Figure.tight_layout();

# save the figure
plt.savefig('Example.png', bbox_inches = 'tight', dpi = 800);

max_stars_repo_name: SumeetSinha/Rplot

max_issues_repo_name: SumeetSinha/Rplot

max_forks_repo_name: SumeetSinha/Rplot


text:
import os
import pickle
import numpy as np
from PIL import Image
import h5py
import json
from glob import glob

import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
from transforms import Scale
from utils import collate_data, collate_data_GQA

def get_dataloader(cfg, mode="clevr"):
    if mode == "clevr":
        train_clevr = CLEVR(cfg.DATALOADER.FEATURES_PATH, train_percent=cfg.DATALOADER.DATA_PERCENT)
        train_dataloader = DataLoader(
            train_clevr, batch_size=cfg.DATALOADER.BATCH_SIZE, num_workers=cfg.DATALOADER.NUM_WORKERS, collate_fn=collate_data, drop_last=True, shuffle=True,
        )
        val_clevr = CLEVR(cfg.DATALOADER.FEATURES_PATH, 'val')
        val_dataloader = DataLoader(
            val_clevr, batch_size=cfg.DATALOADER.BATCH_SIZE, num_workers=cfg.DATALOADER.NUM_WORKERS, collate_fn=collate_data, drop_last=True
        )
        return train_dataloader, val_dataloader
    elif mode == "gqa":
        train_gqa = GQA(cfg.DATALOADER.FEATURES_PATH, 'train', cfg.DATALOADER.TRAIN_SPLIT, train_percent=cfg.DATALOADER.DATA_PERCENT)
        train_dataloader = DataLoader(
            train_gqa, batch_size=cfg.DATALOADER.BATCH_SIZE, num_workers=cfg.DATALOADER.NUM_WORKERS, collate_fn=collate_data_GQA, drop_last=True, shuffle=True,
        )
        val_gqa = GQA(cfg.DATALOADER.FEATURES_PATH, 'testdev', cfg.DATALOADER.VAL_SPLIT)
        val_dataloader = DataLoader(
            val_gqa, batch_size=cfg.DATALOADER.BATCH_SIZE, num_workers=cfg.DATALOADER.NUM_WORKERS, collate_fn=collate_data_GQA, drop_last=True
        )
    else:
        raise NotImplementedError()
    return train_dataloader, val_dataloader

class CLEVR(Dataset):
    def __init__(self, root, split='train', train_percent=1.0):
        features_path = os.path.join(root, 'features')
        with open('{}/{}.pkl'.format(features_path, split), 'rb') as f:
            self.data = pickle.load(f)

        self.root = root
        self.split = split
        self.train_percent = train_percent

        self.h = h5py.File('{}/{}_features.hdf5'.format(features_path, split), 'r')
        self.img = self.h['data']

    def close(self):
        self.h.close()

    def __getitem__(self, index):
        imgfile, question, answer, family = self.data[int(index/self.train_percent)]

        id = int(imgfile.rsplit('_', 1)[1][:-4])
        img = torch.from_numpy(self.img[id])

        return img, question, len(question), answer, family, index

    def __len__(self):
        return int(len(self.data) * self.train_percent)

class GQA(Dataset):
    def __init__(self, root, split='train', variant='all', train_percent=1.0):
        features_path = os.path.join(root, 'features')

        self.root = root
        self.split = split
        self.train_percent = train_percent

        # load tokenized questions
        with open('{}/{}_{}.pkl'.format(features_path, variant, split), 'rb') as f:
            self.data = pickle.load(f)

        # load object features
        objects_path = os.path.join(features_path, 'objects')

        with open(os.path.join(objects_path, 'gqa_objects_info.json')) as f:
            self.objects_info = json.load(f)

        sorted_h5_paths = sorted(
            glob('{}/gqa_objects_*.h5'.format(objects_path)),
            key=lambda path: int(os.path.basename(path).split('_')[-1].split('.')[0])
        )

        self.h5s = [h5py.File(h5_path, 'r') for h5_path in sorted_h5_paths]
        self.feature_h5s = [h5_file['features'] for h5_file in self.h5s]

    def close(self):
        for file in self.h5s:
            file.close()

    def __getitem__(self, q_index):
        imgfile, question, answer = self.data[int(q_index/self.train_percent)]

        object_info = self.objects_info[imgfile]
        file = object_info['file']
        img_idx = object_info['idx']
        num_objects = object_info['objectsNum']

        img_objects = torch.from_numpy(self.feature_h5s[file][img_idx])   # (100, 2048)
        img_objects = img_objects.t().unsqueeze(1)   # (2048, 1, 100)

        return img_objects, num_objects, question, len(question), answer, q_index

    def __len__(self):
        return int(len(self.data) * self.train_percent)


text:
#!/usr/bin/python

import numpy as np
import services.tools as tls
import matplotlib.pyplot as plt
from PIL import Image

#------------------------------------------------------------------------------------------
# Plot slices from the selected ROI
#------------------------------------------------------------------------------------------

def get_sag_slices(data_L, data_R, sag_l, sag_r):
    selected_data_L = data_L[sag_l[0]:sag_l[1], :, :]
    selected_data_R = data_R[sag_r[0]:sag_r[1], :, :]
    return selected_data_L, selected_data_R

def get_cor_slices(data_L, data_R, cor_l, cor_r):
    selected_data_L = data_L[:, cor_l[0]:cor_l[1], :]
    selected_data_R = data_R[:, cor_r[0]:cor_r[1], :]
    return selected_data_L, selected_data_R

def get_axi_slices(data_L, data_R, axi_l, axi_r):
    selected_data_L = data_L[:, :, axi_l[0]:axi_l[1]]
    selected_data_R = data_R[:, :, axi_r[0]:axi_r[1]]
    return selected_data_L, selected_data_R

def plot_ROI_all(data_roi_L, data_roi_R, left_dims, right_dims):
    sag_l, cor_l, axi_l = left_dims
    sag_r, cor_r, axi_r = right_dims
    # sagittal slices
    sag_L, sag_R = get_sag_slices(data_roi_L, data_roi_R, sag_l, sag_r)
    cor_L, cor_R = get_cor_slices(data_roi_L, data_roi_R, cor_l, cor_r)
    axi_L, axi_R = get_axi_slices(data_roi_L, data_roi_R, axi_l, axi_r)

    # """ Function to display row of image slices """
    # fig, axes = plt.subplots(1, len(slices))
    # for i, slice in enumerate(slices):
    #     axes[i].imshow(slice.T, cmap="gray", origin="lower")

    # plot 2D slice from ROI (m-1, m, m+1)
    for i in range(3):
        plt.subplot(3, 6, i+1)
        plt.imshow(sag_L[i, :, :], cmap='gray')
        plt.subplot(3, 6, 4+i)
        plt.imshow(sag_R[i, :, :], cmap='gray')

        plt.subplot(3, 6, 6+i+1)
        plt.imshow(cor_L[:, i, :], cmap='gray')
        plt.subplot(3, 6, 6+4+i)
        plt.imshow(cor_R[:, i, :], cmap='gray')

        plt.subplot(3, 6, 12+i+1)
        plt.imshow(axi_L[:, :, i], cmap='gray')
        plt.subplot(3, 6, 12+4+i)
        plt.imshow(axi_R[:, :, i], cmap='gray')
    plt.show()


text:
import os
import tables

import h5py
import numpy
from numpy.testing import assert_equal, assert_raises
from six.moves import range, cPickle

from fuel.datasets.hdf5 import PytablesDataset, H5PYDataset
from fuel.streams import DataStream
from fuel.schemes import SequentialScheme

class TestPytablesDataset(object):
    def setUp(self):
        num_rows = 500
        filters = tables.Filters(complib='blosc', complevel=5)
        h5file = tables.open_file(
            'tmp.h5', mode='w', title='Test', filters=filters)
        group = h5file.create_group("/", 'Data')
        atom = tables.UInt8Atom()
        y = h5file.create_carray(group, 'y', atom=atom, title='Data targets',
                                 shape=(num_rows, 1), filters=filters)
        for i in range(num_rows):
            y[i] = i
        h5file.flush()
        h5file.close()
        self.dataset = PytablesDataset('tmp.h5', ('y',), 20, 500)
        self.dataset_default = PytablesDataset('tmp.h5', ('y',))

    def tearDown(self):
        self.dataset.close_file()
        self.dataset_default.close_file()
        os.remove('tmp.h5')

    def test_dataset_default(self):
        assert self.dataset_default.start == 0
        assert self.dataset_default.stop == 500

    def test_get_data_slice_request(self):
        assert_equal(self.dataset.get_data(request=slice(0, 10))[0],
                     numpy.arange(20, 30).reshape(10, 1))

    def test_get_data_list_request(self):
        assert_equal(self.dataset.get_data(request=list(range(10)))[0],
                     numpy.arange(20, 30).reshape(10, 1))

    def test_get_data_value_error(self):
        assert_raises(ValueError, self.dataset.get_data, None, True)

    def test_pickling(self):
        dataset = cPickle.loads(cPickle.dumps(self.dataset))
        assert_equal(len(dataset.nodes), 1)

class TestH5PYDataset(object):
    def setUp(self):
        self.features = numpy.arange(3600, dtype='uint16').reshape((100, 36))
        self.targets = numpy.arange(30, dtype='uint8').reshape((30, 1))
        h5file = h5py.File(
            'file.hdf5', mode='w', driver='core', backing_store=False)
        h5file['features'] = self.features
        h5file['features'].dims[0].label = 'batch'
        h5file['features'].dims[1].label = 'feature'
        h5file['targets'] = self.targets
        h5file['targets'].dims[0].label = 'batch'
        h5file['targets'].dims[1].label = 'index'
        split_dict = {'train': {'features': (0, 20, None), 'targets': (0, 20)},
                      'test': {'features': (20, 30), 'targets': (20, 30)},
                      'unlabeled': {'features': (30, 100, None, '.')}}
        h5file.attrs['split'] = H5PYDataset.create_split_array(split_dict)
        self.h5file = h5file

        vlen_h5file = h5py.File(
            'test_vl.hdf5', mode='w', driver='core', backing_store=False)
        self.vlen_features = [
            numpy.arange(12, dtype='uint8').reshape((3, 2, 2)),
            numpy.arange(48, dtype='uint8').reshape((3, 4, 4)),
            numpy.arange(60, dtype='uint8').reshape((3, 5, 4)),
            numpy.arange(18, dtype='uint8').reshape((3, 2, 3))]
        self.vlen_targets = numpy.arange(4, dtype='uint8').reshape((4, 1))
        dtype = h5py.special_dtype(vlen=numpy.dtype('uint8'))
        features = vlen_h5file.create_dataset('features', (4,), dtype=dtype)
        features[...] = [d.flatten() for d in self.vlen_features]
        features.dims[0].label = 'batch'
        features_shapes = vlen_h5file.create_dataset(
            'features_shapes', (4, 3), dtype='uint8')
        features_shapes[...] = numpy.array(
            [d.shape for d in self.vlen_features])
        features.dims.create_scale(features_shapes, 'shapes')
        features.dims[0].attach_scale(features_shapes)
        features_shape_labels = vlen_h5file.create_dataset(
            'features_shape_labels', (3,), dtype='S7')
        features_shape_labels[...] = [
            'channel'.encode('utf8'), 'height'.encode('utf8'),
            'width'.encode('utf8')]
        features.dims.create_scale(features_shape_labels, 'shape_labels')
        features.dims[0].attach_scale(features_shape_labels)
        targets = vlen_h5file.create_dataset('targets', (4, 1), dtype='uint8')
        targets[...] = self.vlen_targets
        targets.dims[0].label = 'batch'
        targets.dims[1].label = 'index'
        split_dict = {'train': {'features': (0, 4), 'targets': (0, 4)}}
        vlen_h5file.attrs['split'] = H5PYDataset.create_split_array(split_dict)
        self.vlen_h5file = vlen_h5file

    def tearDown(self):
        self.h5file.close()
        self.vlen_h5file.close()

    def test_raises_value_error_when_which_sets_is_string(self):
        assert_raises(ValueError, H5PYDataset, self.h5file, 'train')

    def test_split_parsing(self):
        train_set = H5PYDataset(self.h5file, which_sets=('train',))
        assert train_set.provides_sources == ('features', 'targets')
        test_set = H5PYDataset(self.h5file, which_sets=('test',))
        assert test_set.provides_sources == ('features', 'targets')
        unlabeled_set = H5PYDataset(self.h5file, which_sets=('unlabeled',))
        assert unlabeled_set.provides_sources == ('features',)

    def test_get_all_splits(self):
        splits = ('train', 'test', 'unlabeled')
        available_splits = H5PYDataset.get_all_splits(self.h5file)
        assert (all(split in available_splits for split in splits) and
                all(split in splits for split in available_splits))

    def test_get_all_sources(self):
        sources = ('features', 'targets')
        all_sources = H5PYDataset.get_all_sources(self.h5file)
        assert (all(source in all_sources for source in sources) and
                all(source in sources for source in all_sources))

    def test_axis_labels(self):
        dataset = H5PYDataset(self.h5file, which_sets=('train',))
        assert dataset.axis_labels == {'features': ('batch', 'feature'),
                                       'targets': ('batch', 'index')}

    def test_pickling(self):
        try:
            features = numpy.arange(360, dtype='uint16').reshape((10, 36))
            h5file = h5py.File('file.hdf5', mode='w')
            h5file['features'] = features
            split_dict = {'train': {'features': (0, 10, None, '.')}}
            h5file.attrs['split'] = H5PYDataset.create_split_array(split_dict)
            dataset = cPickle.loads(
                cPickle.dumps(H5PYDataset(h5file, which_sets=('train',))))
            # Make sure _out_of_memory_{open,close} accesses
            # external_file_handle rather than _external_file_handle
            dataset._out_of_memory_open()
            dataset._out_of_memory_close()
            assert dataset.data_sources is None
        finally:
            os.remove('file.hdf5')

    def test_data_stream_pickling(self):
        stream = DataStream(H5PYDataset(self.h5file, which_sets=('train',)),
                            iteration_scheme=SequentialScheme(100, 10))
        cPickle.loads(cPickle.dumps(stream))
        stream.close()

    def test_multiple_instances(self):
        dataset_1 = H5PYDataset(self.h5file, which_sets=('train',))
        dataset_2 = H5PYDataset(self.h5file, which_sets=('train',))
        handle_1 = dataset_1.open()
        handle_2 = dataset_2.open()
        dataset_1.get_data(state=handle_1, request=slice(0, 10))
        dataset_2.get_data(state=handle_2, request=slice(0, 10))
        dataset_1.close(handle_1)
        dataset_2.close(handle_2)

    def test_single_split(self):
        train_set = H5PYDataset(self.h5file, which_sets=('train',))
        test_set = H5PYDataset(self.h5file, which_sets=('test',))
        train_handle = train_set.open()
        test_handle = test_set.open()
        assert_equal(train_set.get_data(train_handle, slice(0, 8)),
                     (self.features[:8], self.targets[:8]))
        assert_equal(test_set.get_data(test_handle, slice(0, 2)),
                     (self.features[20:22], self.targets[20:22]))
        train_set.close(train_handle)
        test_set.close(test_handle)

    def test_multiple_split_in_memory(self):
        dataset = H5PYDataset(self.h5file, which_sets=('train', 'test'),
                              load_in_memory=True)
        handle = dataset.open()
        assert_equal(dataset.get_data(handle, slice(0, 30)),
                     (self.features[:30], self.targets[:30]))
        dataset.close(handle)

    def test_multiple_split_out_of_memory_list_request(self):
        dataset = H5PYDataset(self.h5file, which_sets=('train', 'test'),
                              load_in_memory=False)
        handle = dataset.open()
        assert_equal(dataset.get_data(handle, list(range(30))),
                     (self.features[:30], self.targets[:30]))
        dataset.close(handle)

    def test_out_of_memory(self):
        dataset = H5PYDataset(
            self.h5file, which_sets=('test',), load_in_memory=False)
        handle = dataset.open()
        assert_equal(dataset.get_data(handle, slice(3, 5)),
                     (self.features[23:25], self.targets[23:25]))
        dataset.close(handle)

    def test_in_memory(self):
        dataset = H5PYDataset(
            self.h5file, which_sets=('train',), load_in_memory=True)
        handle = dataset.open()
        request = slice(0, 10)
        assert_equal(dataset.get_data(handle, request),
                     (self.features[request], self.targets[request]))
        dataset.close(handle)

    def test_out_of_memory_sorted_indices(self):
        dataset = H5PYDataset(
            self.h5file, which_sets=('train',), load_in_memory=False,
            sort_indices=True)
        handle = dataset.open()
        request = [7, 4, 6, 2, 5]
        assert_equal(dataset.get_data(handle, request),
                     (self.features[request], self.targets[request]))
        dataset.close(handle)

    def test_out_of_memory_unsorted_indices(self):
        dataset = H5PYDataset(
            self.h5file, which_sets=('train',), load_in_memory=False,
            sort_indices=False)
        handle = dataset.open()
        assert_raises(TypeError, dataset.get_data, handle, [7, 4, 6, 2, 5])
        dataset.close(handle)

    def test_value_error_on_unequal_sources(self):
        def get_subsets():
            return H5PYDataset(self.h5file, which_sets=('train',)).subsets
        split_dict = {'train': {'features': (0, 20), 'targets': (0, 15)},
                      'test': {'features': (20, 30), 'targets': (20, 30)},
                      'unlabeled': {'features': (30, 100, None, '.')}}
        self.h5file.attrs['split'] = H5PYDataset.create_split_array(split_dict)
        assert_raises(ValueError, get_subsets)

    def test_io_error_on_unopened_file_handle(self):
        def get_file_handle():
            dataset = H5PYDataset(self.h5file, which_sets=('train',))
            dataset._external_file_handle = None
            return dataset._file_handle
        assert_raises(IOError, get_file_handle)

    def test_value_error_in_memory_get_data(self):
        dataset = H5PYDataset(self.h5file, which_sets=('train',))
        assert_raises(ValueError, dataset._in_memory_get_data, None, None)
        assert_raises(ValueError, dataset._in_memory_get_data, True, None)

    def test_value_error_out_of_memory_get_data(self):
        dataset = H5PYDataset(self.h5file, which_sets=('train',))
        assert_raises(ValueError, dataset._out_of_memory_get_data, None, True)

    def test_index_split_out_of_memory(self):
        features = numpy.arange(50, dtype='uint8').reshape((10, 5))
        h5file = h5py.File(
            'index_split.hdf5', mode='w', driver='core', backing_store=False)
        h5file['features'] = features
        h5file['features'].dims[0].label = 'batch'
        h5file['features'].dims[1].label = 'feature'
        h5file['train_features_subset'] = numpy.arange(0, 10, 2)
        h5file['test_features_subset'] = numpy.arange(1, 10, 2)
        train_ref = h5file['train_features_subset'].ref
        test_ref = h5file['test_features_subset'].ref
        split_dict = {'train': {'features': (-1, -1, train_ref, '.')},
                      'test': {'features': (-1, -1, test_ref, '')}}
        h5file.attrs['split'] = H5PYDataset.create_split_array(split_dict)
        dataset = H5PYDataset(
            h5file, which_sets=('train',), load_in_memory=False)
        handle = dataset.open()
        request = slice(0, 5)
        assert_equal(
            dataset.get_data(handle, request)[0], features[0:10:2])
        assert_equal(dataset.num_examples, 5)
        dataset.close(handle)

    def test_index_split_in_memory(self):
        features = numpy.arange(50, dtype='uint8').reshape((10, 5))
        h5file = h5py.File(
            'index_split.hdf5', mode='w', driver='core', backing_store=False)
        h5file['features'] = features
        h5file['features'].dims[0].label = 'batch'
        h5file['features'].dims[1].label = 'feature'
        h5file['train_features_subset'] = numpy.arange(0, 10, 2)
        h5file['test_features_subset'] = numpy.arange(1, 10, 2)
        train_ref = h5file['train_features_subset'].ref
        test_ref = h5file['test_features_subset'].ref
        split_dict = {'train': {'features': (-1, -1, train_ref, '.')},
                      'test': {'features': (-1, -1, test_ref, '')}}
        h5file.attrs['split'] = H5PYDataset.create_split_array(split_dict)
        dataset = H5PYDataset(
            h5file, which_sets=('train',), load_in_memory=True)
        handle = dataset.open()
        request = slice(0, 5)
        assert_equal(
            dataset.get_data(handle, request)[0], features[0:10:2])
        assert_equal(dataset.num_examples, 5)
        dataset.close(handle)

    def test_index_subset_sorted(self):
        dataset = H5PYDataset(
            self.h5file, which_sets=('train',), subset=[0, 2, 4])
        handle = dataset.open()
        request = slice(0, 3)
        assert_equal(dataset.get_data(handle, request),
                     (self.features[[0, 2, 4]], self.targets[[0, 2, 4]]))
        dataset.close(handle)

    def test_index_subset_unsorted(self):
        # A subset should have the same ordering no matter how you specify it.
        dataset = H5PYDataset(
            self.h5file, which_sets=('train',), subset=[0, 4, 2])
        handle = dataset.open()
        request = slice(0, 3)
        assert_equal(dataset.get_data(handle, request),
                     (self.features[[0, 2, 4]], self.targets[[0, 2, 4]]))
        dataset.close(handle)

    def test_vlen_axis_labels(self):
        dataset = H5PYDataset(self.vlen_h5file, which_sets=('train',))
        assert_equal(dataset.axis_labels['features'],
                     ('batch', 'channel', 'height', 'width'))
        assert_equal(dataset.axis_labels['targets'], ('batch', 'index'))

    def test_vlen_sources_raises_error_on_dim_gt_1(self):
        targets = self.vlen_h5file['targets']
        targets_shapes = self.vlen_h5file.create_dataset(
            'targets_shapes', (4, 1), dtype='uint8')
        targets.dims.create_scale(targets_shapes, 'shapes')
        targets.dims[0].attach_scale(targets_shapes)
        assert_raises(ValueError, H5PYDataset, self.vlen_h5file, 'train')

    def test_vlen_reshape_in_memory(self):
        dataset = H5PYDataset(
            self.vlen_h5file, which_sets=('train',), subset=slice(1, 3),
            load_in_memory=True)
        expected_features = numpy.empty((2,), dtype=numpy.object)
        for i, f in enumerate(self.vlen_features[1:3]):
            expected_features[i] = f
        expected_targets = self.vlen_targets[1:3]
        handle = dataset.open()
        rval = dataset.get_data(handle, slice(0, 2))
        for val, truth in zip(rval[0], expected_features):
            assert_equal(val, truth)
        assert_equal(rval[1], expected_targets)
        dataset.close(handle)

    def test_vlen_reshape_out_of_memory(self):
        dataset = H5PYDataset(
            self.vlen_h5file, which_sets=('train',), subset=slice(1, 3),
            load_in_memory=False)
        expected_features = numpy.empty((2,), dtype=numpy.object)
        for i, f in enumerate(self.vlen_features[1:3]):
            expected_features[i] = f
        expected_targets = self.vlen_targets[1:3]
        handle = dataset.open()
        rval = dataset.get_data(handle, slice(0, 2))
        for val, truth in zip(rval[0], expected_features):
            assert_equal(val, truth)
        assert_equal(rval[1], expected_targets)
        dataset.close(handle)

    def test_vlen_reshape_out_of_memory_unordered(self):
        dataset = H5PYDataset(
            self.vlen_h5file, which_sets=('train',), load_in_memory=False)
        expected_features = numpy.empty((4,), dtype=numpy.object)
        for i, j in enumerate([0, 3, 1, 2]):
            expected_features[i] = self.vlen_features[j]
        expected_targets = self.vlen_targets[[0, 3, 1, 2]]
        handle = dataset.open()
        rval = dataset.get_data(handle, [0, 3, 1, 2])
        for val, truth in zip(rval[0], expected_features):
            assert_equal(val, truth)
        assert_equal(rval[1], expected_targets)
        dataset.close(handle)

    def test_vlen_reshape_out_of_memory_unordered_no_check(self):
        dataset = H5PYDataset(
            self.vlen_h5file, which_sets=('train',), load_in_memory=False,
            sort_indices=False)
        expected_features = numpy.empty((4,), dtype=numpy.object)
        for i, j in enumerate([0, 1, 2, 3]):
            expected_features[i] = self.vlen_features[j]
        expected_targets = self.vlen_targets[[0, 1, 2, 3]]
        handle = dataset.open()
        rval = dataset.get_data(handle, [0, 1, 2, 3])
        for val, truth in zip(rval[0], expected_features):
            assert_equal(val, truth)
        assert_equal(rval[1], expected_targets)
        dataset.close(handle)


text:
"""
Generate Fig.3 of the article
"""
import argparse
import numpy as np
import matplotlib.pyplot as plt
import os
from logging import Formatter, StreamHandler, getLogger, INFO
logger = getLogger(__name__)

plt.rcParams.update({'font.size': 26})

parser = argparse.ArgumentParser(description='options')
parser.add_argument('--eid', type=str, default='taslp', help='experiment id for log')

markers = ['o', 'v', '^', '<', '>', 's', '*', '+', 'x', 'd', 'o', 'v']
styles = [
    'solid',
    (0, (2, 2)),
    (0, (3, 1)),
    'dotted',
    (0, (5, 1)),
    (0, (3, 1, 1, 1, 1, 1)),
    (0, (4, 1, 1, 1)),
]
cmap = plt.get_cmap("tab20")
cids = [7, 6, 9, 8, 1, 0]

def read_logfile(log_fn: str):

    with open(log_fn, 'r') as f:
        lines = f.readlines()

    ax_t, train_loss_sed, train_loss_doa, valid_loss_sed, valid_loss_doa = [], [], [], [], []
    flg = False
    for line in lines:
        ss = line.split()
        if '[INFO]Epoch' in line:
            ax_t.append(int(ss[-5].replace(',', '')))
            train_loss_sed.append(float(ss[-3].replace(',', '')))
            train_loss_doa.append(float(ss[-1].replace(',', '')))
            flg = True
        elif flg:
            valid_loss_sed.append(float(ss[3].replace(',', '')))
            valid_loss_doa.append(float(ss[5].replace(',', '')))
            flg = False

    return [train_loss_sed, train_loss_doa, valid_loss_sed, valid_loss_doa]

if __name__ == '__main__':
    logger.setLevel(INFO)
    handler = StreamHandler()
    handler.setFormatter(Formatter('%(asctime)s %(name)s,l%(lineno)03d[%(levelname)s]%(message)s'))
    logger.addHandler(handler)
    args = parser.parse_args()

    experiment_id = args.eid
    dirpath = os.path.join('./article_figure/', experiment_id)
    try:
        os.mkdir(dirpath)
    except FileExistsError:
        logger.info('Output directory ({:s}) already exists.'.format(dirpath))

    exp_conds = [
        # Enumerate experimental conditions and the corresponding training log file paths here like below:
        # ('Base.', './result/2020-08-05_18-42-39_017557.log'),
        # ('Base. (w time equiv.)', './result/2020-08-05_18-39-45_357551.log'),
        # ('Base. (w rot. equiv.)', './result/2020-08-05_18-41-56_214096.log'),
        # ('Base. (w rot. & time equiv.)', './result/2020-08-05_18-40-43_873531.log'),
        # ('Prop. (w scale equiv.)', './result/2020-08-05_18-35-38_538725.log'),
        # ('Prop. (w time & scale equiv.)', './result/2020-07-30_21-32-37_017604.log'),
    ]

    train_loss_sed, train_loss_doa, validation_loss_sed, validation_loss_doa = [], [], [], []
    for _, log_fn in exp_conds:
        a, b, c, d = read_logfile(log_fn)
        train_loss_sed.append(a)
        train_loss_doa.append(b)
        validation_loss_sed.append(c)
        validation_loss_doa.append(d)

    losses = [train_loss_sed, train_loss_doa, validation_loss_sed, validation_loss_doa]

    fig, axes = plt.subplots(1, 4, figsize=(36.0, 12))

    titles = [
        'Training loss (SED)',
        'Training loss (DOA)',
        'Validation loss (SED)',
        'Validation loss (DOA)',
    ]
    yranges = [
        [0.0, 0.25],
        [0.0, 1.4],
        [0.0, 0.25],
        [0.0, 1.4],
    ]
    for j, c in enumerate(exp_conds):
        for d, (loss_d, ax) in enumerate(zip(losses, axes.flatten())):
            ax.plot(np.arange(len(loss_d[j])) + 1, loss_d[j], color=cmap(cids[j]),
                    linewidth=5, linestyle=styles[j], label=c[0])

    for d, (ax, title, yrange) in enumerate(zip(axes.flatten(), titles, yranges)):
        ax.grid(which='major', color='black', linestyle=':', linewidth=2)
        ax.set_xlabel('Epoch')
        ax.set_xlim([0, 100])
        ax.set_title(title)
        ax.set_ylim(yrange)
        if d == 0:
            ax.set_ylabel('Loss')
            ax.legend(loc='upper right', borderaxespad=0)
    fig.tight_layout()
    fig.savefig(os.path.join(dirpath, 'Fig3-Lossinfo.pdf'))
    fig.clf()

max_stars_repo_name: nttrd-mdlab/group-equiv-seld

max_issues_repo_name: nttrd-mdlab/group-equiv-seld

max_forks_repo_name: nttrd-mdlab/group-equiv-seld