language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
Python
async def topdeathstoday(self, ctx, amount: int = 6): """Show X countries with top amount of deaths today. Defaults to 6. """ if amount > 20 or amount < 0: return await ctx.send("Invalid amount. Please choose between an amount between 1-20.") async with ctx.typing(): data = await self.get(self.api + "/countries?sort = todayDeaths") if isinstance(data, dict): error = data.get("failed") if error is not None: return await ctx.send(error) if not data: return await ctx.send("No data available.") embed = discord.Embed( color = 0xf34949, title= "Covid-19 | Top {} Deaths Today ".format(amount), timestamp = datetime.datetime.utcfromtimestamp(data[0]["updated"] / 1000), ) for i in range(amount): cases = self.humanize_number(data[i]["cases"]) deaths = self.humanize_number(data[i]["deaths"]) recovered = self.humanize_number(data[i]["recovered"]) todayCases = self.humanize_number(data[i]["todayCases"]) todayDeaths = self.humanize_number(data[i]["todayDeaths"]) critical = self.humanize_number(data[i]["critical"]) msg = str('**Cases**: {}\n**Deaths**: {}\n**Recovered**: {}\n**Cases Today**: {}' + '\n**Deaths Today**: {}\n**Critical**: {}').format(cases, deaths, recovered, todayCases, todayDeaths, critical) embed.add_field(name = data[i]["country"], value = msg) await ctx.send(embed = embed)
async def topdeathstoday(self, ctx, amount: int = 6): """Show X countries with top amount of deaths today. Defaults to 6. """ if amount > 20 or amount < 0: return await ctx.send("Invalid amount. Please choose between an amount between 1-20.") async with ctx.typing(): data = await self.get(self.api + "/countries?sort = todayDeaths") if isinstance(data, dict): error = data.get("failed") if error is not None: return await ctx.send(error) if not data: return await ctx.send("No data available.") embed = discord.Embed( color = 0xf34949, title= "Covid-19 | Top {} Deaths Today ".format(amount), timestamp = datetime.datetime.utcfromtimestamp(data[0]["updated"] / 1000), ) for i in range(amount): cases = self.humanize_number(data[i]["cases"]) deaths = self.humanize_number(data[i]["deaths"]) recovered = self.humanize_number(data[i]["recovered"]) todayCases = self.humanize_number(data[i]["todayCases"]) todayDeaths = self.humanize_number(data[i]["todayDeaths"]) critical = self.humanize_number(data[i]["critical"]) msg = str('**Cases**: {}\n**Deaths**: {}\n**Recovered**: {}\n**Cases Today**: {}' + '\n**Deaths Today**: {}\n**Critical**: {}').format(cases, deaths, recovered, todayCases, todayDeaths, critical) embed.add_field(name = data[i]["country"], value = msg) await ctx.send(embed = embed)
Python
async def state(self, ctx, *, states: str): """Show stats for specific states. Supports multiple countries seperated by a comma. Example: luci covid state New York, California """ if not states: return await ctx.send_help() async with ctx.typing(): states = ",".join(states.split(", ")) data = await self.get(self.api + "/states/{}".format(states)) if isinstance(data, dict): error = data.get("failed") if error is not None: return await ctx.send(error) data = [data] if not data: return await ctx.send("No data available.") await GenericMenu(source = CovidStateMenu(data), ctx = ctx, type= "Today").start( ctx = ctx, wait = False, )
async def state(self, ctx, *, states: str): """Show stats for specific states. Supports multiple countries seperated by a comma. Example: luci covid state New York, California """ if not states: return await ctx.send_help() async with ctx.typing(): states = ",".join(states.split(", ")) data = await self.get(self.api + "/states/{}".format(states)) if isinstance(data, dict): error = data.get("failed") if error is not None: return await ctx.send(error) data = [data] if not data: return await ctx.send("No data available.") await GenericMenu(source = CovidStateMenu(data), ctx = ctx, type= "Today").start( ctx = ctx, wait = False, )
Python
async def _yesterday(self, ctx, *, states: str): """Show stats for yesterday for specific states. Supports multiple countries seperated by a comma. Example: luci covid state yesterday New York, California. """ async with ctx.typing(): states = ",".join(states.split(", ")) data = await self.get(self.api + "/states/{}?yesterday = 1".format(states)) if isinstance(data, dict): error = data.get("failed") if error is not None: return await ctx.send(error) data = [data] if not data: return await ctx.send("No data available.") await GenericMenu(source = CovidStateMenu(data), ctx = ctx, type= "Yesterday").start( ctx = ctx, wait = False, )
async def _yesterday(self, ctx, *, states: str): """Show stats for yesterday for specific states. Supports multiple countries seperated by a comma. Example: luci covid state yesterday New York, California. """ async with ctx.typing(): states = ",".join(states.split(", ")) data = await self.get(self.api + "/states/{}?yesterday = 1".format(states)) if isinstance(data, dict): error = data.get("failed") if error is not None: return await ctx.send(error) data = [data] if not data: return await ctx.send("No data available.") await GenericMenu(source = CovidStateMenu(data), ctx = ctx, type= "Yesterday").start( ctx = ctx, wait = False, )
Python
async def format_mod_embed(self, ctx, user, success, method, duration = None, location = None): """Helper function to format an embed to prevent extra code""" embed = discord.Embed(timestamp = ctx.message.created_at) embed.set_author(name = method.title(), icon_url = user.avatar_url) embed.color = 0xf34949 embed.set_footer(text = f"User ID: {user.id}") if success: if method == "ban" or method == "hackban": embed.description = f"{user} was just {method}ned." elif method == "unmute" or method == "kick": embed.description = f"{user} was just {method}d." elif method == "mute": embed.description = f"{user} was just {method}d for {duration}." elif method == "channel-locked" or method == "server-locked": embed.description = f"`{location.name}` is now in lockdown mode!" elif method == "channel-unlocked" or method == "server-unlocked": embed.description = f"`{location.name}` is now unlocked. Enjoy!" else: embed.description = f"{user} was just {method}ed." else: if method == "lock" or "channel-locked": embed.description = f"You do not have the permissions to {method} `{location.name}`." if method == "unlock" or "channel-unlocked": embed.description = f"You do not have the permissions to {method} `{location.name}`." else: embed.description = f"You do not have the permissions to {method} {user.name}." return embed
async def format_mod_embed(self, ctx, user, success, method, duration = None, location = None): """Helper function to format an embed to prevent extra code""" embed = discord.Embed(timestamp = ctx.message.created_at) embed.set_author(name = method.title(), icon_url = user.avatar_url) embed.color = 0xf34949 embed.set_footer(text = f"User ID: {user.id}") if success: if method == "ban" or method == "hackban": embed.description = f"{user} was just {method}ned." elif method == "unmute" or method == "kick": embed.description = f"{user} was just {method}d." elif method == "mute": embed.description = f"{user} was just {method}d for {duration}." elif method == "channel-locked" or method == "server-locked": embed.description = f"`{location.name}` is now in lockdown mode!" elif method == "channel-unlocked" or method == "server-unlocked": embed.description = f"`{location.name}` is now unlocked. Enjoy!" else: embed.description = f"{user} was just {method}ed." else: if method == "lock" or "channel-locked": embed.description = f"You do not have the permissions to {method} `{location.name}`." if method == "unlock" or "channel-unlocked": embed.description = f"You do not have the permissions to {method} `{location.name}`." else: embed.description = f"You do not have the permissions to {method} {user.name}." return embed
Python
async def kick(self, ctx, member: discord.Member, *, reason = None): """Kick someone from the server.""" try: await ctx.guild.kick(member, reason = reason) except: success = False else: success = True embed = await self.format_mod_embed(ctx, member, success, "kick") await ctx.send(embed = embed)
async def kick(self, ctx, member: discord.Member, *, reason = None): """Kick someone from the server.""" try: await ctx.guild.kick(member, reason = reason) except: success = False else: success = True embed = await self.format_mod_embed(ctx, member, success, "kick") await ctx.send(embed = embed)
Python
async def ban(self, ctx, member: discord.Member, *, reason = None): """Ban someone from the server.""" if (member == ctx.author): await ctx.send("Boomer! you can't ban yourself 🤦‍♂️") try: await ctx.guild.ban(member, reason = reason) await member.send(f"You have been banned in {ctx.guild} for {reason}" if reason != None \ else f"You have been banned in {ctx.guild}") except: success = False else: success = True embed = await self.format_mod_embed(ctx, member, success, "ban") await ctx.send(embed = embed)
async def ban(self, ctx, member: discord.Member, *, reason = None): """Ban someone from the server.""" if (member == ctx.author): await ctx.send("Boomer! you can't ban yourself 🤦‍♂️") try: await ctx.guild.ban(member, reason = reason) await member.send(f"You have been banned in {ctx.guild} for {reason}" if reason != None \ else f"You have been banned in {ctx.guild}") except: success = False else: success = True embed = await self.format_mod_embed(ctx, member, success, "ban") await ctx.send(embed = embed)
Python
async def bans(self, ctx): """See a list of banned users in the guild""" bans = await ctx.guild.bans() embed = discord.Embed(title = f"List of Banned Members ({len(bans)}):") embed.description = ", ".join([str(b.user) for b in bans]) embed.color = 0xf34949 await ctx.send(embed = embed)
async def bans(self, ctx): """See a list of banned users in the guild""" bans = await ctx.guild.bans() embed = discord.Embed(title = f"List of Banned Members ({len(bans)}):") embed.description = ", ".join([str(b.user) for b in bans]) embed.color = 0xf34949 await ctx.send(embed = embed)
Python
async def baninfo(self, ctx, *, member: GetFetchUser): """Check the reason of a ban from the audit logs.""" ban = await ctx.guild.fetch_ban(member) embed = discord.Embed() embed.color = 0xf34949 embed.set_author(name = str(ban.user), icon_url = ban.user.avatar_url) embed.add_field(name="Reason", value = ban.reason or "None") embed.set_thumbnail(url = ban.user.avatar_url) embed.set_footer(text = f"User ID: {ban.user.id}") await ctx.send(embed = embed)
async def baninfo(self, ctx, *, member: GetFetchUser): """Check the reason of a ban from the audit logs.""" ban = await ctx.guild.fetch_ban(member) embed = discord.Embed() embed.color = 0xf34949 embed.set_author(name = str(ban.user), icon_url = ban.user.avatar_url) embed.add_field(name="Reason", value = ban.reason or "None") embed.set_thumbnail(url = ban.user.avatar_url) embed.set_footer(text = f"User ID: {ban.user.id}") await ctx.send(embed = embed)
Python
async def addrole(self, ctx, member: discord.Member, *, rolename: str): """Add a role to someone else.""" role = discord.utils.find(lambda m: rolename.lower() in m.name.lower(), ctx.message.guild.roles) if not role: return await ctx.send("That role does not exist.") try: await member.add_roles(role) await ctx.send(f"Added: `{role.name}`") except: await ctx.send("I don't have the perms to add that role.")
async def addrole(self, ctx, member: discord.Member, *, rolename: str): """Add a role to someone else.""" role = discord.utils.find(lambda m: rolename.lower() in m.name.lower(), ctx.message.guild.roles) if not role: return await ctx.send("That role does not exist.") try: await member.add_roles(role) await ctx.send(f"Added: `{role.name}`") except: await ctx.send("I don't have the perms to add that role.")
Python
async def removerole(self, ctx, member: discord.Member, *, rolename: str): """Remove a role from someone else.""" role = discord.utils.find(lambda m: rolename.lower() in m.name.lower(), ctx.message.guild.roles) if not role: return await ctx.send("That role does not exist.") try: await member.remove_roles(role) await ctx.send(f"Removed: `{role.name}`") except: await ctx.send("I don't have the perms to add that role.")
async def removerole(self, ctx, member: discord.Member, *, rolename: str): """Remove a role from someone else.""" role = discord.utils.find(lambda m: rolename.lower() in m.name.lower(), ctx.message.guild.roles) if not role: return await ctx.send("That role does not exist.") try: await member.remove_roles(role) await ctx.send(f"Removed: `{role.name}`") except: await ctx.send("I don't have the perms to add that role.")
Python
async def hackban(self, ctx, userid, *, reason = None): """Ban someone not in the server""" try: userid = int(userid) except: await ctx.send("Invalid ID!") try: await ctx.guild.ban(discord.Object(userid), reason = reason) except: success = False else: success = True if success: async for entry in ctx.guild.audit_logs(limit = 1, user = ctx.guild.me, action = discord.AuditLogAction.ban): embed = await self.format_mod_embed(ctx, entry.target, success, "hackban") else: embed = await self.format_mod_embed(ctx, userid, success, "hackban") await ctx.send(embed = embed)
async def hackban(self, ctx, userid, *, reason = None): """Ban someone not in the server""" try: userid = int(userid) except: await ctx.send("Invalid ID!") try: await ctx.guild.ban(discord.Object(userid), reason = reason) except: success = False else: success = True if success: async for entry in ctx.guild.audit_logs(limit = 1, user = ctx.guild.me, action = discord.AuditLogAction.ban): embed = await self.format_mod_embed(ctx, entry.target, success, "hackban") else: embed = await self.format_mod_embed(ctx, userid, success, "hackban") await ctx.send(embed = embed)
Python
async def mute(self, ctx, member: discord.Member, duration, *, reason = None): """Denies someone from chatting in all text channels and \ talking in voice channels for a specified duration Example: luci mute @luciferchase 1h""" unit = duration[-1] if unit == "s": time = int(duration[:-1]) longunit = "seconds" elif unit == "m": time = int(duration[:-1]) * 60 longunit = "minutes" elif unit == "h": time = int(duration[:-1]) * 60 * 60 longunit = "hours" else: await ctx.send("Invalid Unit! Use `s`, `m`, or `h`.") return progress = await ctx.send("Muting user!") try: for channel in ctx.guild.text_channels: await channel.set_permissions( member, overwrite = discord.PermissionOverwrite(send_messages = False), reason = reason ) for channel in ctx.guild.voice_channels: await channel.set_permissions( member, overwrite = discord.PermissionOverwrite(speak = False), reason = reason ) except: success = False else: success = True await progress.delete() embed = await self.format_mod_embed(ctx, member, success, "mute", f"{str(duration[:-1])} {longunit}") await ctx.send(embed = embed) await asyncio.sleep(time) try: for channel in ctx.guild.channels: await channel.set_permissions(member, overwrite = None, reason = reason) except: pass
async def mute(self, ctx, member: discord.Member, duration, *, reason = None): """Denies someone from chatting in all text channels and \ talking in voice channels for a specified duration Example: luci mute @luciferchase 1h""" unit = duration[-1] if unit == "s": time = int(duration[:-1]) longunit = "seconds" elif unit == "m": time = int(duration[:-1]) * 60 longunit = "minutes" elif unit == "h": time = int(duration[:-1]) * 60 * 60 longunit = "hours" else: await ctx.send("Invalid Unit! Use `s`, `m`, or `h`.") return progress = await ctx.send("Muting user!") try: for channel in ctx.guild.text_channels: await channel.set_permissions( member, overwrite = discord.PermissionOverwrite(send_messages = False), reason = reason ) for channel in ctx.guild.voice_channels: await channel.set_permissions( member, overwrite = discord.PermissionOverwrite(speak = False), reason = reason ) except: success = False else: success = True await progress.delete() embed = await self.format_mod_embed(ctx, member, success, "mute", f"{str(duration[:-1])} {longunit}") await ctx.send(embed = embed) await asyncio.sleep(time) try: for channel in ctx.guild.channels: await channel.set_permissions(member, overwrite = None, reason = reason) except: pass
Python
async def unmute(self, ctx, member: discord.Member, *, reason = None): """Removes channel overrides for specified member""" progress = await ctx.send("Unmuting user!") try: for channel in ctx.message.guild.channels: await channel.set_permissions(member, overwrite = None, reason = reason) except: success = False else: success = True await progress.delete() embed = await self.format_mod_embed(ctx, member, success, "unmute") await ctx.send(embed = embed)
async def unmute(self, ctx, member: discord.Member, *, reason = None): """Removes channel overrides for specified member""" progress = await ctx.send("Unmuting user!") try: for channel in ctx.message.guild.channels: await channel.set_permissions(member, overwrite = None, reason = reason) except: success = False else: success = True await progress.delete() embed = await self.format_mod_embed(ctx, member, success, "unmute") await ctx.send(embed = embed)
Python
async def chan(self, ctx, channel: discord.TextChannel = None, *, reason = None): """Lockdown a channel. Members will not be able to send a message.""" if channel is None: channel = ctx.channel try: await channel.set_permissions( ctx.guild.default_role, overwrite = discord.PermissionOverwrite(send_messages = False), reason = reason ) except: success = False else: success = True embed = await self.format_mod_embed(ctx, ctx.author, success, "channel-locked", 0, channel) await ctx.send(embed = embed)
async def chan(self, ctx, channel: discord.TextChannel = None, *, reason = None): """Lockdown a channel. Members will not be able to send a message.""" if channel is None: channel = ctx.channel try: await channel.set_permissions( ctx.guild.default_role, overwrite = discord.PermissionOverwrite(send_messages = False), reason = reason ) except: success = False else: success = True embed = await self.format_mod_embed(ctx, ctx.author, success, "channel-locked", 0, channel) await ctx.send(embed = embed)
Python
async def _server(self, ctx, server: discord.Guild = None, *, reason = None): """Lockdown the server. Sed lyf.""" if server is None: server = ctx.guild progress = await ctx.send(f"Locking down {server.name}") try: for channel in server.channels: await channel.set_permissions( ctx.guild.default_role, overwrite = discord.PermissionOverwrite(send_messages = False), reason = reason ) except: success = False else: success = True await progress.delete() embed = await self.format_mod_embed(ctx, ctx.author, success, "server-locked", 0, server) await ctx.send(embed = embed)
async def _server(self, ctx, server: discord.Guild = None, *, reason = None): """Lockdown the server. Sed lyf.""" if server is None: server = ctx.guild progress = await ctx.send(f"Locking down {server.name}") try: for channel in server.channels: await channel.set_permissions( ctx.guild.default_role, overwrite = discord.PermissionOverwrite(send_messages = False), reason = reason ) except: success = False else: success = True await progress.delete() embed = await self.format_mod_embed(ctx, ctx.author, success, "server-locked", 0, server) await ctx.send(embed = embed)
Python
async def channel(self, ctx, channel: discord.TextChannel = None, *, reason = None): """Unlock a channel. Members will be able to send message again.""" if channel is None: channel = ctx.channel try: await channel.set_permissions( ctx.guild.default_role, overwrite = discord.PermissionOverwrite(send_messages = True), reason = reason ) except: success = False else: success = True embed = await self.format_mod_embed(ctx, ctx.author, success, "channel-unlocked", 0, channel) await ctx.send(embed = embed)
async def channel(self, ctx, channel: discord.TextChannel = None, *, reason = None): """Unlock a channel. Members will be able to send message again.""" if channel is None: channel = ctx.channel try: await channel.set_permissions( ctx.guild.default_role, overwrite = discord.PermissionOverwrite(send_messages = True), reason = reason ) except: success = False else: success = True embed = await self.format_mod_embed(ctx, ctx.author, success, "channel-unlocked", 0, channel) await ctx.send(embed = embed)
Python
async def server(self, ctx, server: discord.Guild = None, *, reason = None): """Unlock the server. Not sed anymore!""" if server is None: server = ctx.guild progress = await ctx.send(f"Unlocking {server.name}") try: for channel in server.channels: await channel.set_permissions( ctx.guild.default_role, overwrite = discord.PermissionOverwrite(send_messages = True), reason = reason ) except: success = False else: success = True await progress.delete() embed = await self.format_mod_embed(ctx, ctx.author, success, "server-unlocked", 0, server) await ctx.send(embed = embed)
async def server(self, ctx, server: discord.Guild = None, *, reason = None): """Unlock the server. Not sed anymore!""" if server is None: server = ctx.guild progress = await ctx.send(f"Unlocking {server.name}") try: for channel in server.channels: await channel.set_permissions( ctx.guild.default_role, overwrite = discord.PermissionOverwrite(send_messages = True), reason = reason ) except: success = False else: success = True await progress.delete() embed = await self.format_mod_embed(ctx, ctx.author, success, "server-unlocked", 0, server) await ctx.send(embed = embed)
Python
async def contains(self, ctx, *, substr: str): """Removes all messages containing a substring. The substring must be at least 3 characters long. """ if len(substr) < 3: await ctx.send("The substring length must be at least 3 characters.") else: await self.do_removal(ctx, 100, lambda e: substr in e.content)
async def contains(self, ctx, *, substr: str): """Removes all messages containing a substring. The substring must be at least 3 characters long. """ if len(substr) < 3: await ctx.send("The substring length must be at least 3 characters.") else: await self.do_removal(ctx, 100, lambda e: substr in e.content)
Python
async def _bots(self, ctx, search=100, prefix=None): """Removes a bot user's messages and messages with their optional prefix.""" getprefix = prefix if prefix else self.config["prefix"] def predicate(m): return (m.webhook_id is None and m.author.bot) or m.content.startswith(tuple(getprefix)) await self.do_removal(ctx, search, predicate)
async def _bots(self, ctx, search=100, prefix=None): """Removes a bot user's messages and messages with their optional prefix.""" getprefix = prefix if prefix else self.config["prefix"] def predicate(m): return (m.webhook_id is None and m.author.bot) or m.content.startswith(tuple(getprefix)) await self.do_removal(ctx, search, predicate)
Python
async def _emojis(self, ctx, search=100): """Removes all messages containing custom emoji.""" custom_emoji = re.compile(r"<a?:(.*?):(\d{17,21})>|[\u263a-\U0001f645]") def predicate(m): return custom_emoji.search(m.content) await self.do_removal(ctx, search, predicate)
async def _emojis(self, ctx, search=100): """Removes all messages containing custom emoji.""" custom_emoji = re.compile(r"<a?:(.*?):(\d{17,21})>|[\u263a-\U0001f645]") def predicate(m): return custom_emoji.search(m.content) await self.do_removal(ctx, search, predicate)
Python
async def _reactions(self, ctx, search=100): """Removes all reactions from messages that have them.""" if search > 2000: return await ctx.send(f"Too many messages to search for ({search}/2000)") total_reactions = 0 async for message in ctx.history(limit=search, before=ctx.message): if len(message.reactions): total_reactions += sum(r.count for r in message.reactions) await message.clear_reactions() await ctx.send(f"Successfully removed {total_reactions} reactions.")
async def _reactions(self, ctx, search=100): """Removes all reactions from messages that have them.""" if search > 2000: return await ctx.send(f"Too many messages to search for ({search}/2000)") total_reactions = 0 async for message in ctx.history(limit=search, before=ctx.message): if len(message.reactions): total_reactions += sum(r.count for r in message.reactions) await message.clear_reactions() await ctx.send(f"Successfully removed {total_reactions} reactions.")
Python
async def alphanato(self, ctx, *args): """Get military phonetics of every letter in english alphabet. Usage: You can get all the phonetics by simply calling `luci nda` or `luci alphanato` You can also get phonetics for a particular letter or multiple letter (separated by space) by doing: `luci nda l` or `luci nda l m n o`""" phonetics = ["Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf",\ "Hotel", "India", "Juliett", "Kilo", "Lima", "Mike", "November", "Oscar", "Papa", \ "Quebec", "Romeo", "Sierra", "Tango", "Uniform", "Victor", \ "Whiskey", "X-Ray", "Yankee", "Zulu"] message_string = "" if (args == ()): for index in range(26): message_string += f"{chr(97 + index)}: {phonetics[index]}\n" else: for letter in args: mssg_string += f"{letter}: {''.join([i for i in phonetics if i[0].lower() == letter])}\n" await ctx.send(f"```ml\n{mssg_string}```")
async def alphanato(self, ctx, *args): """Get military phonetics of every letter in english alphabet. Usage: You can get all the phonetics by simply calling `luci nda` or `luci alphanato` You can also get phonetics for a particular letter or multiple letter (separated by space) by doing: `luci nda l` or `luci nda l m n o`""" phonetics = ["Alpha", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf",\ "Hotel", "India", "Juliett", "Kilo", "Lima", "Mike", "November", "Oscar", "Papa", \ "Quebec", "Romeo", "Sierra", "Tango", "Uniform", "Victor", \ "Whiskey", "X-Ray", "Yankee", "Zulu"] message_string = "" if (args == ()): for index in range(26): message_string += f"{chr(97 + index)}: {phonetics[index]}\n" else: for letter in args: mssg_string += f"{letter}: {''.join([i for i in phonetics if i[0].lower() == letter])}\n" await ctx.send(f"```ml\n{mssg_string}```")
Python
async def avatar(self, ctx, *, user: discord.Member = None): """Returns user avatar URL. User argument can be user mention, nickname, username, user ID. Default to yourself when no argument is supplied. """ author = ctx.author if not user: user = author if user.is_avatar_animated(): url = user.avatar_url_as(format = "gif") if not user.is_avatar_animated(): url = user.avatar_url_as(static_format = "png") await ctx.send("{}'s Avatar URL : {}".format(user.name, url))
async def avatar(self, ctx, *, user: discord.Member = None): """Returns user avatar URL. User argument can be user mention, nickname, username, user ID. Default to yourself when no argument is supplied. """ author = ctx.author if not user: user = author if user.is_avatar_animated(): url = user.avatar_url_as(format = "gif") if not user.is_avatar_animated(): url = user.avatar_url_as(static_format = "png") await ctx.send("{}'s Avatar URL : {}".format(user.name, url))
Python
async def catfact(self, ctx): """Get a random fact about cats.""" async with self.session.get("https://catfact.ninja/fact") as response: data = await response.json() fact = data["fact"] embed = discord.Embed(title = "Catfact ❤", description = fact, color = 0x00ffff) await ctx.send(embed = embed)
async def catfact(self, ctx): """Get a random fact about cats.""" async with self.session.get("https://catfact.ninja/fact") as response: data = await response.json() fact = data["fact"] embed = discord.Embed(title = "Catfact ❤", description = fact, color = 0x00ffff) await ctx.send(embed = embed)
Python
async def dogfact(self, ctx): """Get a random fact about dogs. [Bit slow to run for the first time though (API limitation)]""" async with self.session.get( "https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?number=1") as response: data = await response.json() fact = data[0]["fact"] embed = discord.Embed(title = "Dogfact ❤", description = fact, color = 0x00ffff) await ctx.send(embed = embed)
async def dogfact(self, ctx): """Get a random fact about dogs. [Bit slow to run for the first time though (API limitation)]""" async with self.session.get( "https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?number=1") as response: data = await response.json() fact = data[0]["fact"] embed = discord.Embed(title = "Dogfact ❤", description = fact, color = 0x00ffff) await ctx.send(embed = embed)
Python
async def insult(self, ctx, member: discord.Member = None): """Insult someone. They are really evil though, take care.""" if (member is None): member = ctx.author async with self.session.get("https://evilinsult.com/generate_insult.php") as response: text = await response.text() embed = discord.Embed( title = f"{ctx.author.name} insulted {member.name}", description = text, color = 0xf34949 ) await ctx.send(embed = embed)
async def insult(self, ctx, member: discord.Member = None): """Insult someone. They are really evil though, take care.""" if (member is None): member = ctx.author async with self.session.get("https://evilinsult.com/generate_insult.php") as response: text = await response.text() embed = discord.Embed( title = f"{ctx.author.name} insulted {member.name}", description = text, color = 0xf34949 ) await ctx.send(embed = embed)
Python
async def isitdown(self, ctx: commands.Context, url_to_check): """ Check if the provided url is down Alias: iid """ try: resp, url = await self._check_if_down(url_to_check) except AssertionError: await ctx.send("Invalid URL provided. Make sure not to include `https://`") return # log.debug(resp) if resp["isitdown"]: await ctx.send(f"{url} is DOWN!") else: await ctx.send(f"{url} is UP!")
async def isitdown(self, ctx: commands.Context, url_to_check): """ Check if the provided url is down Alias: iid """ try: resp, url = await self._check_if_down(url_to_check) except AssertionError: await ctx.send("Invalid URL provided. Make sure not to include `https://`") return # log.debug(resp) if resp["isitdown"]: await ctx.send(f"{url} is DOWN!") else: await ctx.send(f"{url} is UP!")
Python
async def nitro(self, ctx, emoji_name): """Send an animated emoji even if you don't have nitro. \ Send just its name and the bot will send the emote. Usage: `luci n nacho`""" # # Delete original message # await ctx.message.delete() # First get all the emojies the bot has access and then Send emoji emoji_found = False for emoji in self.bot.emojis: if (emoji.name in emoji_name): await ctx.send(emoji.url) emoji_found = True if (not emoji_found): await ctx.send("Emoji not found <a:awkward1:839499334555140157>")
async def nitro(self, ctx, emoji_name): """Send an animated emoji even if you don't have nitro. \ Send just its name and the bot will send the emote. Usage: `luci n nacho`""" # # Delete original message # await ctx.message.delete() # First get all the emojies the bot has access and then Send emoji emoji_found = False for emoji in self.bot.emojis: if (emoji.name in emoji_name): await ctx.send(emoji.url) emoji_found = True if (not emoji_found): await ctx.send("Emoji not found <a:awkward1:839499334555140157>")
Python
async def poll(self, ctx, *message): """Do a poll Syntax: luci poll <question> |option 1|option 2|option 3|... For eg: luci poll Is luci geh? |Yes|No|You are geh| You can omit options to make it automatically a two option poll """ # Delete original message await ctx.message.delete() message = " ".join(message) time = datetime.now().strftime("%m/%d/%Y %H:%M:%S") # CHeck if there is an actual question given or not if (len(message) == 0): await ctx.send("Bruh! Send a question atlease 🤦‍♂️") # await ctx.invoke(self.bot.get_command("help"), "dm") return # Get index of question and options separator "|" index = message.find("|") # Check if there are any options or not if (index != -1): # Get question and options from the message question = message[:message.find("|")] options = [option for option in message[message.find("|") + 1:].split("|") if option != ""] # Check if there are more than 26 options if (len(options) > 20): await ctx.send("Bruh! Please give maximum 20 options 🤦‍♂️.", " You can only react 20 times to a message.") return reactions = ["🇦", "🇧", "🇨", "🇩", "🇪", "🇫", "🇬", "🇭", "🇮", "J", "🇰", "🇱", "🇲", "🇳", "🇴", "🇵", \ "🇶", "🇷", "🇸", "🇹", "🇺", "🇻", "🇼", "🇽", "🇾", "🇿"] options_string = "" for index in range(len(options)): options_string += f"{reactions[index]} {options[index]}\n" embed = discord.Embed( title = question, description = options_string, color = 0x00FFFF ) embed.set_footer(text = time) embed.set_author(name = ctx.author.name, icon_url = ctx.author.avatar_url) poll_embed = await ctx.send(embed = embed) for index in range(len(options)): await poll_embed.add_reaction(reactions[index]) # Else by default make a dual option poll else: question = "".join(message) embed = discord.Embed( title = question, color = 0x00FFFF ) embed.set_footer(text = time) embed.set_author(name = ctx.author.name, icon_url = ctx.author.avatar_url) poll_embed = await ctx.send(embed = embed) await poll_embed.add_reaction("👍") await poll_embed.add_reaction("👎")
async def poll(self, ctx, *message): """Do a poll Syntax: luci poll <question> |option 1|option 2|option 3|... For eg: luci poll Is luci geh? |Yes|No|You are geh| You can omit options to make it automatically a two option poll """ # Delete original message await ctx.message.delete() message = " ".join(message) time = datetime.now().strftime("%m/%d/%Y %H:%M:%S") # CHeck if there is an actual question given or not if (len(message) == 0): await ctx.send("Bruh! Send a question atlease 🤦‍♂️") # await ctx.invoke(self.bot.get_command("help"), "dm") return # Get index of question and options separator "|" index = message.find("|") # Check if there are any options or not if (index != -1): # Get question and options from the message question = message[:message.find("|")] options = [option for option in message[message.find("|") + 1:].split("|") if option != ""] # Check if there are more than 26 options if (len(options) > 20): await ctx.send("Bruh! Please give maximum 20 options 🤦‍♂️.", " You can only react 20 times to a message.") return reactions = ["🇦", "🇧", "🇨", "🇩", "🇪", "🇫", "🇬", "🇭", "🇮", "J", "🇰", "🇱", "🇲", "🇳", "🇴", "🇵", \ "🇶", "🇷", "🇸", "🇹", "🇺", "🇻", "🇼", "🇽", "🇾", "🇿"] options_string = "" for index in range(len(options)): options_string += f"{reactions[index]} {options[index]}\n" embed = discord.Embed( title = question, description = options_string, color = 0x00FFFF ) embed.set_footer(text = time) embed.set_author(name = ctx.author.name, icon_url = ctx.author.avatar_url) poll_embed = await ctx.send(embed = embed) for index in range(len(options)): await poll_embed.add_reaction(reactions[index]) # Else by default make a dual option poll else: question = "".join(message) embed = discord.Embed( title = question, color = 0x00FFFF ) embed.set_footer(text = time) embed.set_author(name = ctx.author.name, icon_url = ctx.author.avatar_url) poll_embed = await ctx.send(embed = embed) await poll_embed.add_reaction("👍") await poll_embed.add_reaction("👎")
Python
async def urban(self, ctx, *, search: commands.clean_content): """ Find the 'best' definition to your words """ async with ctx.channel.typing(): try: async with self.session.get(f"https://api.urbandictionary.com/v0/define?term={search}") \ as response: data = await response.json() except Exception: return await ctx.send("Urban API returned invalid data... might be down atm.") if not len(data["list"]): return await ctx.send("Couldn't find your search in the dictionary...") result = sorted(data["list"], reverse = True, key=lambda i: int(i["thumbs_up"]))[0] definition = result["definition"] if len(definition) >= 1000: definition = definition[:1000] definition = definition.rsplit(" ", 1)[0] definition += "..." await ctx.send(f"📚 Definitions for **{result['word']}**```fix\n{definition}```")
async def urban(self, ctx, *, search: commands.clean_content): """ Find the 'best' definition to your words """ async with ctx.channel.typing(): try: async with self.session.get(f"https://api.urbandictionary.com/v0/define?term={search}") \ as response: data = await response.json() except Exception: return await ctx.send("Urban API returned invalid data... might be down atm.") if not len(data["list"]): return await ctx.send("Couldn't find your search in the dictionary...") result = sorted(data["list"], reverse = True, key=lambda i: int(i["thumbs_up"]))[0] definition = result["definition"] if len(definition) >= 1000: definition = definition[:1000] definition = definition.rsplit(" ", 1)[0] definition += "..." await ctx.send(f"📚 Definitions for **{result['word']}**```fix\n{definition}```")
Python
async def ipl(self, ctx): """Get info about last match and upcoming matches""" # Fetch details first last_match_details, last_match_details_2, \ next_match_details, next_match_details_2 = self.fetch_matches() embed = discord.Embed( color = 0x25dbf4, # Blue title = "Matches" ) embed.add_field( name = "Next Match", value = f'{next_match_details["team-1"]} \nvs \ \n{next_match_details["team-2"]}', inline = False ) # If there is a second match on that day if (next_match_details_2 != False): embed.add_field( name = "Match 2", value = f'{next_match_details_2["team-1"]} \nvs \ \n{next_match_details_2["team-2"]}', inline = False ) embed.add_field( name = "Last Match", value = f'{last_match_details["team-1"]} \nvs \n{last_match_details["team-2"]}', inline = True ) embed.add_field( name = "Winner", value = f'{last_match_details["winner_team"]}', inline = True ) image_url = self.image_url[last_match_details["winner_team"]] # If there was another match yesterday if (last_match_details_2 != False): embed.add_field( name = "Match 2", value = f'{last_match_details_2["team-1"]} \nvs \ \n{last_match_details_2["team-2"]}', inline = False ) embed.add_field( name = "Winner", value = f'{last_match_details_2["winner_team"]}', inline = True ) # Update the image to show image_url = self.image_url[last_match_details_2["winner_team"]] embed.set_image(url = image_url) embed.set_thumbnail(url = self.ipl_logo) await ctx.send(embed = embed)
async def ipl(self, ctx): """Get info about last match and upcoming matches""" # Fetch details first last_match_details, last_match_details_2, \ next_match_details, next_match_details_2 = self.fetch_matches() embed = discord.Embed( color = 0x25dbf4, # Blue title = "Matches" ) embed.add_field( name = "Next Match", value = f'{next_match_details["team-1"]} \nvs \ \n{next_match_details["team-2"]}', inline = False ) # If there is a second match on that day if (next_match_details_2 != False): embed.add_field( name = "Match 2", value = f'{next_match_details_2["team-1"]} \nvs \ \n{next_match_details_2["team-2"]}', inline = False ) embed.add_field( name = "Last Match", value = f'{last_match_details["team-1"]} \nvs \n{last_match_details["team-2"]}', inline = True ) embed.add_field( name = "Winner", value = f'{last_match_details["winner_team"]}', inline = True ) image_url = self.image_url[last_match_details["winner_team"]] # If there was another match yesterday if (last_match_details_2 != False): embed.add_field( name = "Match 2", value = f'{last_match_details_2["team-1"]} \nvs \ \n{last_match_details_2["team-2"]}', inline = False ) embed.add_field( name = "Winner", value = f'{last_match_details_2["winner_team"]}', inline = True ) # Update the image to show image_url = self.image_url[last_match_details_2["winner_team"]] embed.set_image(url = image_url) embed.set_thumbnail(url = self.ipl_logo) await ctx.send(embed = embed)
Python
async def standings(self, ctx): """Get current standings of Sattebaaz Championship""" embed = await self.fetch_standings() await ctx.send(embed = embed)
async def standings(self, ctx): """Get current standings of Sattebaaz Championship""" embed = await self.fetch_standings() await ctx.send(embed = embed)
Python
def info(message: str, member: Union[Member, User], title: str = "Info") -> Embed: """ Constructs success embed with custom title and description. Color depends on passed member top role color. :param message: embed description :param member: member object to get the color of it's top role from :param title: title of embed, defaults to "Info" :return: Embed object """ return Embed(title=title, description=message, color=get_top_role_color(member, fallback_color=Color.green()))
def info(message: str, member: Union[Member, User], title: str = "Info") -> Embed: """ Constructs success embed with custom title and description. Color depends on passed member top role color. :param message: embed description :param member: member object to get the color of it's top role from :param title: title of embed, defaults to "Info" :return: Embed object """ return Embed(title=title, description=message, color=get_top_role_color(member, fallback_color=Color.green()))
Python
def success(message: str, member: Union[Member, User] = None) -> Embed: """ Constructs success embed with fixed title 'Success' and color depending on passed member top role color. If member is not passed or if it's a User (DMs) green color will be used. :param message: embed description :param member: member object to get the color of it's top role from, usually our bot member object from the specific guild. :return: Embed object """ return simple_embed(f"😁︱{message}", "", get_top_role_color(member, fallback_color=Color.green()))
def success(message: str, member: Union[Member, User] = None) -> Embed: """ Constructs success embed with fixed title 'Success' and color depending on passed member top role color. If member is not passed or if it's a User (DMs) green color will be used. :param message: embed description :param member: member object to get the color of it's top role from, usually our bot member object from the specific guild. :return: Embed object """ return simple_embed(f"😁︱{message}", "", get_top_role_color(member, fallback_color=Color.green()))
Python
def failure(message: str) -> Embed: """ Constructs failure embed with fixed title 'Failure' and color red :param message: embed description :return: Embed object """ return simple_embed(f"🥺︱{message}", "", Color.red())
def failure(message: str) -> Embed: """ Constructs failure embed with fixed title 'Failure' and color red :param message: embed description :return: Embed object """ return simple_embed(f"🥺︱{message}", "", Color.red())
Python
async def convert(self, ctx, tz_1, tz_2, *timestamp): """Example: luci convert london kolkata 12:56""" timestamp = timestamp[0] if (":" not in timestamp): timestamp += ":00" if (len(timestamp.split(":")[0]) == 1): timestamp = "0" + timestamp # Convert timestamp to datetime object timestamp = datetime.strptime(timestamp, self.fmt) if (tz_1.lower() == "usa"): tz_1 = "america" if (tz_2.lower() == "usa"): tz_2 = "america" list_of_timezones = list(pytz.all_timezones) found_1, found_2 = (False, False) for i in range(len(list_of_timezones)): if (found_1 and found_2): break if (tz_1.title() in list_of_timezones[i]): tz_1 = list_of_timezones[i] found_1 = True elif (tz_2.title() in list_of_timezones[i]): tz_2 = list_of_timezones[i] found_2 = True else: if (not found_1): country_not_found = "first timezone" elif (not found_2): country_not_found = "second timezone" else: country_not_found = "both the timezone" await ctx.send(f"Uh oh! Your {country_not_found} not found 👀") await ctx.send("You can check list of timezones using `luci timezones [continent name]`") return # First we will get the time difference between the timezones # Current time in UTC now_utc = datetime.now(pytz.timezone("UTC")) time_in_tz1 = now_utc.astimezone(pytz.timezone(tz_1)) time_in_tz2 = now_utc.astimezone(pytz.timezone(tz_2)) # Stip all timezone info from datetime object time_in_tz1 = datetime.strptime(time_in_tz1.strftime(self.fmt), self.fmt) time_in_tz2 = datetime.strptime(time_in_tz2.strftime(self.fmt), self.fmt) if (time_in_tz2 > time_in_tz1): difference_in_time = time_in_tz2 - time_in_tz1 timestamp_2 = timestamp + difference_in_time else: difference_in_time = time_in_tz1 - time_in_tz2 timestamp_2 = timestamp - difference_in_time await ctx.send("```css\n{}: {}\n{}: {}```".format( tz_1, timestamp.strftime(self.fmt), tz_2, timestamp_2.strftime(self.fmt)))
async def convert(self, ctx, tz_1, tz_2, *timestamp): """Example: luci convert london kolkata 12:56""" timestamp = timestamp[0] if (":" not in timestamp): timestamp += ":00" if (len(timestamp.split(":")[0]) == 1): timestamp = "0" + timestamp # Convert timestamp to datetime object timestamp = datetime.strptime(timestamp, self.fmt) if (tz_1.lower() == "usa"): tz_1 = "america" if (tz_2.lower() == "usa"): tz_2 = "america" list_of_timezones = list(pytz.all_timezones) found_1, found_2 = (False, False) for i in range(len(list_of_timezones)): if (found_1 and found_2): break if (tz_1.title() in list_of_timezones[i]): tz_1 = list_of_timezones[i] found_1 = True elif (tz_2.title() in list_of_timezones[i]): tz_2 = list_of_timezones[i] found_2 = True else: if (not found_1): country_not_found = "first timezone" elif (not found_2): country_not_found = "second timezone" else: country_not_found = "both the timezone" await ctx.send(f"Uh oh! Your {country_not_found} not found 👀") await ctx.send("You can check list of timezones using `luci timezones [continent name]`") return # First we will get the time difference between the timezones # Current time in UTC now_utc = datetime.now(pytz.timezone("UTC")) time_in_tz1 = now_utc.astimezone(pytz.timezone(tz_1)) time_in_tz2 = now_utc.astimezone(pytz.timezone(tz_2)) # Stip all timezone info from datetime object time_in_tz1 = datetime.strptime(time_in_tz1.strftime(self.fmt), self.fmt) time_in_tz2 = datetime.strptime(time_in_tz2.strftime(self.fmt), self.fmt) if (time_in_tz2 > time_in_tz1): difference_in_time = time_in_tz2 - time_in_tz1 timestamp_2 = timestamp + difference_in_time else: difference_in_time = time_in_tz1 - time_in_tz2 timestamp_2 = timestamp - difference_in_time await ctx.send("```css\n{}: {}\n{}: {}```".format( tz_1, timestamp.strftime(self.fmt), tz_2, timestamp_2.strftime(self.fmt)))
Python
async def mods(self, ctx): """ Check which mods are online on current guild """ message = "" all_status = { "online": {"users": [], "emoji": "🟢"}, "idle": {"users": [], "emoji": "🟡"}, "dnd": {"users": [], "emoji": "🔴"}, "offline": {"users": [], "emoji": "⚫"} } for user in ctx.guild.members: user_perm = ctx.channel.permissions_for(user) if user_perm.kick_members or user_perm.ban_members: if not user.bot: all_status[str(user.status)]["users"].append(f"{user}") for i in all_status: if all_status[i]["users"]: message += f"{all_status[i]['emoji']} {', '.join(all_status[i]['users'])}\n" await ctx.send(f"Mods in **{ctx.guild.name}**\n{message}")
async def mods(self, ctx): """ Check which mods are online on current guild """ message = "" all_status = { "online": {"users": [], "emoji": "🟢"}, "idle": {"users": [], "emoji": "🟡"}, "dnd": {"users": [], "emoji": "🔴"}, "offline": {"users": [], "emoji": "⚫"} } for user in ctx.guild.members: user_perm = ctx.channel.permissions_for(user) if user_perm.kick_members or user_perm.ban_members: if not user.bot: all_status[str(user.status)]["users"].append(f"{user}") for i in all_status: if all_status[i]["users"]: message += f"{all_status[i]['emoji']} {', '.join(all_status[i]['users'])}\n" await ctx.send(f"Mods in **{ctx.guild.name}**\n{message}")
Python
async def photo(self, ctx, *query): """ Get a photo from Unsplash. For eg. `luci photo messi` Default to a random photo """ endpoint_list = { "search": "/search/photos", "random": "/photos/random" } params = { "client_id": self.unsplash_client_id, "query": f"{' '.join(query)}", "page": "1", } if (len(query) != 0): endpoint = endpoint_list["search"] else: endpoint = endpoint_list["random"] async with self.session.get(self.unsplash_api + endpoint, params = params) as response: data = await response.json() if (len(query) != 0): if (str(response.status)[:2] == 40): self.log.error(f"API Rate limit hit for this hour {datetime.now()}") self.log.error(f"Status Code: {response.status}") async with self.session.get(self.dog_api) as response: data = await response.json() data = data[0] embed = discord.Embed( title = "Sorry!", color = 0xea1010 # Red ) embed.add_field( name = "50/50 Requests of this Hour reached. Try again next Hour.", value = "Maybe give money to @luciferchase? Anyway here is a cute doggo ❤" ) embed.set_image(url = data["url"]) await ctx.send(embed = embed) return elif (data["results"] == []): self.log.error(f"No photo found for the query : {' '.join(query)}") async with self.session.get(self.dog_api) as response: data = await response.json() data = data[0] embed = discord.Embed( title = "No Photo Found", color = 0xea1010 # Red ) embed.add_field( name = f"No photo found for the query : `{' '.join(query)}`", value = "Maybe change your query? Anyway here is a cute doggo ❤" ) embed.set_image(url = data["url"]) await ctx.send(embed = embed) return likes = {} for photo in data["results"]: likes[photo["id"]] = photo["likes"] photo_info = [photo for photo in data["results"] if photo["id"] == max(likes)][0] # In case there is no particular photo requested, get a random photo else: photo_info = data if (photo_info["description"] == None): if (photo_info["alt_description"] != None): photo_info["description"] = photo_info["alt_description"] else: photo_info["description"] = "Photo" embed = discord.Embed( title = f"{' '.join(query)}".title(), description = f'{photo_info["description"][:50]}...', url = photo_info["urls"]["regular"], color = 0xf5009b # Pinkish ) embed.set_author( name = photo_info["user"]["name"], url = f'https://unsplash.com/@{photo_info["user"]["username"]}', icon_url = photo_info["user"]["profile_image"]["large"] ) embed.set_thumbnail(url = photo_info["user"]["profile_image"]["large"]) embed.set_image(url = photo_info["urls"]["full"]) embed.set_footer(text = f"❤️ {photo_info['likes']}") await ctx.send(embed = embed)
async def photo(self, ctx, *query): """ Get a photo from Unsplash. For eg. `luci photo messi` Default to a random photo """ endpoint_list = { "search": "/search/photos", "random": "/photos/random" } params = { "client_id": self.unsplash_client_id, "query": f"{' '.join(query)}", "page": "1", } if (len(query) != 0): endpoint = endpoint_list["search"] else: endpoint = endpoint_list["random"] async with self.session.get(self.unsplash_api + endpoint, params = params) as response: data = await response.json() if (len(query) != 0): if (str(response.status)[:2] == 40): self.log.error(f"API Rate limit hit for this hour {datetime.now()}") self.log.error(f"Status Code: {response.status}") async with self.session.get(self.dog_api) as response: data = await response.json() data = data[0] embed = discord.Embed( title = "Sorry!", color = 0xea1010 # Red ) embed.add_field( name = "50/50 Requests of this Hour reached. Try again next Hour.", value = "Maybe give money to @luciferchase? Anyway here is a cute doggo ❤" ) embed.set_image(url = data["url"]) await ctx.send(embed = embed) return elif (data["results"] == []): self.log.error(f"No photo found for the query : {' '.join(query)}") async with self.session.get(self.dog_api) as response: data = await response.json() data = data[0] embed = discord.Embed( title = "No Photo Found", color = 0xea1010 # Red ) embed.add_field( name = f"No photo found for the query : `{' '.join(query)}`", value = "Maybe change your query? Anyway here is a cute doggo ❤" ) embed.set_image(url = data["url"]) await ctx.send(embed = embed) return likes = {} for photo in data["results"]: likes[photo["id"]] = photo["likes"] photo_info = [photo for photo in data["results"] if photo["id"] == max(likes)][0] # In case there is no particular photo requested, get a random photo else: photo_info = data if (photo_info["description"] == None): if (photo_info["alt_description"] != None): photo_info["description"] = photo_info["alt_description"] else: photo_info["description"] = "Photo" embed = discord.Embed( title = f"{' '.join(query)}".title(), description = f'{photo_info["description"][:50]}...', url = photo_info["urls"]["regular"], color = 0xf5009b # Pinkish ) embed.set_author( name = photo_info["user"]["name"], url = f'https://unsplash.com/@{photo_info["user"]["username"]}', icon_url = photo_info["user"]["profile_image"]["large"] ) embed.set_thumbnail(url = photo_info["user"]["profile_image"]["large"]) embed.set_image(url = photo_info["urls"]["full"]) embed.set_footer(text = f"❤️ {photo_info['likes']}") await ctx.send(embed = embed)
Python
async def wallpaper(self, ctx): """ Get Bing's daily wallpaper of the day """ async with self.session.get(self.bing_api) as response: data = await response.json() await ctx.send(data["images"][0]["title"]) wallpaper = await ctx.send(f'http://bing.com{data["images"][0]["url"]}') await wallpaper.add_reaction("❤️") await wallpaper.add_reaction("👍") await wallpaper.add_reaction("👎")
async def wallpaper(self, ctx): """ Get Bing's daily wallpaper of the day """ async with self.session.get(self.bing_api) as response: data = await response.json() await ctx.send(data["images"][0]["title"]) wallpaper = await ctx.send(f'http://bing.com{data["images"][0]["url"]}') await wallpaper.add_reaction("❤️") await wallpaper.add_reaction("👍") await wallpaper.add_reaction("👎")
Python
async def redpanda(self, ctx): """ Get a random red panda pic """ async with self.session.get(self.red_panda_api) as response: data = await response.json() embed = discord.Embed( title = "Here is a cute red panda ❤", color = 0xf34949 # Red ) embed.set_image(url = data["link"]) await ctx.send(embed = embed)
async def redpanda(self, ctx): """ Get a random red panda pic """ async with self.session.get(self.red_panda_api) as response: data = await response.json() embed = discord.Embed( title = "Here is a cute red panda ❤", color = 0xf34949 # Red ) embed.set_image(url = data["link"]) await ctx.send(embed = embed)
Python
async def math(self, ctx, *expression): """ Solve a math expression. Supports very complex problems too. For eg. `luci math sin(pi/4)` """ log = logging.getLogger("math") if (expression == ""): embed = discord.Embed( color = 0xf34949, # Red title = "Input A Expression" ) await ctx.send(embed = embed) return start = time.monotonic() api = "http://api.mathjs.org/v4/" params = { "expr": "".join(expression) } async with self.session.get(api, params = params) as response: end = time.monotonic() if (response.status != 200): log.info(expression) log.error(await response.text()) return embed = discord.Embed( color = 0xf34949, # Red title = await response.text() ) embed.add_field( name = "Your Input:", value = f'`{"".join(expression)}`', inline = True ) embed.add_field( name = "Answer:", value = f"`{await response.text()}`", inline = True ) embed.set_footer(text = f"Calculated in {round((end - start) * 1000, 3)} ms") await ctx.send(embed = embed)
async def math(self, ctx, *expression): """ Solve a math expression. Supports very complex problems too. For eg. `luci math sin(pi/4)` """ log = logging.getLogger("math") if (expression == ""): embed = discord.Embed( color = 0xf34949, # Red title = "Input A Expression" ) await ctx.send(embed = embed) return start = time.monotonic() api = "http://api.mathjs.org/v4/" params = { "expr": "".join(expression) } async with self.session.get(api, params = params) as response: end = time.monotonic() if (response.status != 200): log.info(expression) log.error(await response.text()) return embed = discord.Embed( color = 0xf34949, # Red title = await response.text() ) embed.add_field( name = "Your Input:", value = f'`{"".join(expression)}`', inline = True ) embed.add_field( name = "Answer:", value = f"`{await response.text()}`", inline = True ) embed.set_footer(text = f"Calculated in {round((end - start) * 1000, 3)} ms") await ctx.send(embed = embed)
Python
async def factorise(self, ctx, *expression): """Factorise a polynomial equation. Please put tan(x) instead of tanx and so on for all trigonametric functions. Usage: `luci factorise x^2 + 2x`""" expression = "".join(expression) loading = await ctx.send("Calculating...") await ctx.trigger_typing() embed = await self.get_result(ctx = ctx, operation = "factor", expression = expression) # First delete the calculating message await loading.delete() await ctx.send(embed = embed)
async def factorise(self, ctx, *expression): """Factorise a polynomial equation. Please put tan(x) instead of tanx and so on for all trigonametric functions. Usage: `luci factorise x^2 + 2x`""" expression = "".join(expression) loading = await ctx.send("Calculating...") await ctx.trigger_typing() embed = await self.get_result(ctx = ctx, operation = "factor", expression = expression) # First delete the calculating message await loading.delete() await ctx.send(embed = embed)
Python
async def derive(self, ctx, *expression): """Differentiate a polynomial. Please put tan(x) instead of tanx and so on for all trigonametric functions. Usage: `luci derive x^2 + 2x`""" expression = "".join(expression) loading = await ctx.send("Calculating...") await ctx.trigger_typing() embed = await self.get_result(ctx = ctx, operation = "derive", expression = expression) # First delete the calculating message await loading.delete() await ctx.send(embed = embed)
async def derive(self, ctx, *expression): """Differentiate a polynomial. Please put tan(x) instead of tanx and so on for all trigonametric functions. Usage: `luci derive x^2 + 2x`""" expression = "".join(expression) loading = await ctx.send("Calculating...") await ctx.trigger_typing() embed = await self.get_result(ctx = ctx, operation = "derive", expression = expression) # First delete the calculating message await loading.delete() await ctx.send(embed = embed)
Python
async def integrate(self, ctx, *expression): """Integrate a polynomial. Please put tan(x) instead of tanx and so on for all trigonametric functions. Usage: `luci integrate x^2 + 2x`""" expression = "".join(expression) loading = await ctx.send("Calculating...") await ctx.trigger_typing() embed = await self.get_result(ctx = ctx, operation = "integrate", expression = expression) # First delete the calculating message await loading.delete() await ctx.send(embed = embed)
async def integrate(self, ctx, *expression): """Integrate a polynomial. Please put tan(x) instead of tanx and so on for all trigonametric functions. Usage: `luci integrate x^2 + 2x`""" expression = "".join(expression) loading = await ctx.send("Calculating...") await ctx.trigger_typing() embed = await self.get_result(ctx = ctx, operation = "integrate", expression = expression) # First delete the calculating message await loading.delete() await ctx.send(embed = embed)
Python
async def solve(self, ctx, *expression): """Find roots of a polynomial. Please put tan(x) instead of tanx and so on for all trigonametric functions. Usage: `luci roots x^2 + 2x`""" expression = "".join(expression) loading = await ctx.send("Calculating...") await ctx.trigger_typing() embed = await self.get_result(ctx = ctx, operation = "zeroes", expression = expression) # First delete the calculating message await loading.delete() await ctx.send(embed = embed)
async def solve(self, ctx, *expression): """Find roots of a polynomial. Please put tan(x) instead of tanx and so on for all trigonametric functions. Usage: `luci roots x^2 + 2x`""" expression = "".join(expression) loading = await ctx.send("Calculating...") await ctx.trigger_typing() embed = await self.get_result(ctx = ctx, operation = "zeroes", expression = expression) # First delete the calculating message await loading.delete() await ctx.send(embed = embed)
Python
async def truth(self, ctx, *, user: discord.Member): """Ask a truth question to users!""" question = random.choice(self.truths) # Set author author = ctx.message.author # Get and pick random user member_list = len(ctx.guild.members) random_number = random.randint(0, member_list - 1) random_member = ctx.guild.members[random_number].mention # Build Embed embed = discord.Embed( title = f"{author.nick} asked {user.nick}", description = question.format(name = random_member), color = 0xf34949 # red ) await ctx.send(embed = embed)
async def truth(self, ctx, *, user: discord.Member): """Ask a truth question to users!""" question = random.choice(self.truths) # Set author author = ctx.message.author # Get and pick random user member_list = len(ctx.guild.members) random_number = random.randint(0, member_list - 1) random_member = ctx.guild.members[random_number].mention # Build Embed embed = discord.Embed( title = f"{author.nick} asked {user.nick}", description = question.format(name = random_member), color = 0xf34949 # red ) await ctx.send(embed = embed)
Python
async def oddones(self, ctx, date: str = None): """Odd 1s Out Only random comics are available. """ all_comics = [] main_url = "https://theodd1sout.com/pages/comics" async with ctx.typing(): async with self.session.get(main_url) as response: html = await response.text() soup = BeautifulSoup(html, "html.parser") a = soup.find_all("a", {"class": "shogun-image-link"}) for item in a: try: all_comics.append(item["href"]) except KeyError: pass random_comic_page = random.choice(all_comics) async with self.session.get(random_comic_page) as response: html = await response.text() soup = BeautifulSoup(html, "html.parser") partial_comic_url = soup.find(id = "article-featured-image")["src"] comic_name = soup.find(id = "article-featured-image")["alt"].replace(" ", "-") if partial_comic_url: async with self.session.get(f"https:{partial_comic_url}") as response: img = io.BytesIO(await response.read()) await ctx.send(file = discord.File(img, f"oddonesout-{comic_name}.png")) else: return await ctx.send("Can't retrieve a comic image for that site.")
async def oddones(self, ctx, date: str = None): """Odd 1s Out Only random comics are available. """ all_comics = [] main_url = "https://theodd1sout.com/pages/comics" async with ctx.typing(): async with self.session.get(main_url) as response: html = await response.text() soup = BeautifulSoup(html, "html.parser") a = soup.find_all("a", {"class": "shogun-image-link"}) for item in a: try: all_comics.append(item["href"]) except KeyError: pass random_comic_page = random.choice(all_comics) async with self.session.get(random_comic_page) as response: html = await response.text() soup = BeautifulSoup(html, "html.parser") partial_comic_url = soup.find(id = "article-featured-image")["src"] comic_name = soup.find(id = "article-featured-image")["alt"].replace(" ", "-") if partial_comic_url: async with self.session.get(f"https:{partial_comic_url}") as response: img = io.BytesIO(await response.read()) await ctx.send(file = discord.File(img, f"oddonesout-{comic_name}.png")) else: return await ctx.send("Can't retrieve a comic image for that site.")
Python
def equal_to( cls, value: str, ctx: Optional[commands.Context] = None, channel: Optional[Union[discord.TextChannel, discord.DMChannel]] = None, user: Optional[discord.abc.User] = None, ) -> "MessagePredicate": """Match if the response is equal to the specified value. Parameters ---------- value : str The value to compare the response with. ctx : Optional[Context] Same as ``ctx`` in :meth:`same_context`. channel : Optional[discord.TextChannel] Same as ``channel`` in :meth:`same_context`. user : Optional[discord.abc.User] Same as ``user`` in :meth:`same_context`. Returns ------- MessagePredicate The event predicate. """ same_context = cls.same_context(ctx, channel, user) return cls(lambda self, m: same_context(m) and m.content == value)
def equal_to( cls, value: str, ctx: Optional[commands.Context] = None, channel: Optional[Union[discord.TextChannel, discord.DMChannel]] = None, user: Optional[discord.abc.User] = None, ) -> "MessagePredicate": """Match if the response is equal to the specified value. Parameters ---------- value : str The value to compare the response with. ctx : Optional[Context] Same as ``ctx`` in :meth:`same_context`. channel : Optional[discord.TextChannel] Same as ``channel`` in :meth:`same_context`. user : Optional[discord.abc.User] Same as ``user`` in :meth:`same_context`. Returns ------- MessagePredicate The event predicate. """ same_context = cls.same_context(ctx, channel, user) return cls(lambda self, m: same_context(m) and m.content == value)
Python
def lower_equal_to( cls, value: str, ctx: Optional[commands.Context] = None, channel: Optional[Union[discord.TextChannel, discord.DMChannel]] = None, user: Optional[discord.abc.User] = None, ) -> "MessagePredicate": """Match if the response *as lowercase* is equal to the specified value. Parameters ---------- value : str The value to compare the response with. ctx : Optional[Context] Same as ``ctx`` in :meth:`same_context`. channel : Optional[discord.TextChannel] Same as ``channel`` in :meth:`same_context`. user : Optional[discord.abc.User] Same as ``user`` in :meth:`same_context`. Returns ------- MessagePredicate The event predicate. """ same_context = cls.same_context(ctx, channel, user) return cls(lambda self, m: same_context(m) and m.content.lower() == value)
def lower_equal_to( cls, value: str, ctx: Optional[commands.Context] = None, channel: Optional[Union[discord.TextChannel, discord.DMChannel]] = None, user: Optional[discord.abc.User] = None, ) -> "MessagePredicate": """Match if the response *as lowercase* is equal to the specified value. Parameters ---------- value : str The value to compare the response with. ctx : Optional[Context] Same as ``ctx`` in :meth:`same_context`. channel : Optional[discord.TextChannel] Same as ``channel`` in :meth:`same_context`. user : Optional[discord.abc.User] Same as ``user`` in :meth:`same_context`. Returns ------- MessagePredicate The event predicate. """ same_context = cls.same_context(ctx, channel, user) return cls(lambda self, m: same_context(m) and m.content.lower() == value)
Python
def less( cls, value: Union[int, float], ctx: Optional[commands.Context] = None, channel: Optional[Union[discord.TextChannel, discord.DMChannel]] = None, user: Optional[discord.abc.User] = None, ) -> "MessagePredicate": """Match if the response is less than the specified value. Parameters ---------- value : Union[int, float] The value to compare the response with. ctx : Optional[Context] Same as ``ctx`` in :meth:`same_context`. channel : Optional[discord.TextChannel] Same as ``channel`` in :meth:`same_context`. user : Optional[discord.abc.User] Same as ``user`` in :meth:`same_context`. Returns ------- MessagePredicate The event predicate. """ valid_int = cls.valid_int(ctx, channel, user) valid_float = cls.valid_float(ctx, channel, user) return cls(lambda self, m: (valid_int(m) or valid_float(m)) and float(m.content) < value)
def less( cls, value: Union[int, float], ctx: Optional[commands.Context] = None, channel: Optional[Union[discord.TextChannel, discord.DMChannel]] = None, user: Optional[discord.abc.User] = None, ) -> "MessagePredicate": """Match if the response is less than the specified value. Parameters ---------- value : Union[int, float] The value to compare the response with. ctx : Optional[Context] Same as ``ctx`` in :meth:`same_context`. channel : Optional[discord.TextChannel] Same as ``channel`` in :meth:`same_context`. user : Optional[discord.abc.User] Same as ``user`` in :meth:`same_context`. Returns ------- MessagePredicate The event predicate. """ valid_int = cls.valid_int(ctx, channel, user) valid_float = cls.valid_float(ctx, channel, user) return cls(lambda self, m: (valid_int(m) or valid_float(m)) and float(m.content) < value)
Python
def greater( cls, value: Union[int, float], ctx: Optional[commands.Context] = None, channel: Optional[Union[discord.TextChannel, discord.DMChannel]] = None, user: Optional[discord.abc.User] = None, ) -> "MessagePredicate": """Match if the response is greater than the specified value. Parameters ---------- value : Union[int, float] The value to compare the response with. ctx : Optional[Context] Same as ``ctx`` in :meth:`same_context`. channel : Optional[discord.TextChannel] Same as ``channel`` in :meth:`same_context`. user : Optional[discord.abc.User] Same as ``user`` in :meth:`same_context`. Returns ------- MessagePredicate The event predicate. """ valid_int = cls.valid_int(ctx, channel, user) valid_float = cls.valid_float(ctx, channel, user) return cls(lambda self, m: (valid_int(m) or valid_float(m)) and float(m.content) > value)
def greater( cls, value: Union[int, float], ctx: Optional[commands.Context] = None, channel: Optional[Union[discord.TextChannel, discord.DMChannel]] = None, user: Optional[discord.abc.User] = None, ) -> "MessagePredicate": """Match if the response is greater than the specified value. Parameters ---------- value : Union[int, float] The value to compare the response with. ctx : Optional[Context] Same as ``ctx`` in :meth:`same_context`. channel : Optional[discord.TextChannel] Same as ``channel`` in :meth:`same_context`. user : Optional[discord.abc.User] Same as ``user`` in :meth:`same_context`. Returns ------- MessagePredicate The event predicate. """ valid_int = cls.valid_int(ctx, channel, user) valid_float = cls.valid_float(ctx, channel, user) return cls(lambda self, m: (valid_int(m) or valid_float(m)) and float(m.content) > value)
Python
def length_less( cls, length: int, ctx: Optional[commands.Context] = None, channel: Optional[Union[discord.TextChannel, discord.DMChannel]] = None, user: Optional[discord.abc.User] = None, ) -> "MessagePredicate": """Match if the response's length is less than the specified length. Parameters ---------- length : int The value to compare the response's length with. ctx : Optional[Context] Same as ``ctx`` in :meth:`same_context`. channel : Optional[discord.TextChannel] Same as ``channel`` in :meth:`same_context`. user : Optional[discord.abc.User] Same as ``user`` in :meth:`same_context`. Returns ------- MessagePredicate The event predicate. """ same_context = cls.same_context(ctx, channel, user) return cls(lambda self, m: same_context(m) and len(m.content) <= length)
def length_less( cls, length: int, ctx: Optional[commands.Context] = None, channel: Optional[Union[discord.TextChannel, discord.DMChannel]] = None, user: Optional[discord.abc.User] = None, ) -> "MessagePredicate": """Match if the response's length is less than the specified length. Parameters ---------- length : int The value to compare the response's length with. ctx : Optional[Context] Same as ``ctx`` in :meth:`same_context`. channel : Optional[discord.TextChannel] Same as ``channel`` in :meth:`same_context`. user : Optional[discord.abc.User] Same as ``user`` in :meth:`same_context`. Returns ------- MessagePredicate The event predicate. """ same_context = cls.same_context(ctx, channel, user) return cls(lambda self, m: same_context(m) and len(m.content) <= length)
Python
def length_greater( cls, length: int, ctx: Optional[commands.Context] = None, channel: Optional[Union[discord.TextChannel, discord.DMChannel]] = None, user: Optional[discord.abc.User] = None, ) -> "MessagePredicate": """Match if the response's length is greater than the specified length. Parameters ---------- length : int The value to compare the response's length with. ctx : Optional[Context] Same as ``ctx`` in :meth:`same_context`. channel : Optional[discord.TextChannel] Same as ``channel`` in :meth:`same_context`. user : Optional[discord.abc.User] Same as ``user`` in :meth:`same_context`. Returns ------- MessagePredicate The event predicate. """ same_context = cls.same_context(ctx, channel, user) return cls(lambda self, m: same_context(m) and len(m.content) >= length)
def length_greater( cls, length: int, ctx: Optional[commands.Context] = None, channel: Optional[Union[discord.TextChannel, discord.DMChannel]] = None, user: Optional[discord.abc.User] = None, ) -> "MessagePredicate": """Match if the response's length is greater than the specified length. Parameters ---------- length : int The value to compare the response's length with. ctx : Optional[Context] Same as ``ctx`` in :meth:`same_context`. channel : Optional[discord.TextChannel] Same as ``channel`` in :meth:`same_context`. user : Optional[discord.abc.User] Same as ``user`` in :meth:`same_context`. Returns ------- MessagePredicate The event predicate. """ same_context = cls.same_context(ctx, channel, user) return cls(lambda self, m: same_context(m) and len(m.content) >= length)
Python
def same_context( cls, message: Optional[discord.Message] = None, user: Optional[discord.abc.User] = None ) -> "ReactionPredicate": """Match if a reaction fits the described context. This will ignore reactions added by the bot user, regardless of whether or not ``user`` is supplied. Parameters ---------- message : Optional[discord.Message] The message which we expect a reaction to. If unspecified, the reaction's message will be ignored. user : Optional[discord.abc.User] The user we expect to react. If unspecified, the user who added the reaction will be ignored. Returns ------- ReactionPredicate The event predicate. """ # noinspection PyProtectedMember me_id = message._state.self_id return cls( lambda self, r, u: u.id != me_id and (message is None or r.message.id == message.id) and (user is None or u.id == user.id) )
def same_context( cls, message: Optional[discord.Message] = None, user: Optional[discord.abc.User] = None ) -> "ReactionPredicate": """Match if a reaction fits the described context. This will ignore reactions added by the bot user, regardless of whether or not ``user`` is supplied. Parameters ---------- message : Optional[discord.Message] The message which we expect a reaction to. If unspecified, the reaction's message will be ignored. user : Optional[discord.abc.User] The user we expect to react. If unspecified, the user who added the reaction will be ignored. Returns ------- ReactionPredicate The event predicate. """ # noinspection PyProtectedMember me_id = message._state.self_id return cls( lambda self, r, u: u.id != me_id and (message is None or r.message.id == message.id) and (user is None or u.id == user.id) )
Python
async def leaderboard(self, ctx, world = None): """See quiz leaderboard. Type `luci leaderboard global` to see global leaderboard""" if (world != None): self.cursor.execute(f"""SELECT * FROM quiz WHERE guild_id = {ctx.guild.id} ORDER BY points DESC""") else: self.cursor.execute("""SELECT * FROM quiz ORDER BY points DESC""") data = self.cursor.fetchall() embed = discord.Embed( title = "Global Leaderboard" if world else "Leaderboard", color = 0x07f223 ) emojies = ["🥇", "🥈", "🥉", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"] # Add fields to the embed for index in range(len(data)): user = self.bot.get_user(data[index][0]) embed.add_field( name = f"{emojies[index]} {user.name}#{user.discriminator}", value = f"Points: {data[index][1]}", inline = False ) await ctx.send(embed = embed)
async def leaderboard(self, ctx, world = None): """See quiz leaderboard. Type `luci leaderboard global` to see global leaderboard""" if (world != None): self.cursor.execute(f"""SELECT * FROM quiz WHERE guild_id = {ctx.guild.id} ORDER BY points DESC""") else: self.cursor.execute("""SELECT * FROM quiz ORDER BY points DESC""") data = self.cursor.fetchall() embed = discord.Embed( title = "Global Leaderboard" if world else "Leaderboard", color = 0x07f223 ) emojies = ["🥇", "🥈", "🥉", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"] # Add fields to the embed for index in range(len(data)): user = self.bot.get_user(data[index][0]) embed.add_field( name = f"{emojies[index]} {user.name}#{user.discriminator}", value = f"Points: {data[index][1]}", inline = False ) await ctx.send(embed = embed)
Python
async def startgame(ctx: commands.Context, user: discord.Member) -> bool: """ Whether to start the connect 4 game. """ await ctx.send( f"{user.mention}, {ctx.author.name} is challenging you to a game of Connect4. (y/n)" ) try: pred = MessagePredicate.yes_or_no(ctx, user = user) await ctx.bot.wait_for("message", check = pred, timeout = 60) except asyncio.TimeoutError: await ctx.send("Game offer declined, cancelling.") return False if pred.result: return True await ctx.send("Game cancelled.") return False
async def startgame(ctx: commands.Context, user: discord.Member) -> bool: """ Whether to start the connect 4 game. """ await ctx.send( f"{user.mention}, {ctx.author.name} is challenging you to a game of Connect4. (y/n)" ) try: pred = MessagePredicate.yes_or_no(ctx, user = user) await ctx.bot.wait_for("message", check = pred, timeout = 60) except asyncio.TimeoutError: await ctx.send("Game offer declined, cancelling.") return False if pred.result: return True await ctx.send("Game cancelled.") return False
Python
def loss(hypes, decoded_logits, labels): """Calculate the loss from the logits and the labels. Args: logits: Logits tensor, float - [batch_size, NUM_CLASSES]. labels: Labels tensor, int32 - [batch_size]. Returns: loss: Loss tensor of type float. """ logits = decoded_logits['logits'] with tf.name_scope('loss'): xentropy = tf.nn.sparse_softmax_cross_entropy_with_logits( logits=logits, labels=labels, name="xentropy") class_loss = tf.reduce_mean(xentropy, name='road_loss_mean') reg_loss_col = tf.GraphKeys.REGULARIZATION_LOSSES weight_loss = tf.add_n(tf.get_collection(reg_loss_col), name='reg_loss') losses = {} losses['total_loss'] = class_loss+weight_loss losses['loss'] = class_loss losses['weight_loss'] = weight_loss return losses
def loss(hypes, decoded_logits, labels): """Calculate the loss from the logits and the labels. Args: logits: Logits tensor, float - [batch_size, NUM_CLASSES]. labels: Labels tensor, int32 - [batch_size]. Returns: loss: Loss tensor of type float. """ logits = decoded_logits['logits'] with tf.name_scope('loss'): xentropy = tf.nn.sparse_softmax_cross_entropy_with_logits( logits=logits, labels=labels, name="xentropy") class_loss = tf.reduce_mean(xentropy, name='road_loss_mean') reg_loss_col = tf.GraphKeys.REGULARIZATION_LOSSES weight_loss = tf.add_n(tf.get_collection(reg_loss_col), name='reg_loss') losses = {} losses['total_loss'] = class_loss+weight_loss losses['loss'] = class_loss losses['weight_loss'] = weight_loss return losses
Python
def evaluation(hyp, images, labels, decoded_logits, losses, global_step): """Evaluate the quality of the logits at predicting the label. Args: logits: Logits tensor, float - [batch_size, NUM_CLASSES]. labels: Labels tensor, int32 - [batch_size], with values in the range [0, NUM_CLASSES). Returns: A scalar int32 tensor with the number of examples (out of batch_size) that were predicted correctly. """ # For a classifier model, we can use the in_top_k Op. # It returns a bool tensor with shape [batch_size] that is true for # the examples where the label's is was in the top k (here k=1) # of all logits for that example. eval_list = [] road_classes = hyp["road_classes"] logits = decoded_logits['logits'] correct_road = tf.nn.in_top_k(logits, labels, 1) acc_road = tf.reduce_sum(tf.cast(correct_road, tf.int32)) eval_list.append(('Acc. Road ', acc_road)) eval_list.append(('Class loss', losses['loss'])) eval_list.append(('l2', losses['weight_loss'])) # eval_list.append(('Precision', tp/(tp + fp))) # eval_list.append(('True BG', tn/(tn + fp))) # eval_list.append(('True Street [Recall]', tp/(tp + fn))) return eval_list
def evaluation(hyp, images, labels, decoded_logits, losses, global_step): """Evaluate the quality of the logits at predicting the label. Args: logits: Logits tensor, float - [batch_size, NUM_CLASSES]. labels: Labels tensor, int32 - [batch_size], with values in the range [0, NUM_CLASSES). Returns: A scalar int32 tensor with the number of examples (out of batch_size) that were predicted correctly. """ # For a classifier model, we can use the in_top_k Op. # It returns a bool tensor with shape [batch_size] that is true for # the examples where the label's is was in the top k (here k=1) # of all logits for that example. eval_list = [] road_classes = hyp["road_classes"] logits = decoded_logits['logits'] correct_road = tf.nn.in_top_k(logits, labels, 1) acc_road = tf.reduce_sum(tf.cast(correct_road, tf.int32)) eval_list.append(('Acc. Road ', acc_road)) eval_list.append(('Class loss', losses['loss'])) eval_list.append(('l2', losses['weight_loss'])) # eval_list.append(('Precision', tp/(tp + fp))) # eval_list.append(('True BG', tn/(tn + fp))) # eval_list.append(('True Street [Recall]', tp/(tp + fn))) return eval_list
Python
def to_seconds(string): """ Converts a human readable time string into seconds. Accepts: - 's': seconds - 'm': minutes - 'h': hours - 'd': days Examples: >>> to_seconds('1m30s') 90 >>> to_seconds('5m') 300 >>> to_seconds('1h') 3600 >>> to_seconds('1h30m') 5400 >>> to_seconds('3d') 259200 >>> to_seconds('42x') Traceback (most recent call last): ... ValueError """ units = { 's': 1, 'm': 60, 'h': 60 * 60, 'd': 60 * 60 * 24 } match = re.search(r'(?:(?P<d>\d+)d)?(?:(?P<h>\d+)h)?(?:(?P<m>\d+)m)?(?:(?P<s>\d+)s)?', string) if not match or not any(match.groups()): raise ValueError total = 0 for unit, seconds in units.iteritems(): if match.group(unit) is not None: total += int(match.group(unit)) * seconds return total
def to_seconds(string): """ Converts a human readable time string into seconds. Accepts: - 's': seconds - 'm': minutes - 'h': hours - 'd': days Examples: >>> to_seconds('1m30s') 90 >>> to_seconds('5m') 300 >>> to_seconds('1h') 3600 >>> to_seconds('1h30m') 5400 >>> to_seconds('3d') 259200 >>> to_seconds('42x') Traceback (most recent call last): ... ValueError """ units = { 's': 1, 'm': 60, 'h': 60 * 60, 'd': 60 * 60 * 24 } match = re.search(r'(?:(?P<d>\d+)d)?(?:(?P<h>\d+)h)?(?:(?P<m>\d+)m)?(?:(?P<s>\d+)s)?', string) if not match or not any(match.groups()): raise ValueError total = 0 for unit, seconds in units.iteritems(): if match.group(unit) is not None: total += int(match.group(unit)) * seconds return total
Python
def calculate_cooperation_stuff(self): """ Calculate the cooperation rate for each bot in each bot pair and store these in an instance variable STORES: - cooperation_matrix: numpy array, cooperation_matrix[i][j] is i's cooperation rate when partnered with j - bigger_man_scores: a bot's bigger_man_score is the fraction of partnerships in which that bot cooperated at least as much as its partner - cooperation_rates: the fraction of each bot's total moves that are cooperations """ tr = self.tourney_res bot_list = tr.get_bot_list() bot_id_list = [bot.tournament_id for bot in bot_list] num_bots = len(bot_list) coop_matrix = [[0 for _ in xrange(num_bots)] for _ in xrange(num_bots)] big_man_scores = {} for bot_id in bot_id_list: big_man_scores[bot_id] = 0.0 coop_rates = {} # for each bot pair, count the times each bot cooperates and divide by # the total number of turns, and store this rate in coop_matrix for i in xrange(num_bots): bot1_id = bot_list[i].tournament_id for j in xrange(i, num_bots): bot2_id = bot_list[j].tournament_id interactions = tr.get_interactions(bot1_id, bot2_id) total_turns = sum([len(meeting) for meeting in interactions]) bot1_coops, bot2_coops = 0.0, 0.0 for meeting in interactions: for turn in meeting: if turn[0] == 'C': bot1_coops += 1.0 if turn[1] == 'C': bot2_coops += 1.0 bot1_rate = bot1_coops/total_turns bot2_rate = bot2_coops/total_turns coop_matrix[bot1_id][bot2_id] = bot1_rate coop_matrix[bot2_id][bot1_id] = bot2_rate # don't include the case where a bot partners with its own clone if bot1_id != bot2_id: if bot1_rate >= bot2_rate: big_man_scores[bot1_id] += 1.0 if bot2_rate >= bot1_rate: big_man_scores[bot2_id] += 1.0 for i in xrange(num_bots): bot_id = bot_list[i].tournament_id bot_coop_rates = coop_matrix[bot_id] coop_rates[bot_id] = sum(bot_coop_rates)/len(bot_coop_rates) big_man_scores[bot_id] = big_man_scores[bot_id]/(num_bots-1) # save these cooperation rates per interaction and the overall # cooperation rate for each bot self.cooperation_matrix = np.array(coop_matrix) self.bigger_man_scores = big_man_scores self.cooperation_rates = coop_rates
def calculate_cooperation_stuff(self): """ Calculate the cooperation rate for each bot in each bot pair and store these in an instance variable STORES: - cooperation_matrix: numpy array, cooperation_matrix[i][j] is i's cooperation rate when partnered with j - bigger_man_scores: a bot's bigger_man_score is the fraction of partnerships in which that bot cooperated at least as much as its partner - cooperation_rates: the fraction of each bot's total moves that are cooperations """ tr = self.tourney_res bot_list = tr.get_bot_list() bot_id_list = [bot.tournament_id for bot in bot_list] num_bots = len(bot_list) coop_matrix = [[0 for _ in xrange(num_bots)] for _ in xrange(num_bots)] big_man_scores = {} for bot_id in bot_id_list: big_man_scores[bot_id] = 0.0 coop_rates = {} # for each bot pair, count the times each bot cooperates and divide by # the total number of turns, and store this rate in coop_matrix for i in xrange(num_bots): bot1_id = bot_list[i].tournament_id for j in xrange(i, num_bots): bot2_id = bot_list[j].tournament_id interactions = tr.get_interactions(bot1_id, bot2_id) total_turns = sum([len(meeting) for meeting in interactions]) bot1_coops, bot2_coops = 0.0, 0.0 for meeting in interactions: for turn in meeting: if turn[0] == 'C': bot1_coops += 1.0 if turn[1] == 'C': bot2_coops += 1.0 bot1_rate = bot1_coops/total_turns bot2_rate = bot2_coops/total_turns coop_matrix[bot1_id][bot2_id] = bot1_rate coop_matrix[bot2_id][bot1_id] = bot2_rate # don't include the case where a bot partners with its own clone if bot1_id != bot2_id: if bot1_rate >= bot2_rate: big_man_scores[bot1_id] += 1.0 if bot2_rate >= bot1_rate: big_man_scores[bot2_id] += 1.0 for i in xrange(num_bots): bot_id = bot_list[i].tournament_id bot_coop_rates = coop_matrix[bot_id] coop_rates[bot_id] = sum(bot_coop_rates)/len(bot_coop_rates) big_man_scores[bot_id] = big_man_scores[bot_id]/(num_bots-1) # save these cooperation rates per interaction and the overall # cooperation rate for each bot self.cooperation_matrix = np.array(coop_matrix) self.bigger_man_scores = big_man_scores self.cooperation_rates = coop_rates
Python
def principle_eigenvector(self, C, iters): """ Starts with every node at a constant amount of 'worth' and iterates using C to update every node's 'worth' until converging on the principle eigenvector ARGS: - C: C is a numpy array in [0, 1]^(nxn) where values represent the 'votes' between nodes like in PageRank RETURNS: - pev: pev is the principle eigenvector of C, representing the end values of each node. normalize to add to n """ num_vals = len(C) current_vals = np.array([1 for _ in xrange(num_vals)]) i = 0 while i < iters: current_vals = C.dot(current_vals) i += 1 total_val = float(sum(current_vals)) pev = copy.copy(current_vals) for idx, v in enumerate(current_vals): try: pev[idx] = (num_vals/total_val)*v except ZeroDivisionError: pev[idx] = 1 return pev
def principle_eigenvector(self, C, iters): """ Starts with every node at a constant amount of 'worth' and iterates using C to update every node's 'worth' until converging on the principle eigenvector ARGS: - C: C is a numpy array in [0, 1]^(nxn) where values represent the 'votes' between nodes like in PageRank RETURNS: - pev: pev is the principle eigenvector of C, representing the end values of each node. normalize to add to n """ num_vals = len(C) current_vals = np.array([1 for _ in xrange(num_vals)]) i = 0 while i < iters: current_vals = C.dot(current_vals) i += 1 total_val = float(sum(current_vals)) pev = copy.copy(current_vals) for idx, v in enumerate(current_vals): try: pev[idx] = (num_vals/total_val)*v except ZeroDivisionError: pev[idx] = 1 return pev
Python
def calculate_network_morality(self): """ Calculate and store the morality metrics of network jesus and network moses for each bot ARGS: - coop_matrix: numpy array, coop_matrix[i][j] is i's cooperation rate when partnered with j STORES: - eigenjesus_scores: list of recursively defined morality scores (cooperating with cooperaters is worth more), cooperating always helps - eigenmoses_scores: list of recursively defined morality scores (cooperating with cooperaters is worth more), cooperating with a defector actually counts against you """ ## TODO: come up with programmtic way of determining number of iters self.eigenjesus_scores =\ self.principle_eigenvector(self.cooperation_matrix, 100) coop_def_matrix = (self.cooperation_matrix-0.5)*2 self.eigenmoses_scores =\ self.principle_eigenvector(coop_def_matrix, 100)
def calculate_network_morality(self): """ Calculate and store the morality metrics of network jesus and network moses for each bot ARGS: - coop_matrix: numpy array, coop_matrix[i][j] is i's cooperation rate when partnered with j STORES: - eigenjesus_scores: list of recursively defined morality scores (cooperating with cooperaters is worth more), cooperating always helps - eigenmoses_scores: list of recursively defined morality scores (cooperating with cooperaters is worth more), cooperating with a defector actually counts against you """ ## TODO: come up with programmtic way of determining number of iters self.eigenjesus_scores =\ self.principle_eigenvector(self.cooperation_matrix, 100) coop_def_matrix = (self.cooperation_matrix-0.5)*2 self.eigenmoses_scores =\ self.principle_eigenvector(coop_def_matrix, 100)
Python
def calculate_scores(self): """ Get the scores for each bot pair meetings list and store in self.interaction_scores. Tally up the total score for each bot and store in self.bot_info_by_id['total'] """ for bot_pair in self.interactions: self.interaction_scores[bot_pair] = [] for meeting in self.interactions[bot_pair]: meeting_scores = [0, 0] for turn in meeting: turn_scores = self.score_turn(turn) # accumulate scores for meeting meeting_scores[0] += turn_scores[0] meeting_scores[1] += turn_scores[1] meeting_scores = tuple(meeting_scores) # add scores for meeting to list of meeting scores for this pair self.interaction_scores[bot_pair].append(meeting_scores) # also add to total for each bot, but only once if this is a bot # paired with its clone if bot_pair[0] == bot_pair[1]: self.bot_info_by_id[bot_pair[0]]['total']\ += meeting_scores[0] else: for idx, bot_id in enumerate(bot_pair): self.bot_info_by_id[bot_id]['total']\ += meeting_scores[idx]
def calculate_scores(self): """ Get the scores for each bot pair meetings list and store in self.interaction_scores. Tally up the total score for each bot and store in self.bot_info_by_id['total'] """ for bot_pair in self.interactions: self.interaction_scores[bot_pair] = [] for meeting in self.interactions[bot_pair]: meeting_scores = [0, 0] for turn in meeting: turn_scores = self.score_turn(turn) # accumulate scores for meeting meeting_scores[0] += turn_scores[0] meeting_scores[1] += turn_scores[1] meeting_scores = tuple(meeting_scores) # add scores for meeting to list of meeting scores for this pair self.interaction_scores[bot_pair].append(meeting_scores) # also add to total for each bot, but only once if this is a bot # paired with its clone if bot_pair[0] == bot_pair[1]: self.bot_info_by_id[bot_pair[0]]['total']\ += meeting_scores[0] else: for idx, bot_id in enumerate(bot_pair): self.bot_info_by_id[bot_id]['total']\ += meeting_scores[idx]
Python
def generate_interaction_lengths(self, w, numMeetings): """ Based on a probability of continuing each step, generate interaction lengths for the bot pairs ARGS: - w: probability of interaction continuing at each step - numMeetings: number of interaction_lengths needed to be generated RETURNS: - interaction_lengths: a list of integers representing how long each meeting between bots will be (if the list is n long, it is because each bot pair meets n times) """ interaction_lengths = [] i = 0 while i < numMeetings: meeting_length = 1 while True: r = random.random() if r > w: break else: meeting_length += 1 interaction_lengths.append(meeting_length) i += 1 return interaction_lengths
def generate_interaction_lengths(self, w, numMeetings): """ Based on a probability of continuing each step, generate interaction lengths for the bot pairs ARGS: - w: probability of interaction continuing at each step - numMeetings: number of interaction_lengths needed to be generated RETURNS: - interaction_lengths: a list of integers representing how long each meeting between bots will be (if the list is n long, it is because each bot pair meets n times) """ interaction_lengths = [] i = 0 while i < numMeetings: meeting_length = 1 while True: r = random.random() if r > w: break else: meeting_length += 1 interaction_lengths.append(meeting_length) i += 1 return interaction_lengths
Python
def bot_interaction(self, bot1, bot2, interaction_length, payoffs={'T': 5,'R': 3,'P': 1,'S': 0}, w=0.995): """ Two bots paired together interacting ARGS: - bot1, bot2: instances of BotPlayer (presumably subclasses of BotPlayer), representing the two participating bots - interaction_length: how many turns bot1 and bot2 play in this interaction RETURNS: - past_moves: list of every move that occurred during the interaction """ past_moves_1 = [] past_moves_2 = [] i = 0 while i < interaction_length: bot1_move = bot1.getNextMove(past_moves_1, payoffs=payoffs, w=w) bot2_move = bot2.getNextMove(past_moves_2, payoffs=payoffs, w=w) next_moves_1 = (bot1_move, bot2_move) next_moves_2 = (bot2_move, bot1_move) past_moves_1.append(next_moves_1) past_moves_2.append(next_moves_2) i += 1 return past_moves_1
def bot_interaction(self, bot1, bot2, interaction_length, payoffs={'T': 5,'R': 3,'P': 1,'S': 0}, w=0.995): """ Two bots paired together interacting ARGS: - bot1, bot2: instances of BotPlayer (presumably subclasses of BotPlayer), representing the two participating bots - interaction_length: how many turns bot1 and bot2 play in this interaction RETURNS: - past_moves: list of every move that occurred during the interaction """ past_moves_1 = [] past_moves_2 = [] i = 0 while i < interaction_length: bot1_move = bot1.getNextMove(past_moves_1, payoffs=payoffs, w=w) bot2_move = bot2.getNextMove(past_moves_2, payoffs=payoffs, w=w) next_moves_1 = (bot1_move, bot2_move) next_moves_2 = (bot2_move, bot1_move) past_moves_1.append(next_moves_1) past_moves_2.append(next_moves_2) i += 1 return past_moves_1
Python
def validate_tournament_inputs(self, botList, numMeetings, payoffs, w): """ Make sure the inputs to runTournament make sense and if they do not, say why in the list 'errors' ARGS: - botList: list of bots to participate in the tournament - w: probability of interaction continuing at each step - numMeetings: number of times each bot is paired with each other bot - payoffs: defines the scores for each Prisoner's Dilemma situation RETURNS: - errors: list or error messages to let the user know what is wrong with the inputs, if anything """ errors = [] # botList has to be a list of BotPlayer instances for bot in botList: if not isinstance(bot, bp.BotPlayer): errors.append("botList must be a list of BotPlayer objects") break if int(numMeetings) != numMeetings: errors.append("numMeetings must represent an integer") if numMeetings < 1: errors.append("numMeetings must be at least 1") if not (payoffs['T'] > payoffs['R'] > payoffs['P'] > payoffs['S']): errors.append("payoffs must obey T > R > P > S") if not (2*payoffs['R'] > payoffs['T'] + payoffs['S']): errors.append("payoffs must obey 2*R > T + S") if not (0 < w < 1): errors.append("w must be a number between 0 and 1") return errors
def validate_tournament_inputs(self, botList, numMeetings, payoffs, w): """ Make sure the inputs to runTournament make sense and if they do not, say why in the list 'errors' ARGS: - botList: list of bots to participate in the tournament - w: probability of interaction continuing at each step - numMeetings: number of times each bot is paired with each other bot - payoffs: defines the scores for each Prisoner's Dilemma situation RETURNS: - errors: list or error messages to let the user know what is wrong with the inputs, if anything """ errors = [] # botList has to be a list of BotPlayer instances for bot in botList: if not isinstance(bot, bp.BotPlayer): errors.append("botList must be a list of BotPlayer objects") break if int(numMeetings) != numMeetings: errors.append("numMeetings must represent an integer") if numMeetings < 1: errors.append("numMeetings must be at least 1") if not (payoffs['T'] > payoffs['R'] > payoffs['P'] > payoffs['S']): errors.append("payoffs must obey T > R > P > S") if not (2*payoffs['R'] > payoffs['T'] + payoffs['S']): errors.append("payoffs must obey 2*R > T + S") if not (0 < w < 1): errors.append("w must be a number between 0 and 1") return errors
Python
def runTournament(self, botList, numMeetings, payoffs={'T':5,'R':3,'P':1,'S':0}, w=0.995): """ Main method, partners each bot with each other bot with w probability of ending each turn (length of interactions is determined (using w) before any pairings, so all pairings use the same list of interaction lengths) ARGS: - botList: list of bots to participate in the tournament - w: probability of interaction continuing at each step - numMeetings: number of times each bot is paired with each other bot - payoffs: defines the scores for each Prisoner's Dilemma situation RETURNS: - tourney_res: TournamentResults object with all the info """ # validate inputs error_messages =\ self.validate_tournament_inputs(botList, numMeetings, payoffs, w) if error_messages: print(error_messages) return -1 # dictionary of interactions to pass to TournamentResults interactions = {} # determine length of each interaction based on w interaction_lengths =\ self.generate_interaction_lengths(w, numMeetings) # assign each bot a tournament id number for t_id, bot in enumerate(botList): bot.tournament_id = t_id # pair each bot with each other bot and save the results num_bots = len(botList) for i in xrange(num_bots): for j in xrange(i, num_bots): bot1 = botList[i] bot2 = botList[j] meeting_results_list = [] for m in xrange(numMeetings): interaction_length = interaction_lengths[m] meeting_results =\ self.bot_interaction(bot1, bot2, interaction_length,\ payoffs=payoffs, w=w) meeting_results_list.append(meeting_results) interactions[(bot1.tournament_id, bot2.tournament_id)] =\ meeting_results_list tourney_res = tr.TournamentResults(botList, interactions, payoffs) return tourney_res
def runTournament(self, botList, numMeetings, payoffs={'T':5,'R':3,'P':1,'S':0}, w=0.995): """ Main method, partners each bot with each other bot with w probability of ending each turn (length of interactions is determined (using w) before any pairings, so all pairings use the same list of interaction lengths) ARGS: - botList: list of bots to participate in the tournament - w: probability of interaction continuing at each step - numMeetings: number of times each bot is paired with each other bot - payoffs: defines the scores for each Prisoner's Dilemma situation RETURNS: - tourney_res: TournamentResults object with all the info """ # validate inputs error_messages =\ self.validate_tournament_inputs(botList, numMeetings, payoffs, w) if error_messages: print(error_messages) return -1 # dictionary of interactions to pass to TournamentResults interactions = {} # determine length of each interaction based on w interaction_lengths =\ self.generate_interaction_lengths(w, numMeetings) # assign each bot a tournament id number for t_id, bot in enumerate(botList): bot.tournament_id = t_id # pair each bot with each other bot and save the results num_bots = len(botList) for i in xrange(num_bots): for j in xrange(i, num_bots): bot1 = botList[i] bot2 = botList[j] meeting_results_list = [] for m in xrange(numMeetings): interaction_length = interaction_lengths[m] meeting_results =\ self.bot_interaction(bot1, bot2, interaction_length,\ payoffs=payoffs, w=w) meeting_results_list.append(meeting_results) interactions[(bot1.tournament_id, bot2.tournament_id)] =\ meeting_results_list tourney_res = tr.TournamentResults(botList, interactions, payoffs) return tourney_res
Python
def start_service(): """Start this service set SENTRY_DSN environmental variable to enable logging with Sentry """ # Initialize Sentry sentry_sdk.init(os.environ.get('SENTRY_DSN')) # Initialize Falcon api = falcon.API() api.add_route('/rows/{row_id}', Row()) api.add_route('/rows', Rows()) api.add_sink(default_error, '') return api
def start_service(): """Start this service set SENTRY_DSN environmental variable to enable logging with Sentry """ # Initialize Sentry sentry_sdk.init(os.environ.get('SENTRY_DSN')) # Initialize Falcon api = falcon.API() api.add_route('/rows/{row_id}', Row()) api.add_route('/rows', Rows()) api.add_sink(default_error, '') return api
Python
def validate_post_params(params_json): """Enforce parameter inputs for post method""" validate_spreadsheet_params(params_json) if 'row_values' not in params_json: raise Exception(ERR_MISSING_ROW_VALUES)
def validate_post_params(params_json): """Enforce parameter inputs for post method""" validate_spreadsheet_params(params_json) if 'row_values' not in params_json: raise Exception(ERR_MISSING_ROW_VALUES)
Python
def validate_get_params(params): """Enforce parameter inputs for get method""" validate_spreadsheet_params(params) if 'column_label' not in params: raise Exception(ERR_MISSING_COLUMN) if 'value' not in params: raise Exception(ERR_MISSING_VALUE)
def validate_get_params(params): """Enforce parameter inputs for get method""" validate_spreadsheet_params(params) if 'column_label' not in params: raise Exception(ERR_MISSING_COLUMN) if 'value' not in params: raise Exception(ERR_MISSING_VALUE)
Python
def validate_patch_params(params_json): """Enforce parameter inputs for patch method""" validate_spreadsheet_params(params_json) if 'id_column_label' not in params_json: raise Exception(ERR_MISSING_ID_COLUMN_LABEL) if 'label_value_map' not in params_json: raise Exception(ERR_MISSING_LABEL_VALUE_MAP)
def validate_patch_params(params_json): """Enforce parameter inputs for patch method""" validate_spreadsheet_params(params_json) if 'id_column_label' not in params_json: raise Exception(ERR_MISSING_ID_COLUMN_LABEL) if 'label_value_map' not in params_json: raise Exception(ERR_MISSING_LABEL_VALUE_MAP)
Python
def validate_get_params(params_json): """Enforce parameter inputs for get method""" validate_spreadsheet_params(params_json) if 'id_column_label' not in params_json: raise Exception(ERR_MISSING_ID_COLUMN_LABEL)
def validate_get_params(params_json): """Enforce parameter inputs for get method""" validate_spreadsheet_params(params_json) if 'id_column_label' not in params_json: raise Exception(ERR_MISSING_ID_COLUMN_LABEL)
Python
def isolate_dQdV_peaks(processed_cycler_run, diag_nr, charge_y_n, cwt_range, max_nr_peaks, rpt_type, half_peak_width=0.075): """ Determine the number of cycles to reach a certain level of degradation Args: processed_cycler_run: processed_cycler_run (beep.structure.ProcessedCyclerRun): information about cycler run rpt_type: string indicating which rpt to pick charge_y_n: if 1 (default), takes charge dQdV, if 0, takes discharge dQdV diag_nr: if 1 (default), takes dQdV of 1st RPT past the initial diagnostic cwt_range: range for scaling parameter to use in Continuous Wave Transform method - used for peak finding Returns: dataframe with Voltage and dQdV columns for charge or discharge curve in the rpt_type diagnostic cycle. The peaks will be isolated """ rpt_type_data = processed_cycler_run.diagnostic_interpolated[(processed_cycler_run.diagnostic_interpolated.cycle_type == rpt_type)] cycles = rpt_type_data.cycle_index.unique() ## Take charge or discharge from cycle 'diag_nr' data = pd.DataFrame({'dQdV': [], 'voltage': []}) if charge_y_n == 1: data.dQdV = rpt_type_data[ (rpt_type_data.cycle_index == cycles[diag_nr]) & (rpt_type_data.step_type == 0)].charge_dQdV.values data.voltage = rpt_type_data[ (rpt_type_data.cycle_index == cycles[diag_nr]) & (rpt_type_data.step_type == 0)].voltage.values elif charge_y_n == 0: data.dQdV = rpt_type_data[ (rpt_type_data.cycle_index == cycles[diag_nr]) & (rpt_type_data.step_type == 1)].discharge_dQdV.values data.voltage = rpt_type_data[ (rpt_type_data.cycle_index == cycles[diag_nr]) & (rpt_type_data.step_type == 1)].voltage.values # Turn values to positive temporarily data.dQdV = -data.dQdV else: raise NotImplementedError('Charge_y_n must be either 0 or 1') # Remove NaN from x and y data = data.dropna() # Reset x and y to values without NaNs x = data.voltage y = data.dQdV # Remove strong outliers upper_limit = y.sort_values().tail(round(0.01 * len(y))).mean() + y.sort_values().mean() data = data[(y < upper_limit)] # Reset x and y to values without outliers x = data.voltage y = data.dQdV # Filter out the x values of the peaks only no_filter_data = data # Find peaks peak_indices = signal.find_peaks_cwt(y, cwt_range)[-max_nr_peaks:] peak_voltages = {} peak_dQdVs = {} for count, i in enumerate(peak_indices): temp_filter_data = no_filter_data[((x > x.iloc[i] - half_peak_width) & (x < x.iloc[i] + half_peak_width))] peak_voltages[count] = x.iloc[i] peak_dQdVs[count] = y.iloc[i] if count == 0: filter_data = temp_filter_data else: filter_data = filter_data.append(temp_filter_data) return filter_data, no_filter_data, peak_voltages, peak_dQdVs
def isolate_dQdV_peaks(processed_cycler_run, diag_nr, charge_y_n, cwt_range, max_nr_peaks, rpt_type, half_peak_width=0.075): """ Determine the number of cycles to reach a certain level of degradation Args: processed_cycler_run: processed_cycler_run (beep.structure.ProcessedCyclerRun): information about cycler run rpt_type: string indicating which rpt to pick charge_y_n: if 1 (default), takes charge dQdV, if 0, takes discharge dQdV diag_nr: if 1 (default), takes dQdV of 1st RPT past the initial diagnostic cwt_range: range for scaling parameter to use in Continuous Wave Transform method - used for peak finding Returns: dataframe with Voltage and dQdV columns for charge or discharge curve in the rpt_type diagnostic cycle. The peaks will be isolated """ rpt_type_data = processed_cycler_run.diagnostic_interpolated[(processed_cycler_run.diagnostic_interpolated.cycle_type == rpt_type)] cycles = rpt_type_data.cycle_index.unique() ## Take charge or discharge from cycle 'diag_nr' data = pd.DataFrame({'dQdV': [], 'voltage': []}) if charge_y_n == 1: data.dQdV = rpt_type_data[ (rpt_type_data.cycle_index == cycles[diag_nr]) & (rpt_type_data.step_type == 0)].charge_dQdV.values data.voltage = rpt_type_data[ (rpt_type_data.cycle_index == cycles[diag_nr]) & (rpt_type_data.step_type == 0)].voltage.values elif charge_y_n == 0: data.dQdV = rpt_type_data[ (rpt_type_data.cycle_index == cycles[diag_nr]) & (rpt_type_data.step_type == 1)].discharge_dQdV.values data.voltage = rpt_type_data[ (rpt_type_data.cycle_index == cycles[diag_nr]) & (rpt_type_data.step_type == 1)].voltage.values # Turn values to positive temporarily data.dQdV = -data.dQdV else: raise NotImplementedError('Charge_y_n must be either 0 or 1') # Remove NaN from x and y data = data.dropna() # Reset x and y to values without NaNs x = data.voltage y = data.dQdV # Remove strong outliers upper_limit = y.sort_values().tail(round(0.01 * len(y))).mean() + y.sort_values().mean() data = data[(y < upper_limit)] # Reset x and y to values without outliers x = data.voltage y = data.dQdV # Filter out the x values of the peaks only no_filter_data = data # Find peaks peak_indices = signal.find_peaks_cwt(y, cwt_range)[-max_nr_peaks:] peak_voltages = {} peak_dQdVs = {} for count, i in enumerate(peak_indices): temp_filter_data = no_filter_data[((x > x.iloc[i] - half_peak_width) & (x < x.iloc[i] + half_peak_width))] peak_voltages[count] = x.iloc[i] peak_dQdVs[count] = y.iloc[i] if count == 0: filter_data = temp_filter_data else: filter_data = filter_data.append(temp_filter_data) return filter_data, no_filter_data, peak_voltages, peak_dQdVs
Python
def generate_model(spec): """ Method that generates a model to fit the RPT data to for peak extraction, using spec dictionary :param spec (dict): dictionary containing X, y model types. :return: composite model objects of lmfit Model class and a parameter object as defined in lmfit. """ composite_model = None params = None x = spec['x'] y = spec['y'] x_min = np.min(x) x_max = np.max(x) x_range = x_max - x_min y_max = np.max(y) for i, basis_func in enumerate(spec['model']): prefix = f'm{i}_' #models is an lmfit object model = getattr(models, basis_func['type'])(prefix=prefix) if basis_func['type'] in ['GaussianModel', 'LorentzianModel', 'VoigtModel']: # for now VoigtModel has gamma constrained to sigma model.set_param_hint('sigma', min=1e-6, max=x_range) model.set_param_hint('center', min=x_min, max=x_max) model.set_param_hint('height', min=1e-6, max=1.1 * y_max) model.set_param_hint('amplitude', min=1e-6) default_params = { prefix + 'center': x_min + x_range * np.random.randn(), prefix + 'height': y_max * np.random.randn(), prefix + 'sigma': x_range * np.random.randn() } else: raise NotImplemented(f'model {basis_func["type"]} not implemented yet') if 'help' in basis_func: # allow override of settings in parameter for param, options in basis_func['help'].items(): model.set_param_hint(param, **options) model_params = model.make_params(**default_params, **basis_func.get('params', {})) if params is None: params = model_params else: params.update(model_params) if composite_model is None: composite_model = model else: composite_model = composite_model + model return composite_model, params
def generate_model(spec): """ Method that generates a model to fit the RPT data to for peak extraction, using spec dictionary :param spec (dict): dictionary containing X, y model types. :return: composite model objects of lmfit Model class and a parameter object as defined in lmfit. """ composite_model = None params = None x = spec['x'] y = spec['y'] x_min = np.min(x) x_max = np.max(x) x_range = x_max - x_min y_max = np.max(y) for i, basis_func in enumerate(spec['model']): prefix = f'm{i}_' #models is an lmfit object model = getattr(models, basis_func['type'])(prefix=prefix) if basis_func['type'] in ['GaussianModel', 'LorentzianModel', 'VoigtModel']: # for now VoigtModel has gamma constrained to sigma model.set_param_hint('sigma', min=1e-6, max=x_range) model.set_param_hint('center', min=x_min, max=x_max) model.set_param_hint('height', min=1e-6, max=1.1 * y_max) model.set_param_hint('amplitude', min=1e-6) default_params = { prefix + 'center': x_min + x_range * np.random.randn(), prefix + 'height': y_max * np.random.randn(), prefix + 'sigma': x_range * np.random.randn() } else: raise NotImplemented(f'model {basis_func["type"]} not implemented yet') if 'help' in basis_func: # allow override of settings in parameter for param, options in basis_func['help'].items(): model.set_param_hint(param, **options) model_params = model.make_params(**default_params, **basis_func.get('params', {})) if params is None: params = model_params else: params.update(model_params) if composite_model is None: composite_model = model else: composite_model = composite_model + model return composite_model, params
Python
def generate_dQdV_peak_fits(processed_cycler_run, rpt_type, diag_nr, charge_y_n, plotting_y_n=0, max_nr_peaks=4, cwt_range = np.arange(10,30)): """ Generate fits characteristics from dQdV peaks Args: processed_cycler_run: processed_cycler_run (beep.structure.ProcessedCyclerRun) diag_nr: if 1, takes dQdV of 1st RPT past the initial diagnostic, 0 (default) is initial dianostic charge_y_n: if 1 (default), takes charge dQdV, if 0, takes discharge dQdV Returns: dataframe with Amplitude, mu and sigma of fitted peaks """ # Uses isolate_dQdV_peaks function to filter out peaks and returns x(Volt) and y(dQdV) values from peaks data, no_filter_data, peak_voltages, peak_dQdVs = isolate_dQdV_peaks(processed_cycler_run, rpt_type=rpt_type, charge_y_n=charge_y_n, diag_nr=diag_nr, cwt_range = cwt_range, max_nr_peaks=max_nr_peaks, half_peak_width=0.07) no_filter_x = no_filter_data.voltage no_filter_y = no_filter_data.dQdV ####### Setting spec for gaussian model generation x = data.voltage y = data.dQdV # Set construct spec using number of peaks model_types = [] for i in np.arange(max_nr_peaks): model_types.append({'type': 'GaussianModel', 'help': {'sigma': {'max': 0.1}}}) spec = { 'x': x, 'y': y, 'model': model_types } # Update spec using the found peaks update_spec_from_peaks(spec, np.arange(max_nr_peaks), peak_voltages, peak_dQdVs) if plotting_y_n: fig, ax = plt.subplots() ax.scatter(spec['x'], spec['y'], s=4) for i in peak_voltages: ax.axvline(x=peak_voltages[i], c='black', linestyle='dotted') ax.scatter(peak_voltages[i], peak_dQdVs[i], s=30, c='red') #### Generate fitting model model, params = generate_model(spec) output = model.fit(spec['y'], params, x=spec['x']) if plotting_y_n: # #Plot residuals # fig, gridspec = output.plot(data_kws={'markersize': 1}) ### Plot components ax.scatter(no_filter_x, no_filter_y, s=4) ax.set_xlabel('Voltage') if charge_y_n: ax.set_title(f'dQdV for charge diag cycle {diag_nr}') ax.set_ylabel('dQdV') else: ax.set_title(f'dQdV for discharge diag cycle {diag_nr}') ax.set_ylabel('- dQdV') components = output.eval_components() for i, model in enumerate(spec['model']): ax.plot(spec['x'], components[f'm{i}_']) # Construct dictionary of peak fits peak_fit_dict = {} for i, model in enumerate(spec['model']): best_values = output.best_values prefix = f'm{i}_' peak_fit_dict[prefix+"Amp"+"_"+rpt_type+"_"+str(charge_y_n)] = [peak_dQdVs[i]] peak_fit_dict[prefix+"Mu"+"_"+rpt_type+"_"+str(charge_y_n)] = [peak_voltages[i]] # Make dataframe out of dict peak_fit_df = pd.DataFrame(peak_fit_dict) # Incorporate troughs of dQdV curve color_list = ['g', 'b', 'r', 'k', 'c'] for peak_nr in np.arange(0, max_nr_peaks - 1): between_outer_peak_data = no_filter_data[ (no_filter_data.voltage > peak_voltages[peak_nr]) & (no_filter_data.voltage < peak_voltages[peak_nr + 1])] pct = 0.05 lowest_dQdV_pct_between_peaks = (between_outer_peak_data.dQdV.sort_values(ascending=False)).tail( round(len(between_outer_peak_data.dQdV) * pct)) if plotting_y_n: ax.axhline(y=lowest_dQdV_pct_between_peaks.mean(), color=color_list[peak_nr], linestyle='-') # Add belly feature to dataframe peak_fit_df[f'trough_height_{peak_nr}_{rpt_type}_{charge_y_n}'] = lowest_dQdV_pct_between_peaks.mean() return peak_fit_df
def generate_dQdV_peak_fits(processed_cycler_run, rpt_type, diag_nr, charge_y_n, plotting_y_n=0, max_nr_peaks=4, cwt_range = np.arange(10,30)): """ Generate fits characteristics from dQdV peaks Args: processed_cycler_run: processed_cycler_run (beep.structure.ProcessedCyclerRun) diag_nr: if 1, takes dQdV of 1st RPT past the initial diagnostic, 0 (default) is initial dianostic charge_y_n: if 1 (default), takes charge dQdV, if 0, takes discharge dQdV Returns: dataframe with Amplitude, mu and sigma of fitted peaks """ # Uses isolate_dQdV_peaks function to filter out peaks and returns x(Volt) and y(dQdV) values from peaks data, no_filter_data, peak_voltages, peak_dQdVs = isolate_dQdV_peaks(processed_cycler_run, rpt_type=rpt_type, charge_y_n=charge_y_n, diag_nr=diag_nr, cwt_range = cwt_range, max_nr_peaks=max_nr_peaks, half_peak_width=0.07) no_filter_x = no_filter_data.voltage no_filter_y = no_filter_data.dQdV ####### Setting spec for gaussian model generation x = data.voltage y = data.dQdV # Set construct spec using number of peaks model_types = [] for i in np.arange(max_nr_peaks): model_types.append({'type': 'GaussianModel', 'help': {'sigma': {'max': 0.1}}}) spec = { 'x': x, 'y': y, 'model': model_types } # Update spec using the found peaks update_spec_from_peaks(spec, np.arange(max_nr_peaks), peak_voltages, peak_dQdVs) if plotting_y_n: fig, ax = plt.subplots() ax.scatter(spec['x'], spec['y'], s=4) for i in peak_voltages: ax.axvline(x=peak_voltages[i], c='black', linestyle='dotted') ax.scatter(peak_voltages[i], peak_dQdVs[i], s=30, c='red') #### Generate fitting model model, params = generate_model(spec) output = model.fit(spec['y'], params, x=spec['x']) if plotting_y_n: # #Plot residuals # fig, gridspec = output.plot(data_kws={'markersize': 1}) ### Plot components ax.scatter(no_filter_x, no_filter_y, s=4) ax.set_xlabel('Voltage') if charge_y_n: ax.set_title(f'dQdV for charge diag cycle {diag_nr}') ax.set_ylabel('dQdV') else: ax.set_title(f'dQdV for discharge diag cycle {diag_nr}') ax.set_ylabel('- dQdV') components = output.eval_components() for i, model in enumerate(spec['model']): ax.plot(spec['x'], components[f'm{i}_']) # Construct dictionary of peak fits peak_fit_dict = {} for i, model in enumerate(spec['model']): best_values = output.best_values prefix = f'm{i}_' peak_fit_dict[prefix+"Amp"+"_"+rpt_type+"_"+str(charge_y_n)] = [peak_dQdVs[i]] peak_fit_dict[prefix+"Mu"+"_"+rpt_type+"_"+str(charge_y_n)] = [peak_voltages[i]] # Make dataframe out of dict peak_fit_df = pd.DataFrame(peak_fit_dict) # Incorporate troughs of dQdV curve color_list = ['g', 'b', 'r', 'k', 'c'] for peak_nr in np.arange(0, max_nr_peaks - 1): between_outer_peak_data = no_filter_data[ (no_filter_data.voltage > peak_voltages[peak_nr]) & (no_filter_data.voltage < peak_voltages[peak_nr + 1])] pct = 0.05 lowest_dQdV_pct_between_peaks = (between_outer_peak_data.dQdV.sort_values(ascending=False)).tail( round(len(between_outer_peak_data.dQdV) * pct)) if plotting_y_n: ax.axhline(y=lowest_dQdV_pct_between_peaks.mean(), color=color_list[peak_nr], linestyle='-') # Add belly feature to dataframe peak_fit_df[f'trough_height_{peak_nr}_{rpt_type}_{charge_y_n}'] = lowest_dQdV_pct_between_peaks.mean() return peak_fit_df
Python
def res_calc(chosen, diag_pos, soc, step_ocv, step_cur, index): """ This function calculates resistances at different socs and a specific pulse duration for a specified hppc cycle. Args: chosen(pd.DataFrame): a dataframe for a specific diagnostic cycle you are interested in. diag_pos (int): diagnostic cycle occurence for a specific <diagnostic_cycle_type>. e.g. if rpt_0.2C, occurs at cycle_index = [2, 37, 142, 244 ...], <diag_pos>=0 would correspond to cycle_index 2 soc (int): step index counter corresponding to the soc window of interest. step_ocv (int): 0 corresponds to the 1h-rest, and 2 corresponds to the 40s-rest. step_cur (int): 1 is for discharge, and 3 is for charge. index (float or str): this will input a time scale for resistance (unit is second), e.g. 0.01, 5 or 'last' which is the entire pulse duration. Returns: (a number) resistance at a specific soc in hppc cycles """ counters = [] if diag_pos == 0: steps = [11, 12, 13, 14, 15] else: steps = [43, 44, 45, 46, 47] for step in steps: counters.append(chosen[chosen.step_index == step].step_index_counter.unique().tolist()) if index == 'last': index = -1 else: start = chosen[(chosen.step_index_counter == counters[step_cur][soc])].diagnostic_time.min() stop = start + index / 3600 index = len(chosen[(chosen.step_index_counter == counters[step_cur][soc]) & (chosen.diagnostic_time > start) & ( chosen.diagnostic_time < stop)]) if len(counters[step_ocv]) < soc - 1: return None v_ocv = chosen[(chosen.step_index_counter == counters[step_ocv][soc])].voltage.iloc[-1] # i_ocv = chosen[(chosen.step_index_counter == counters[step_ocv][soc])].current.tail(5).mean() v_dis = chosen[(chosen.step_index_counter == counters[step_cur][soc])].voltage.iloc[index] i_dis = chosen[(chosen.step_index_counter == counters[step_cur][soc])].current.iloc[index] res = (v_dis - v_ocv) / i_dis return res
def res_calc(chosen, diag_pos, soc, step_ocv, step_cur, index): """ This function calculates resistances at different socs and a specific pulse duration for a specified hppc cycle. Args: chosen(pd.DataFrame): a dataframe for a specific diagnostic cycle you are interested in. diag_pos (int): diagnostic cycle occurence for a specific <diagnostic_cycle_type>. e.g. if rpt_0.2C, occurs at cycle_index = [2, 37, 142, 244 ...], <diag_pos>=0 would correspond to cycle_index 2 soc (int): step index counter corresponding to the soc window of interest. step_ocv (int): 0 corresponds to the 1h-rest, and 2 corresponds to the 40s-rest. step_cur (int): 1 is for discharge, and 3 is for charge. index (float or str): this will input a time scale for resistance (unit is second), e.g. 0.01, 5 or 'last' which is the entire pulse duration. Returns: (a number) resistance at a specific soc in hppc cycles """ counters = [] if diag_pos == 0: steps = [11, 12, 13, 14, 15] else: steps = [43, 44, 45, 46, 47] for step in steps: counters.append(chosen[chosen.step_index == step].step_index_counter.unique().tolist()) if index == 'last': index = -1 else: start = chosen[(chosen.step_index_counter == counters[step_cur][soc])].diagnostic_time.min() stop = start + index / 3600 index = len(chosen[(chosen.step_index_counter == counters[step_cur][soc]) & (chosen.diagnostic_time > start) & ( chosen.diagnostic_time < stop)]) if len(counters[step_ocv]) < soc - 1: return None v_ocv = chosen[(chosen.step_index_counter == counters[step_ocv][soc])].voltage.iloc[-1] # i_ocv = chosen[(chosen.step_index_counter == counters[step_ocv][soc])].current.tail(5).mean() v_dis = chosen[(chosen.step_index_counter == counters[step_cur][soc])].voltage.iloc[index] i_dis = chosen[(chosen.step_index_counter == counters[step_cur][soc])].current.iloc[index] res = (v_dis - v_ocv) / i_dis return res
Python
def d_curve_fitting(x, y): ''' This function fits given data x and y into a linear function. Argument: relevant data x and y. Returns: the slope of the curve. ''' def test(x, a, b): return a * x + b param, param_cov = curve_fit(test, x, y) a = param[0] ans = param[0] * (x) + param[1] return a
def d_curve_fitting(x, y): ''' This function fits given data x and y into a linear function. Argument: relevant data x and y. Returns: the slope of the curve. ''' def test(x, a, b): return a * x + b param, param_cov = curve_fit(test, x, y) a = param[0] ans = param[0] * (x) + param[1] return a
Python
def from_file(cls, filename, encoding='UTF-8'): """ Procedure file ingestion. Invokes Procedure object from standard Maccor xml file. Args: filename (str): xml procedure file. Returns: (Procedure): Ordered dictionary with keys corresponding to options or control variables. Section headers are nested dicts or lists within the dict. """ with open(filename, 'rb') as f: text = f.read().decode(encoding) data = xmltodict.parse(text, process_namespaces=False, strip_whitespace=True) return cls(data)
def from_file(cls, filename, encoding='UTF-8'): """ Procedure file ingestion. Invokes Procedure object from standard Maccor xml file. Args: filename (str): xml procedure file. Returns: (Procedure): Ordered dictionary with keys corresponding to options or control variables. Section headers are nested dicts or lists within the dict. """ with open(filename, 'rb') as f: text = f.read().decode(encoding) data = xmltodict.parse(text, process_namespaces=False, strip_whitespace=True) return cls(data)
Python
def _format_maccor(self): """ Dictionary reformatting of the entries in the procedure in order to match the maccor formats. Mainly re-adding whitespace to entries that were stripped on injestion. Returns: dict: Ordered dictionary with reformatted entries to match the formatting used in the maccor procedure files. """ formatted = deepcopy(self) for step in formatted['MaccorTestProcedure']['ProcSteps']['TestStep']: # print(json.dumps(step['StepType'], indent=2)) while len(step['StepType']) < 8: step['StepType'] = step['StepType'].center(8) if step['StepMode'] is None: step['StepMode'] = " " while len(step['StepMode']) < 8: step['StepMode'] = step['StepMode'].center(8) if step['Ends'] is not None: # If the Ends Element is a list we need to # check each entry in the list if isinstance(step['Ends']['EndEntry'], list): # print(json.dumps(step['Ends'], indent=2)) for end_entry in step['Ends']['EndEntry']: self.ends_whitespace(end_entry) if isinstance(step['Ends']['EndEntry'], dict): self.ends_whitespace(step['Ends']['EndEntry']) if step['Reports'] is not None: if isinstance(step['Reports']['ReportEntry'], list): for rep_entry in step['Reports']['ReportEntry']: self.reports_whitespace(rep_entry) if isinstance(step['Reports']['ReportEntry'], dict): self.reports_whitespace(step['Reports']['ReportEntry']) return formatted
def _format_maccor(self): """ Dictionary reformatting of the entries in the procedure in order to match the maccor formats. Mainly re-adding whitespace to entries that were stripped on injestion. Returns: dict: Ordered dictionary with reformatted entries to match the formatting used in the maccor procedure files. """ formatted = deepcopy(self) for step in formatted['MaccorTestProcedure']['ProcSteps']['TestStep']: # print(json.dumps(step['StepType'], indent=2)) while len(step['StepType']) < 8: step['StepType'] = step['StepType'].center(8) if step['StepMode'] is None: step['StepMode'] = " " while len(step['StepMode']) < 8: step['StepMode'] = step['StepMode'].center(8) if step['Ends'] is not None: # If the Ends Element is a list we need to # check each entry in the list if isinstance(step['Ends']['EndEntry'], list): # print(json.dumps(step['Ends'], indent=2)) for end_entry in step['Ends']['EndEntry']: self.ends_whitespace(end_entry) if isinstance(step['Ends']['EndEntry'], dict): self.ends_whitespace(step['Ends']['EndEntry']) if step['Reports'] is not None: if isinstance(step['Reports']['ReportEntry'], list): for rep_entry in step['Reports']['ReportEntry']: self.reports_whitespace(rep_entry) if isinstance(step['Reports']['ReportEntry'], dict): self.reports_whitespace(step['Reports']['ReportEntry']) return formatted
Python
def to_file(self, filename, encoding='UTF-8'): """ Writes object to maccor-formatted xml file using xmltodict unparse function. encoding (str): text encoding of output file Args: filename (str):file name to save xml to. """ formatted = self._format_maccor() contents = xmltodict.unparse( input_dict=formatted, output=None, encoding=encoding, short_empty_elements=False, pretty=True, newl="\n", indent=" ") # Manually inject processing instructions on line 2 line0, remainder = contents.split('\n', 1) line1 = "<?maccor-application progid=\"Maccor Procedure File\"?>" contents = "\n".join([line0, line1, remainder]) contents = self._fixup_empty_elements(contents) contents += "\n" with open(filename, 'w') as f: f.write(contents)
def to_file(self, filename, encoding='UTF-8'): """ Writes object to maccor-formatted xml file using xmltodict unparse function. encoding (str): text encoding of output file Args: filename (str):file name to save xml to. """ formatted = self._format_maccor() contents = xmltodict.unparse( input_dict=formatted, output=None, encoding=encoding, short_empty_elements=False, pretty=True, newl="\n", indent=" ") # Manually inject processing instructions on line 2 line0, remainder = contents.split('\n', 1) line1 = "<?maccor-application progid=\"Maccor Procedure File\"?>" contents = "\n".join([line0, line1, remainder]) contents = self._fixup_empty_elements(contents) contents += "\n" with open(filename, 'w') as f: f.write(contents)
Python
def _fixup_empty_elements(text): """ xml reformatting to match the empty elements that are used in the maccor procedure format. Writes directly back to the file and assumes that the empty elements to be replaced are all on a single line. Args: text (str): xml file raw text to be formatted """ text = text.replace(r"<Limits></Limits>", "<Limits/>") text = text.replace(r"<Reports></Reports>", "<Reports/>") text = text.replace(r"<Ends></Ends>", "<Ends/>") return text
def _fixup_empty_elements(text): """ xml reformatting to match the empty elements that are used in the maccor procedure format. Writes directly back to the file and assumes that the empty elements to be replaced are all on a single line. Args: text (str): xml file raw text to be formatted """ text = text.replace(r"<Limits></Limits>", "<Limits/>") text = text.replace(r"<Reports></Reports>", "<Reports/>") text = text.replace(r"<Ends></Ends>", "<Ends/>") return text
Python
def modify_step_value(self, step_num, step_type, step_value): """ Modifies the procedure parameters to set a step value at at given step num and type. Args: step_num (int): step id at which to set value step_type (str): step type at which to set value step_value (str): value to set Returns: dict: modified proc_dict with set value """ for step_idx, step in enumerate(self['MaccorTestProcedure']['ProcSteps']['TestStep']): if step_idx == step_num and step['StepType'] == step_type: step['StepValue'] = step_value return self
def modify_step_value(self, step_num, step_type, step_value): """ Modifies the procedure parameters to set a step value at at given step num and type. Args: step_num (int): step id at which to set value step_type (str): step type at which to set value step_value (str): value to set Returns: dict: modified proc_dict with set value """ for step_idx, step in enumerate(self['MaccorTestProcedure']['ProcSteps']['TestStep']): if step_idx == step_num and step['StepType'] == step_type: step['StepValue'] = step_value return self
Python
def from_exp(cls, cutoff_voltage, charge_rate, discharge_rate, template=None): """ Generates a procedure according to the EXP-style template. Args: cutoff_voltage (float): cutoff voltage for. charge_rate (float): charging C-rate in 1/h. discharge_rate (float): discharging C-rate in 1/h. template (str): template name, defaults to EXP in template dir Returns: (Procedure): dictionary of procedure parameters. """ # Load EXP template template = template or os.path.join(PROCEDURE_TEMPLATE_DIR, "EXP.000") obj = cls.from_file(template) # Modify according to params loop_idx_start, loop_idx_end = None, None for step_idx, step in enumerate(obj['MaccorTestProcedure']['ProcSteps']['TestStep']): if step['StepType'] == "Do 1": loop_idx_start = step_idx if step['StepType'] == "Loop 1": loop_idx_end = step_idx if loop_idx_start is None or loop_idx_end is None: raise UnboundLocalError("Loop index is not set") for step_idx, step in enumerate(obj['MaccorTestProcedure']['ProcSteps']['TestStep']): if step['StepType'] == 'Charge': if step['Limits'] is not None and 'Voltage' in step['Limits']: step['Limits']['Voltage'] = cutoff_voltage if step['StepMode'] == 'Current' and loop_idx_start < step_idx < loop_idx_end: step['StepValue'] = charge_rate if step['StepType'] == "Dischrge" and step['StepMode'] == 'Current' \ and loop_idx_start < step_idx < loop_idx_end: step['StepValue'] = discharge_rate return obj
def from_exp(cls, cutoff_voltage, charge_rate, discharge_rate, template=None): """ Generates a procedure according to the EXP-style template. Args: cutoff_voltage (float): cutoff voltage for. charge_rate (float): charging C-rate in 1/h. discharge_rate (float): discharging C-rate in 1/h. template (str): template name, defaults to EXP in template dir Returns: (Procedure): dictionary of procedure parameters. """ # Load EXP template template = template or os.path.join(PROCEDURE_TEMPLATE_DIR, "EXP.000") obj = cls.from_file(template) # Modify according to params loop_idx_start, loop_idx_end = None, None for step_idx, step in enumerate(obj['MaccorTestProcedure']['ProcSteps']['TestStep']): if step['StepType'] == "Do 1": loop_idx_start = step_idx if step['StepType'] == "Loop 1": loop_idx_end = step_idx if loop_idx_start is None or loop_idx_end is None: raise UnboundLocalError("Loop index is not set") for step_idx, step in enumerate(obj['MaccorTestProcedure']['ProcSteps']['TestStep']): if step['StepType'] == 'Charge': if step['Limits'] is not None and 'Voltage' in step['Limits']: step['Limits']['Voltage'] = cutoff_voltage if step['StepMode'] == 'Current' and loop_idx_start < step_idx < loop_idx_end: step['StepValue'] = charge_rate if step['StepType'] == "Dischrge" and step['StepMode'] == 'Current' \ and loop_idx_start < step_idx < loop_idx_end: step['StepValue'] = discharge_rate return obj
Python
def insert_maccor_waveform_discharge(self, waveform_idx, waveform_filename): """ Inserts a waveform into procedure dictionary at given id. Args: waveform_idx (int): Step in the procedure file to insert waveform at waveform_filename (str): Path to .MWF waveform file. Waveform needs to be pre-scaled for current/power capabilities of the cell and cycler """ steps = self['MaccorTestProcedure']['ProcSteps']['TestStep'] self.set('MaccorTestProcedure.ProcSteps.TestStep.{}.StepType'.format(waveform_idx), 'FastWave') self.set('MaccorTestProcedure.ProcSteps.TestStep.{}.StepMode'.format(waveform_idx), '') self.set('MaccorTestProcedure.ProcSteps.TestStep.{}.Ends'.format(waveform_idx), None) self.set('MaccorTestProcedure.ProcSteps.TestStep.{}.Reports'.format(waveform_idx), None) self.set('MaccorTestProcedure.ProcSteps.TestStep.{}.Range'.format(waveform_idx), '') self.set('MaccorTestProcedure.ProcSteps.TestStep.{}.Option1'.format(waveform_idx), '') self.set('MaccorTestProcedure.ProcSteps.TestStep.{}.Option2'.format(waveform_idx), '') self.set('MaccorTestProcedure.ProcSteps.TestStep.{}.Option3'.format(waveform_idx), '') assert steps[waveform_idx]['StepType'] == "FastWave" assert waveform_filename.split('.')[-1].lower() == 'mwf' local_name = waveform_filename.split('.')[0] _, local_name = os.path.split(local_name) assert len(local_name) < 25, str(len(local_name)) steps[waveform_idx]['StepValue'] = local_name return self
def insert_maccor_waveform_discharge(self, waveform_idx, waveform_filename): """ Inserts a waveform into procedure dictionary at given id. Args: waveform_idx (int): Step in the procedure file to insert waveform at waveform_filename (str): Path to .MWF waveform file. Waveform needs to be pre-scaled for current/power capabilities of the cell and cycler """ steps = self['MaccorTestProcedure']['ProcSteps']['TestStep'] self.set('MaccorTestProcedure.ProcSteps.TestStep.{}.StepType'.format(waveform_idx), 'FastWave') self.set('MaccorTestProcedure.ProcSteps.TestStep.{}.StepMode'.format(waveform_idx), '') self.set('MaccorTestProcedure.ProcSteps.TestStep.{}.Ends'.format(waveform_idx), None) self.set('MaccorTestProcedure.ProcSteps.TestStep.{}.Reports'.format(waveform_idx), None) self.set('MaccorTestProcedure.ProcSteps.TestStep.{}.Range'.format(waveform_idx), '') self.set('MaccorTestProcedure.ProcSteps.TestStep.{}.Option1'.format(waveform_idx), '') self.set('MaccorTestProcedure.ProcSteps.TestStep.{}.Option2'.format(waveform_idx), '') self.set('MaccorTestProcedure.ProcSteps.TestStep.{}.Option3'.format(waveform_idx), '') assert steps[waveform_idx]['StepType'] == "FastWave" assert waveform_filename.split('.')[-1].lower() == 'mwf' local_name = waveform_filename.split('.')[0] _, local_name = os.path.split(local_name) assert len(local_name) < 25, str(len(local_name)) steps[waveform_idx]['StepValue'] = local_name return self
Python
def insert_resistance_regcyclev2(self, resist_idx, reg_param): """ Inserts resistance into procedure dictionary at given id. Args: resist_idx (int): reg_param (pandas.DataFrame): Returns: dict: """ steps = self['MaccorTestProcedure']['ProcSteps']['TestStep'] # Initial resistance check assert steps[resist_idx]['StepType'] == "Charge" assert steps[resist_idx]['StepMode'] == "Current" steps[resist_idx]['StepValue'] = float(round(1.0 * reg_param['capacity_nominal'], 3)) return self
def insert_resistance_regcyclev2(self, resist_idx, reg_param): """ Inserts resistance into procedure dictionary at given id. Args: resist_idx (int): reg_param (pandas.DataFrame): Returns: dict: """ steps = self['MaccorTestProcedure']['ProcSteps']['TestStep'] # Initial resistance check assert steps[resist_idx]['StepType'] == "Charge" assert steps[resist_idx]['StepMode'] == "Current" steps[resist_idx]['StepValue'] = float(round(1.0 * reg_param['capacity_nominal'], 3)) return self
Python
def insert_charge_regcyclev2(self, charge_idx, reg_param): """ Inserts charge into procedure dictionary at given id. Args: charge_idx (int) reg_param (pandas.DataFrame): Returns: dict: """ steps = self['MaccorTestProcedure']['ProcSteps']['TestStep'] # Regular cycle constant current charge part 1 step_idx = charge_idx assert steps[step_idx]['StepType'] == "Charge" assert steps[step_idx]['StepMode'] == "Current" steps[step_idx]['StepValue'] = float(round(reg_param['charge_constant_current_1'] * reg_param['capacity_nominal'], 3)) assert steps[step_idx]['Ends']['EndEntry'][0]['EndType'] == "StepTime" time_s = int(round(3600 * (reg_param['charge_percent_limit_1'] / 100) / reg_param['charge_constant_current_1'])) steps[step_idx]['Ends']['EndEntry'][0]['Value'] = time.strftime( '%H:%M:%S', time.gmtime(time_s)) # Regular cycle constant current charge part 2 step_idx = charge_idx + 1 assert steps[step_idx]['StepType'] == "Charge" assert steps[step_idx]['StepMode'] == "Current" steps[step_idx]['StepValue'] = float(round(reg_param['charge_constant_current_2'] * reg_param['capacity_nominal'], 3)) assert steps[step_idx]['Ends']['EndEntry'][0]['EndType'] == "Voltage" steps[step_idx]['Ends']['EndEntry'][0]['Value'] = float(round(reg_param['charge_cutoff_voltage'], 3)) # Regular cycle constant voltage hold step_idx = charge_idx + 2 assert steps[step_idx]['StepType'] == "Charge" assert steps[step_idx]['StepMode'] == "Voltage" steps[step_idx]['StepValue'] = reg_param['charge_cutoff_voltage'] assert steps[step_idx]['Ends']['EndEntry'][0]['EndType'] == "StepTime" time_s = int(round(60 * reg_param['charge_constant_voltage_time'])) steps[step_idx]['Ends']['EndEntry'][0]['Value'] = time.strftime('%H:%M:%S', time.gmtime(time_s)) # Regular cycle rest at top of charge step_idx = charge_idx + 3 assert steps[step_idx]['StepType'] == "Rest" assert steps[step_idx]['Ends']['EndEntry'][0]['EndType'] == "StepTime" time_s = int(round(60 * reg_param['charge_rest_time'])) steps[step_idx]['Ends']['EndEntry'][0]['Value'] = time.strftime('%H:%M:%S', time.gmtime(time_s)) return self
def insert_charge_regcyclev2(self, charge_idx, reg_param): """ Inserts charge into procedure dictionary at given id. Args: charge_idx (int) reg_param (pandas.DataFrame): Returns: dict: """ steps = self['MaccorTestProcedure']['ProcSteps']['TestStep'] # Regular cycle constant current charge part 1 step_idx = charge_idx assert steps[step_idx]['StepType'] == "Charge" assert steps[step_idx]['StepMode'] == "Current" steps[step_idx]['StepValue'] = float(round(reg_param['charge_constant_current_1'] * reg_param['capacity_nominal'], 3)) assert steps[step_idx]['Ends']['EndEntry'][0]['EndType'] == "StepTime" time_s = int(round(3600 * (reg_param['charge_percent_limit_1'] / 100) / reg_param['charge_constant_current_1'])) steps[step_idx]['Ends']['EndEntry'][0]['Value'] = time.strftime( '%H:%M:%S', time.gmtime(time_s)) # Regular cycle constant current charge part 2 step_idx = charge_idx + 1 assert steps[step_idx]['StepType'] == "Charge" assert steps[step_idx]['StepMode'] == "Current" steps[step_idx]['StepValue'] = float(round(reg_param['charge_constant_current_2'] * reg_param['capacity_nominal'], 3)) assert steps[step_idx]['Ends']['EndEntry'][0]['EndType'] == "Voltage" steps[step_idx]['Ends']['EndEntry'][0]['Value'] = float(round(reg_param['charge_cutoff_voltage'], 3)) # Regular cycle constant voltage hold step_idx = charge_idx + 2 assert steps[step_idx]['StepType'] == "Charge" assert steps[step_idx]['StepMode'] == "Voltage" steps[step_idx]['StepValue'] = reg_param['charge_cutoff_voltage'] assert steps[step_idx]['Ends']['EndEntry'][0]['EndType'] == "StepTime" time_s = int(round(60 * reg_param['charge_constant_voltage_time'])) steps[step_idx]['Ends']['EndEntry'][0]['Value'] = time.strftime('%H:%M:%S', time.gmtime(time_s)) # Regular cycle rest at top of charge step_idx = charge_idx + 3 assert steps[step_idx]['StepType'] == "Rest" assert steps[step_idx]['Ends']['EndEntry'][0]['EndType'] == "StepTime" time_s = int(round(60 * reg_param['charge_rest_time'])) steps[step_idx]['Ends']['EndEntry'][0]['Value'] = time.strftime('%H:%M:%S', time.gmtime(time_s)) return self
Python
def insert_discharge_regcyclev2(self, discharge_idx, reg_param): """ Inserts discharge into procedure dictionary at given id. Args: discharge_idx (int): reg_param (pandas.DataFrame): Returns: dict: """ steps = self['MaccorTestProcedure']['ProcSteps']['TestStep'] # Regular cycle constant current discharge part 1 step_idx = discharge_idx assert steps[step_idx]['StepType'] == "Dischrge" assert steps[step_idx]['StepMode'] == "Current" steps[step_idx]['StepValue'] = float(round(reg_param['discharge_constant_current'] * reg_param['capacity_nominal'], 3)) assert steps[step_idx]['Ends']['EndEntry'][0]['EndType'] == "Voltage" steps[step_idx]['Ends']['EndEntry'][0]['Value'] = float(round(reg_param['discharge_cutoff_voltage'], 3)) # Regular cycle rest after discharge step_idx = discharge_idx + 1 assert steps[step_idx]['StepType'] == "Rest" assert steps[step_idx]['Ends']['EndEntry'][0]['EndType'] == "StepTime" time_s = int(round(60 * reg_param['discharge_rest_time'])) steps[step_idx]['Ends']['EndEntry'][0]['Value'] = time.strftime('%H:%M:%S', time.gmtime(time_s)) # Regular cycle number of times to repeat regular cycle for initial offset and main body step_idx = discharge_idx + 3 assert steps[step_idx]['StepType'][0:4] == "Loop" if steps[step_idx]['StepType'] == "Loop 1": assert steps[step_idx]['Ends']['EndEntry']['EndType'] == "Loop Cnt" steps[step_idx]['Ends']['EndEntry']['Value'] = reg_param['diagnostic_start_cycle'] elif steps[step_idx]['StepType'] == "Loop 2": assert steps[step_idx]['Ends']['EndEntry']['EndType'] == "Loop Cnt" steps[step_idx]['Ends']['EndEntry']['Value'] = reg_param['diagnostic_interval'] return self
def insert_discharge_regcyclev2(self, discharge_idx, reg_param): """ Inserts discharge into procedure dictionary at given id. Args: discharge_idx (int): reg_param (pandas.DataFrame): Returns: dict: """ steps = self['MaccorTestProcedure']['ProcSteps']['TestStep'] # Regular cycle constant current discharge part 1 step_idx = discharge_idx assert steps[step_idx]['StepType'] == "Dischrge" assert steps[step_idx]['StepMode'] == "Current" steps[step_idx]['StepValue'] = float(round(reg_param['discharge_constant_current'] * reg_param['capacity_nominal'], 3)) assert steps[step_idx]['Ends']['EndEntry'][0]['EndType'] == "Voltage" steps[step_idx]['Ends']['EndEntry'][0]['Value'] = float(round(reg_param['discharge_cutoff_voltage'], 3)) # Regular cycle rest after discharge step_idx = discharge_idx + 1 assert steps[step_idx]['StepType'] == "Rest" assert steps[step_idx]['Ends']['EndEntry'][0]['EndType'] == "StepTime" time_s = int(round(60 * reg_param['discharge_rest_time'])) steps[step_idx]['Ends']['EndEntry'][0]['Value'] = time.strftime('%H:%M:%S', time.gmtime(time_s)) # Regular cycle number of times to repeat regular cycle for initial offset and main body step_idx = discharge_idx + 3 assert steps[step_idx]['StepType'][0:4] == "Loop" if steps[step_idx]['StepType'] == "Loop 1": assert steps[step_idx]['Ends']['EndEntry']['EndType'] == "Loop Cnt" steps[step_idx]['Ends']['EndEntry']['Value'] = reg_param['diagnostic_start_cycle'] elif steps[step_idx]['StepType'] == "Loop 2": assert steps[step_idx]['Ends']['EndEntry']['EndType'] == "Loop Cnt" steps[step_idx]['Ends']['EndEntry']['Value'] = reg_param['diagnostic_interval'] return self
Python
def insert_storage_regcyclev2(self, storage_idx, reg_param): """ Inserts storage into procedure dictionary at given id. Args: storage_idx (int): reg_param (pandas.DataFrame): Returns: dict: """ steps = self['MaccorTestProcedure']['ProcSteps']['TestStep'] # Storage condition step_idx = storage_idx assert steps[step_idx]['StepType'] == "Dischrge" assert steps[step_idx]['StepMode'] == "Current" steps[step_idx]['StepValue'] = float(round(0.5 * reg_param['capacity_nominal'], 3)) steps[step_idx]['Limits']['Voltage'] = float(round(reg_param['discharge_cutoff_voltage'], 3)) assert steps[step_idx]['Ends']['EndEntry']['EndType'] == "Current" steps[step_idx]['Ends']['EndEntry']['Value'] = float(round(0.05 * reg_param['capacity_nominal'], 3)) step_idx = storage_idx + 1 assert steps[step_idx]['StepType'] == "Charge" assert steps[step_idx]['StepMode'] == "Current" steps[step_idx]['StepValue'] = float(round(0.5 * reg_param['capacity_nominal'], 3)) assert steps[step_idx]['Ends']['EndEntry'][0]['EndType'] == "StepTime" time_s = int(round(60 * 12)) steps[step_idx]['Ends']['EndEntry'][0]['Value'] = time.strftime('%H:%M:%S', time.gmtime(time_s)) return self
def insert_storage_regcyclev2(self, storage_idx, reg_param): """ Inserts storage into procedure dictionary at given id. Args: storage_idx (int): reg_param (pandas.DataFrame): Returns: dict: """ steps = self['MaccorTestProcedure']['ProcSteps']['TestStep'] # Storage condition step_idx = storage_idx assert steps[step_idx]['StepType'] == "Dischrge" assert steps[step_idx]['StepMode'] == "Current" steps[step_idx]['StepValue'] = float(round(0.5 * reg_param['capacity_nominal'], 3)) steps[step_idx]['Limits']['Voltage'] = float(round(reg_param['discharge_cutoff_voltage'], 3)) assert steps[step_idx]['Ends']['EndEntry']['EndType'] == "Current" steps[step_idx]['Ends']['EndEntry']['Value'] = float(round(0.05 * reg_param['capacity_nominal'], 3)) step_idx = storage_idx + 1 assert steps[step_idx]['StepType'] == "Charge" assert steps[step_idx]['StepMode'] == "Current" steps[step_idx]['StepValue'] = float(round(0.5 * reg_param['capacity_nominal'], 3)) assert steps[step_idx]['Ends']['EndEntry'][0]['EndType'] == "StepTime" time_s = int(round(60 * 12)) steps[step_idx]['Ends']['EndEntry'][0]['Value'] = time.strftime('%H:%M:%S', time.gmtime(time_s)) return self
Python
def insert_initialrest_regcyclev3(self, rest_idx, index): """ Inserts initial rest into procedure dictionary at given id. Args: rest_idx (int): index (int): Returns: dict: """ steps = self['MaccorTestProcedure']['ProcSteps']['TestStep'] # Initial rest offset_seconds = 720 assert steps[rest_idx]['StepType'] == "Rest" assert steps[rest_idx]['Ends']['EndEntry'][0]['EndType'] == "StepTime" time_s = int(round(3 * 3600 + offset_seconds * (index % 96))) steps[rest_idx]['Ends']['EndEntry'][0]['Value'] = time.strftime('%H:%M:%S', time.gmtime(time_s)) return self
def insert_initialrest_regcyclev3(self, rest_idx, index): """ Inserts initial rest into procedure dictionary at given id. Args: rest_idx (int): index (int): Returns: dict: """ steps = self['MaccorTestProcedure']['ProcSteps']['TestStep'] # Initial rest offset_seconds = 720 assert steps[rest_idx]['StepType'] == "Rest" assert steps[rest_idx]['Ends']['EndEntry'][0]['EndType'] == "StepTime" time_s = int(round(3 * 3600 + offset_seconds * (index % 96))) steps[rest_idx]['Ends']['EndEntry'][0]['Value'] = time.strftime('%H:%M:%S', time.gmtime(time_s)) return self
Python
def insert_charge_regcyclev3(self, charge_idx, reg_param): """ Inserts charge into procedure dictionary at given id. Args: charge_idx (int): reg_param (pandas.DataFrame): Returns: dict: """ steps = self['MaccorTestProcedure']['ProcSteps']['TestStep'] # Regular cycle constant current charge part 1 step_idx = charge_idx assert steps[step_idx]['StepType'] == "Charge" assert steps[step_idx]['StepMode'] == "Current" steps[step_idx]['StepValue'] = float(round(reg_param['charge_constant_current_1'] * reg_param['capacity_nominal'], 3)) assert steps[step_idx]['Ends']['EndEntry'][0]['EndType'] == "StepTime" time_s = int(round(3600 * (reg_param['charge_percent_limit_1'] / 100) / reg_param['charge_constant_current_1'])) steps[step_idx]['Ends']['EndEntry'][0]['Value'] = time.strftime('%H:%M:%S', time.gmtime(time_s)) assert steps[step_idx]['Ends']['EndEntry'][1]['Value'] != 4.4 steps[step_idx]['Ends']['EndEntry'][1]['Value'] = float(round(reg_param['charge_cutoff_voltage'], 3)) # Regular cycle constant current charge part 2 step_idx = charge_idx + 1 assert steps[step_idx]['StepType'] == "Charge" assert steps[step_idx]['StepMode'] == "Current" steps[step_idx]['StepValue'] = float(round(reg_param['charge_constant_current_2'] * reg_param['capacity_nominal'], 3)) assert steps[step_idx]['Ends']['EndEntry'][0]['EndType'] == "Voltage" steps[step_idx]['Ends']['EndEntry'][0]['Value'] = float(round(reg_param['charge_cutoff_voltage'], 3)) # Regular cycle constant voltage hold step_idx = charge_idx + 2 assert steps[step_idx]['StepType'] == "Charge" assert steps[step_idx]['StepMode'] == "Voltage" steps[step_idx]['StepValue'] = reg_param['charge_cutoff_voltage'] assert steps[step_idx]['Ends']['EndEntry'][0]['EndType'] == "StepTime" time_s = int(round(60 * reg_param['charge_constant_voltage_time'])) steps[step_idx]['Ends']['EndEntry'][0]['Value'] = time.strftime('%H:%M:%S', time.gmtime(time_s)) # Regular cycle rest at top of charge step_idx = charge_idx + 3 assert steps[step_idx]['StepType'] == "Rest" assert steps[step_idx]['Ends']['EndEntry'][0]['EndType'] == "StepTime" time_s = int(round(60 * reg_param['charge_rest_time'])) steps[step_idx]['Ends']['EndEntry'][0]['Value'] = time.strftime('%H:%M:%S', time.gmtime(time_s)) return self
def insert_charge_regcyclev3(self, charge_idx, reg_param): """ Inserts charge into procedure dictionary at given id. Args: charge_idx (int): reg_param (pandas.DataFrame): Returns: dict: """ steps = self['MaccorTestProcedure']['ProcSteps']['TestStep'] # Regular cycle constant current charge part 1 step_idx = charge_idx assert steps[step_idx]['StepType'] == "Charge" assert steps[step_idx]['StepMode'] == "Current" steps[step_idx]['StepValue'] = float(round(reg_param['charge_constant_current_1'] * reg_param['capacity_nominal'], 3)) assert steps[step_idx]['Ends']['EndEntry'][0]['EndType'] == "StepTime" time_s = int(round(3600 * (reg_param['charge_percent_limit_1'] / 100) / reg_param['charge_constant_current_1'])) steps[step_idx]['Ends']['EndEntry'][0]['Value'] = time.strftime('%H:%M:%S', time.gmtime(time_s)) assert steps[step_idx]['Ends']['EndEntry'][1]['Value'] != 4.4 steps[step_idx]['Ends']['EndEntry'][1]['Value'] = float(round(reg_param['charge_cutoff_voltage'], 3)) # Regular cycle constant current charge part 2 step_idx = charge_idx + 1 assert steps[step_idx]['StepType'] == "Charge" assert steps[step_idx]['StepMode'] == "Current" steps[step_idx]['StepValue'] = float(round(reg_param['charge_constant_current_2'] * reg_param['capacity_nominal'], 3)) assert steps[step_idx]['Ends']['EndEntry'][0]['EndType'] == "Voltage" steps[step_idx]['Ends']['EndEntry'][0]['Value'] = float(round(reg_param['charge_cutoff_voltage'], 3)) # Regular cycle constant voltage hold step_idx = charge_idx + 2 assert steps[step_idx]['StepType'] == "Charge" assert steps[step_idx]['StepMode'] == "Voltage" steps[step_idx]['StepValue'] = reg_param['charge_cutoff_voltage'] assert steps[step_idx]['Ends']['EndEntry'][0]['EndType'] == "StepTime" time_s = int(round(60 * reg_param['charge_constant_voltage_time'])) steps[step_idx]['Ends']['EndEntry'][0]['Value'] = time.strftime('%H:%M:%S', time.gmtime(time_s)) # Regular cycle rest at top of charge step_idx = charge_idx + 3 assert steps[step_idx]['StepType'] == "Rest" assert steps[step_idx]['Ends']['EndEntry'][0]['EndType'] == "StepTime" time_s = int(round(60 * reg_param['charge_rest_time'])) steps[step_idx]['Ends']['EndEntry'][0]['Value'] = time.strftime('%H:%M:%S', time.gmtime(time_s)) return self
Python
def insert_storage_regcyclev3(self, storage_idx, reg_param): """ Inserts storage into procedure dictionary at given id. Args: self (dict): storage_idx (int): reg_param (pandas.DataFrame): Returns: dict: """ steps = self['MaccorTestProcedure']['ProcSteps']['TestStep'] # Storage condition step_idx = storage_idx assert steps[step_idx]['StepType'] == "Dischrge" assert steps[step_idx]['StepMode'] == "Current" steps[step_idx]['StepValue'] = float(round(0.5 * reg_param['capacity_nominal'], 3)) steps[step_idx]['Limits']['Voltage'] = float(round(reg_param['discharge_cutoff_voltage'], 3)) assert steps[step_idx]['Ends']['EndEntry'][0]['EndType'] == "Current" steps[step_idx]['Ends']['EndEntry'][0]['Value'] = float(round(0.05 * reg_param['capacity_nominal'], 3)) step_idx = storage_idx + 1 assert steps[step_idx]['StepType'] == "Charge" assert steps[step_idx]['StepMode'] == "Current" steps[step_idx]['StepValue'] = float(round(0.5 * reg_param['capacity_nominal'], 3)) assert steps[step_idx]['Ends']['EndEntry'][0]['EndType'] == "StepTime" time_s = int(round(60 * 12)) steps[step_idx]['Ends']['EndEntry'][0]['Value'] = time.strftime('%H:%M:%S', time.gmtime(time_s)) return self
def insert_storage_regcyclev3(self, storage_idx, reg_param): """ Inserts storage into procedure dictionary at given id. Args: self (dict): storage_idx (int): reg_param (pandas.DataFrame): Returns: dict: """ steps = self['MaccorTestProcedure']['ProcSteps']['TestStep'] # Storage condition step_idx = storage_idx assert steps[step_idx]['StepType'] == "Dischrge" assert steps[step_idx]['StepMode'] == "Current" steps[step_idx]['StepValue'] = float(round(0.5 * reg_param['capacity_nominal'], 3)) steps[step_idx]['Limits']['Voltage'] = float(round(reg_param['discharge_cutoff_voltage'], 3)) assert steps[step_idx]['Ends']['EndEntry'][0]['EndType'] == "Current" steps[step_idx]['Ends']['EndEntry'][0]['Value'] = float(round(0.05 * reg_param['capacity_nominal'], 3)) step_idx = storage_idx + 1 assert steps[step_idx]['StepType'] == "Charge" assert steps[step_idx]['StepMode'] == "Current" steps[step_idx]['StepValue'] = float(round(0.5 * reg_param['capacity_nominal'], 3)) assert steps[step_idx]['Ends']['EndEntry'][0]['EndType'] == "StepTime" time_s = int(round(60 * 12)) steps[step_idx]['Ends']['EndEntry'][0]['Value'] = time.strftime('%H:%M:%S', time.gmtime(time_s)) return self
Python
def add_procedure_diagcyclev2(self, nominal_capacity, diagnostic_params): """ Modifies a procedure according to the diagnosticV2 template. Args: nominal_capacity (float): Standard capacity for this cell. diagnostic_params (pandas.Series): Series containing all of the diagnostic parameters. Returns: (dict) dictionary of procedure parameters. """ start_reset_cycle_1 = 4 self.insert_reset_cyclev2(start_reset_cycle_1, nominal_capacity, diagnostic_params) start_hppc_cycle_1 = 8 self.insert_hppc_cyclev2(start_hppc_cycle_1, nominal_capacity, diagnostic_params) start_rpt_cycle_1 = 18 self.insert_rpt_cyclev2(start_rpt_cycle_1, nominal_capacity, diagnostic_params) start_reset_cycle_2 = 37 self.insert_reset_cyclev2(start_reset_cycle_2, nominal_capacity, diagnostic_params) start_hppc_cycle_2 = 40 self.insert_hppc_cyclev2(start_hppc_cycle_2, nominal_capacity, diagnostic_params) start_rpt_cycle_2 = 50 self.insert_rpt_cyclev2(start_rpt_cycle_2, nominal_capacity, diagnostic_params) return self
def add_procedure_diagcyclev2(self, nominal_capacity, diagnostic_params): """ Modifies a procedure according to the diagnosticV2 template. Args: nominal_capacity (float): Standard capacity for this cell. diagnostic_params (pandas.Series): Series containing all of the diagnostic parameters. Returns: (dict) dictionary of procedure parameters. """ start_reset_cycle_1 = 4 self.insert_reset_cyclev2(start_reset_cycle_1, nominal_capacity, diagnostic_params) start_hppc_cycle_1 = 8 self.insert_hppc_cyclev2(start_hppc_cycle_1, nominal_capacity, diagnostic_params) start_rpt_cycle_1 = 18 self.insert_rpt_cyclev2(start_rpt_cycle_1, nominal_capacity, diagnostic_params) start_reset_cycle_2 = 37 self.insert_reset_cyclev2(start_reset_cycle_2, nominal_capacity, diagnostic_params) start_hppc_cycle_2 = 40 self.insert_hppc_cyclev2(start_hppc_cycle_2, nominal_capacity, diagnostic_params) start_rpt_cycle_2 = 50 self.insert_rpt_cyclev2(start_rpt_cycle_2, nominal_capacity, diagnostic_params) return self
Python
def generate_procedure_diagcyclev3(self, nominal_capacity, diagnostic_params): """ Generates a diagnostic procedure according to the diagnosticV3 template. Args: nominal_capacity (float): Standard capacity for this cell. diagnostic_params (pandas.Series): Series containing all of the diagnostic parameters. Returns: dict: dictionary of procedure parameters. """ start_reset_cycle_1 = 4 self.insert_reset_cyclev2(start_reset_cycle_1, nominal_capacity, diagnostic_params) start_hppc_cycle_1 = 8 self.insert_hppc_cyclev2(start_hppc_cycle_1, nominal_capacity, diagnostic_params) start_rpt_cycle_1 = 18 self.insert_rpt_cyclev2(start_rpt_cycle_1, nominal_capacity, diagnostic_params) start_reset_cycle_2 = 37 self.insert_reset_cyclev2(start_reset_cycle_2, nominal_capacity, diagnostic_params) start_hppc_cycle_2 = 40 self.insert_hppc_cyclev2(start_hppc_cycle_2, nominal_capacity, diagnostic_params) start_rpt_cycle_2 = 50 self.insert_rpt_cyclev2(start_rpt_cycle_2, nominal_capacity, diagnostic_params) start_reset_cycle_3 = 70 self.insert_reset_cyclev2(start_reset_cycle_3, nominal_capacity, diagnostic_params) start_hppc_cycle_3 = 74 self.insert_hppc_cyclev2(start_hppc_cycle_3, nominal_capacity, diagnostic_params) start_rpt_cycle_3 = 84 self.insert_rpt_cyclev2(start_rpt_cycle_3, nominal_capacity, diagnostic_params) return self
def generate_procedure_diagcyclev3(self, nominal_capacity, diagnostic_params): """ Generates a diagnostic procedure according to the diagnosticV3 template. Args: nominal_capacity (float): Standard capacity for this cell. diagnostic_params (pandas.Series): Series containing all of the diagnostic parameters. Returns: dict: dictionary of procedure parameters. """ start_reset_cycle_1 = 4 self.insert_reset_cyclev2(start_reset_cycle_1, nominal_capacity, diagnostic_params) start_hppc_cycle_1 = 8 self.insert_hppc_cyclev2(start_hppc_cycle_1, nominal_capacity, diagnostic_params) start_rpt_cycle_1 = 18 self.insert_rpt_cyclev2(start_rpt_cycle_1, nominal_capacity, diagnostic_params) start_reset_cycle_2 = 37 self.insert_reset_cyclev2(start_reset_cycle_2, nominal_capacity, diagnostic_params) start_hppc_cycle_2 = 40 self.insert_hppc_cyclev2(start_hppc_cycle_2, nominal_capacity, diagnostic_params) start_rpt_cycle_2 = 50 self.insert_rpt_cyclev2(start_rpt_cycle_2, nominal_capacity, diagnostic_params) start_reset_cycle_3 = 70 self.insert_reset_cyclev2(start_reset_cycle_3, nominal_capacity, diagnostic_params) start_hppc_cycle_3 = 74 self.insert_hppc_cyclev2(start_hppc_cycle_3, nominal_capacity, diagnostic_params) start_rpt_cycle_3 = 84 self.insert_rpt_cyclev2(start_rpt_cycle_3, nominal_capacity, diagnostic_params) return self
Python
def insert_reset_cyclev2(self, start, nominal_capacity, diagnostic_params): """ Helper function for parameterizing the reset cycle. Args: start: nominal_capacity: diagnostic_params: Returns: dict: """ steps = self['MaccorTestProcedure']['ProcSteps']['TestStep'] # Charge step for reset cycle assert steps[start]['StepType'] == 'Charge' assert steps[start]['StepMode'] == 'Current' steps[start]['StepValue'] = float(round(nominal_capacity * diagnostic_params['reset_cycle_current'], 4)) steps[start]['Limits']['Voltage'] = float(round(diagnostic_params['diagnostic_charge_cutoff_voltage'], 3)) assert steps[start]['Ends']['EndEntry'][0]['EndType'] == 'Current' steps[start]['Ends']['EndEntry'][0]['Value'] = float(round(nominal_capacity * diagnostic_params['reset_cycle_cutoff_current'], 4)) # Discharge step for reset cycle assert steps[start+1]['StepType'] == 'Dischrge' assert steps[start+1]['StepMode'] == 'Current' steps[start+1]['StepValue'] = float(round(nominal_capacity * diagnostic_params['reset_cycle_current'], 4)) assert steps[start+1]['Ends']['EndEntry'][0]['EndType'] == 'Voltage' steps[start+1]['Ends']['EndEntry'][0]['Value'] = \ float(round(diagnostic_params['diagnostic_discharge_cutoff_voltage'], 3)) return self
def insert_reset_cyclev2(self, start, nominal_capacity, diagnostic_params): """ Helper function for parameterizing the reset cycle. Args: start: nominal_capacity: diagnostic_params: Returns: dict: """ steps = self['MaccorTestProcedure']['ProcSteps']['TestStep'] # Charge step for reset cycle assert steps[start]['StepType'] == 'Charge' assert steps[start]['StepMode'] == 'Current' steps[start]['StepValue'] = float(round(nominal_capacity * diagnostic_params['reset_cycle_current'], 4)) steps[start]['Limits']['Voltage'] = float(round(diagnostic_params['diagnostic_charge_cutoff_voltage'], 3)) assert steps[start]['Ends']['EndEntry'][0]['EndType'] == 'Current' steps[start]['Ends']['EndEntry'][0]['Value'] = float(round(nominal_capacity * diagnostic_params['reset_cycle_cutoff_current'], 4)) # Discharge step for reset cycle assert steps[start+1]['StepType'] == 'Dischrge' assert steps[start+1]['StepMode'] == 'Current' steps[start+1]['StepValue'] = float(round(nominal_capacity * diagnostic_params['reset_cycle_current'], 4)) assert steps[start+1]['Ends']['EndEntry'][0]['EndType'] == 'Voltage' steps[start+1]['Ends']['EndEntry'][0]['Value'] = \ float(round(diagnostic_params['diagnostic_discharge_cutoff_voltage'], 3)) return self
Python
def insert_hppc_cyclev2(self, start, nominal_capacity, diagnostic_params): """ Helper function for parameterizing the hybrid pulse power cycle Args: start: nominal_capacity: diagnostic_params: Returns: dict: """ steps = self['MaccorTestProcedure']['ProcSteps']['TestStep'] # Initial charge step for hppc cycle assert steps[start]['StepType'] == 'Charge' assert steps[start]['StepMode'] == 'Current' steps[start]['StepValue'] = float(round(nominal_capacity * diagnostic_params['HPPC_baseline_constant_current'], 3)) steps[start]['Limits']['Voltage'] = float(round(diagnostic_params['diagnostic_charge_cutoff_voltage'], 3)) assert steps[start]['Ends']['EndEntry'][0]['EndType'] == 'Current' steps[start]['Ends']['EndEntry'][0]['Value'] = float(round(nominal_capacity * diagnostic_params['diagnostic_cutoff_current'], 3)) # Rest step for hppc cycle assert steps[start+2]['StepType'] == 'Rest' assert steps[start+2]['Ends']['EndEntry'][0]['EndType'] == 'StepTime' time_s = int(round(60 * diagnostic_params['HPPC_rest_time'])) steps[start+2]['Ends']['EndEntry'][0]['Value'] = time.strftime('%H:%M:%S', time.gmtime(time_s)) # Discharge step 1 for hppc cycle assert steps[start+3]['StepType'] == 'Dischrge' assert steps[start+3]['StepMode'] == 'Current' steps[start+3]['StepValue'] = float(round(nominal_capacity * diagnostic_params['HPPC_pulse_current_1'], 3)) assert steps[start+3]['Ends']['EndEntry'][0]['EndType'] == 'StepTime' time_s = diagnostic_params['HPPC_pulse_duration_1'] steps[start+3]['Ends']['EndEntry'][0]['Value'] = time.strftime('%H:%M:%S', time.gmtime(time_s)) assert steps[start+3]['Ends']['EndEntry'][1]['EndType'] == 'Voltage' steps[start+3]['Ends']['EndEntry'][1]['Value'] = \ float(round(diagnostic_params['diagnostic_discharge_cutoff_voltage'], 3)) # Pulse rest step for hppc cycle assert steps[start+4]['StepType'] == 'Rest' assert steps[start+4]['Ends']['EndEntry'][0]['EndType'] == 'StepTime' time_s = int(round(diagnostic_params['HPPC_pulse_rest_time'])) steps[start+4]['Ends']['EndEntry'][0]['Value'] = time.strftime('%H:%M:%S', time.gmtime(time_s)) # Charge step 1 for hppc cycle assert steps[start+5]['StepType'] == 'Charge' assert steps[start+5]['StepMode'] == 'Current' steps[start+5]['StepValue'] = float(round(nominal_capacity * diagnostic_params['HPPC_pulse_current_2'], 3)) assert steps[start+5]['Ends']['EndEntry'][0]['EndType'] == 'StepTime' time_s = diagnostic_params['HPPC_pulse_duration_2'] steps[start+5]['Ends']['EndEntry'][0]['Value'] = time.strftime('%H:%M:%S', time.gmtime(time_s)) assert steps[start+5]['Ends']['EndEntry'][1]['EndType'] == 'Voltage' steps[start+5]['Ends']['EndEntry'][1]['Value'] = \ float(round(diagnostic_params['HPPC_pulse_cutoff_voltage'], 3)) # Discharge step 2 for hppc cycle assert steps[start+6]['StepType'] == 'Dischrge' assert steps[start+6]['StepMode'] == 'Current' steps[start+6]['StepValue'] = float(round(nominal_capacity * diagnostic_params['HPPC_baseline_constant_current'], 3)) assert steps[start+6]['Ends']['EndEntry'][0]['EndType'] == 'StepTime' time_s = int(round(3600 * (diagnostic_params['HPPC_interval'] / 100) / diagnostic_params['HPPC_baseline_constant_current'] - 1)) steps[start+6]['Ends']['EndEntry'][0]['Value'] = time.strftime('%H:%M:%S', time.gmtime(time_s)) assert steps[start+6]['Ends']['EndEntry'][1]['EndType'] == 'Voltage' steps[start+6]['Ends']['EndEntry'][1]['Value'] = \ float(round(diagnostic_params['diagnostic_discharge_cutoff_voltage'], 3)) # Final discharge step for hppc cycle assert steps[start+8]['StepType'] == 'Dischrge' assert steps[start+8]['StepMode'] == 'Voltage' steps[start+8]['StepValue'] = float(round(diagnostic_params['diagnostic_discharge_cutoff_voltage'], 3)) steps[start+8]['Limits']['Current'] = float(round(nominal_capacity * diagnostic_params['HPPC_baseline_constant_current'], 3)) assert steps[start+8]['Ends']['EndEntry'][0]['EndType'] == 'Current' steps[start+8]['Ends']['EndEntry'][0]['Value'] = float(round(nominal_capacity * diagnostic_params['diagnostic_cutoff_current'], 3)) return self
def insert_hppc_cyclev2(self, start, nominal_capacity, diagnostic_params): """ Helper function for parameterizing the hybrid pulse power cycle Args: start: nominal_capacity: diagnostic_params: Returns: dict: """ steps = self['MaccorTestProcedure']['ProcSteps']['TestStep'] # Initial charge step for hppc cycle assert steps[start]['StepType'] == 'Charge' assert steps[start]['StepMode'] == 'Current' steps[start]['StepValue'] = float(round(nominal_capacity * diagnostic_params['HPPC_baseline_constant_current'], 3)) steps[start]['Limits']['Voltage'] = float(round(diagnostic_params['diagnostic_charge_cutoff_voltage'], 3)) assert steps[start]['Ends']['EndEntry'][0]['EndType'] == 'Current' steps[start]['Ends']['EndEntry'][0]['Value'] = float(round(nominal_capacity * diagnostic_params['diagnostic_cutoff_current'], 3)) # Rest step for hppc cycle assert steps[start+2]['StepType'] == 'Rest' assert steps[start+2]['Ends']['EndEntry'][0]['EndType'] == 'StepTime' time_s = int(round(60 * diagnostic_params['HPPC_rest_time'])) steps[start+2]['Ends']['EndEntry'][0]['Value'] = time.strftime('%H:%M:%S', time.gmtime(time_s)) # Discharge step 1 for hppc cycle assert steps[start+3]['StepType'] == 'Dischrge' assert steps[start+3]['StepMode'] == 'Current' steps[start+3]['StepValue'] = float(round(nominal_capacity * diagnostic_params['HPPC_pulse_current_1'], 3)) assert steps[start+3]['Ends']['EndEntry'][0]['EndType'] == 'StepTime' time_s = diagnostic_params['HPPC_pulse_duration_1'] steps[start+3]['Ends']['EndEntry'][0]['Value'] = time.strftime('%H:%M:%S', time.gmtime(time_s)) assert steps[start+3]['Ends']['EndEntry'][1]['EndType'] == 'Voltage' steps[start+3]['Ends']['EndEntry'][1]['Value'] = \ float(round(diagnostic_params['diagnostic_discharge_cutoff_voltage'], 3)) # Pulse rest step for hppc cycle assert steps[start+4]['StepType'] == 'Rest' assert steps[start+4]['Ends']['EndEntry'][0]['EndType'] == 'StepTime' time_s = int(round(diagnostic_params['HPPC_pulse_rest_time'])) steps[start+4]['Ends']['EndEntry'][0]['Value'] = time.strftime('%H:%M:%S', time.gmtime(time_s)) # Charge step 1 for hppc cycle assert steps[start+5]['StepType'] == 'Charge' assert steps[start+5]['StepMode'] == 'Current' steps[start+5]['StepValue'] = float(round(nominal_capacity * diagnostic_params['HPPC_pulse_current_2'], 3)) assert steps[start+5]['Ends']['EndEntry'][0]['EndType'] == 'StepTime' time_s = diagnostic_params['HPPC_pulse_duration_2'] steps[start+5]['Ends']['EndEntry'][0]['Value'] = time.strftime('%H:%M:%S', time.gmtime(time_s)) assert steps[start+5]['Ends']['EndEntry'][1]['EndType'] == 'Voltage' steps[start+5]['Ends']['EndEntry'][1]['Value'] = \ float(round(diagnostic_params['HPPC_pulse_cutoff_voltage'], 3)) # Discharge step 2 for hppc cycle assert steps[start+6]['StepType'] == 'Dischrge' assert steps[start+6]['StepMode'] == 'Current' steps[start+6]['StepValue'] = float(round(nominal_capacity * diagnostic_params['HPPC_baseline_constant_current'], 3)) assert steps[start+6]['Ends']['EndEntry'][0]['EndType'] == 'StepTime' time_s = int(round(3600 * (diagnostic_params['HPPC_interval'] / 100) / diagnostic_params['HPPC_baseline_constant_current'] - 1)) steps[start+6]['Ends']['EndEntry'][0]['Value'] = time.strftime('%H:%M:%S', time.gmtime(time_s)) assert steps[start+6]['Ends']['EndEntry'][1]['EndType'] == 'Voltage' steps[start+6]['Ends']['EndEntry'][1]['Value'] = \ float(round(diagnostic_params['diagnostic_discharge_cutoff_voltage'], 3)) # Final discharge step for hppc cycle assert steps[start+8]['StepType'] == 'Dischrge' assert steps[start+8]['StepMode'] == 'Voltage' steps[start+8]['StepValue'] = float(round(diagnostic_params['diagnostic_discharge_cutoff_voltage'], 3)) steps[start+8]['Limits']['Current'] = float(round(nominal_capacity * diagnostic_params['HPPC_baseline_constant_current'], 3)) assert steps[start+8]['Ends']['EndEntry'][0]['EndType'] == 'Current' steps[start+8]['Ends']['EndEntry'][0]['Value'] = float(round(nominal_capacity * diagnostic_params['diagnostic_cutoff_current'], 3)) return self
Python
def insert_rpt_cyclev2(self, start, nominal_capacity, diagnostic_params): """ Helper function for parameterizing the Rate Performance Test cycle Args: start: nominal_capacity: diagnostic_params: Returns: dict """ steps = self['MaccorTestProcedure']['ProcSteps']['TestStep'] # First charge step for rpt cycle assert steps[start]['StepType'] == 'Charge' assert steps[start]['StepMode'] == 'Current' steps[start]['StepValue'] = float(round(nominal_capacity * diagnostic_params['RPT_charge_constant_current'], 3)) steps[start]['Limits']['Voltage'] = float(round(diagnostic_params['diagnostic_charge_cutoff_voltage'], 3)) assert steps[start]['Ends']['EndEntry'][0]['EndType'] == 'Current' steps[start]['Ends']['EndEntry'][0]['Value'] = float(round(nominal_capacity * diagnostic_params['diagnostic_cutoff_current'], 3)) # 0.2C discharge step for rpt cycle assert steps[start+1]['StepType'] == 'Dischrge' assert steps[start+1]['StepMode'] == 'Current' steps[start+1]['StepValue'] = float(round(nominal_capacity * diagnostic_params['RPT_discharge_constant_current_1'], 3)) assert steps[start+1]['Ends']['EndEntry'][0]['EndType'] == 'Voltage' steps[start+1]['Ends']['EndEntry'][0]['Value'] = \ float(round(diagnostic_params['diagnostic_discharge_cutoff_voltage'], 3)) # Second charge step for rpt cycle assert steps[start+3]['StepType'] == 'Charge' assert steps[start+3]['StepMode'] == 'Current' steps[start+3]['StepValue'] = float(round(nominal_capacity * diagnostic_params['RPT_charge_constant_current'], 3)) steps[start+3]['Limits']['Voltage'] = float(round(diagnostic_params['diagnostic_charge_cutoff_voltage'], 3)) assert steps[start+3]['Ends']['EndEntry'][0]['EndType'] == 'Current' steps[start+3]['Ends']['EndEntry'][0]['Value'] = float(round(nominal_capacity * diagnostic_params['diagnostic_cutoff_current'], 3)) # 1C discharge step for rpt cycle assert steps[start+4]['StepType'] == 'Dischrge' assert steps[start+4]['StepMode'] == 'Current' steps[start+4]['StepValue'] = float(round(nominal_capacity * diagnostic_params['RPT_discharge_constant_current_2'], 3)) assert steps[start+4]['Ends']['EndEntry'][0]['EndType'] == 'Voltage' steps[start+4]['Ends']['EndEntry'][0]['Value'] = \ float(round(diagnostic_params['diagnostic_discharge_cutoff_voltage'], 3)) # Third charge step for rpt cycle assert steps[start+6]['StepType'] == 'Charge' assert steps[start+6]['StepMode'] == 'Current' steps[start+6]['StepValue'] = float(round(nominal_capacity * diagnostic_params['RPT_charge_constant_current'], 3)) steps[start+6]['Limits']['Voltage'] = float(round(diagnostic_params['diagnostic_charge_cutoff_voltage'], 3)) assert steps[start+6]['Ends']['EndEntry'][0]['EndType'] == 'Current' steps[start+6]['Ends']['EndEntry'][0]['Value'] = float(round(nominal_capacity * diagnostic_params['diagnostic_cutoff_current'], 3)) # 2C discharge step for rpt cycle assert steps[start+7]['StepType'] == 'Dischrge' assert steps[start+7]['StepMode'] == 'Current' steps[start+7]['StepValue'] = float(round(nominal_capacity * diagnostic_params['RPT_discharge_constant_current_3'], 3)) assert steps[start+7]['Ends']['EndEntry'][0]['EndType'] == 'Voltage' steps[start+7]['Ends']['EndEntry'][0]['Value'] = \ float(round(diagnostic_params['diagnostic_discharge_cutoff_voltage'], 3)) return self
def insert_rpt_cyclev2(self, start, nominal_capacity, diagnostic_params): """ Helper function for parameterizing the Rate Performance Test cycle Args: start: nominal_capacity: diagnostic_params: Returns: dict """ steps = self['MaccorTestProcedure']['ProcSteps']['TestStep'] # First charge step for rpt cycle assert steps[start]['StepType'] == 'Charge' assert steps[start]['StepMode'] == 'Current' steps[start]['StepValue'] = float(round(nominal_capacity * diagnostic_params['RPT_charge_constant_current'], 3)) steps[start]['Limits']['Voltage'] = float(round(diagnostic_params['diagnostic_charge_cutoff_voltage'], 3)) assert steps[start]['Ends']['EndEntry'][0]['EndType'] == 'Current' steps[start]['Ends']['EndEntry'][0]['Value'] = float(round(nominal_capacity * diagnostic_params['diagnostic_cutoff_current'], 3)) # 0.2C discharge step for rpt cycle assert steps[start+1]['StepType'] == 'Dischrge' assert steps[start+1]['StepMode'] == 'Current' steps[start+1]['StepValue'] = float(round(nominal_capacity * diagnostic_params['RPT_discharge_constant_current_1'], 3)) assert steps[start+1]['Ends']['EndEntry'][0]['EndType'] == 'Voltage' steps[start+1]['Ends']['EndEntry'][0]['Value'] = \ float(round(diagnostic_params['diagnostic_discharge_cutoff_voltage'], 3)) # Second charge step for rpt cycle assert steps[start+3]['StepType'] == 'Charge' assert steps[start+3]['StepMode'] == 'Current' steps[start+3]['StepValue'] = float(round(nominal_capacity * diagnostic_params['RPT_charge_constant_current'], 3)) steps[start+3]['Limits']['Voltage'] = float(round(diagnostic_params['diagnostic_charge_cutoff_voltage'], 3)) assert steps[start+3]['Ends']['EndEntry'][0]['EndType'] == 'Current' steps[start+3]['Ends']['EndEntry'][0]['Value'] = float(round(nominal_capacity * diagnostic_params['diagnostic_cutoff_current'], 3)) # 1C discharge step for rpt cycle assert steps[start+4]['StepType'] == 'Dischrge' assert steps[start+4]['StepMode'] == 'Current' steps[start+4]['StepValue'] = float(round(nominal_capacity * diagnostic_params['RPT_discharge_constant_current_2'], 3)) assert steps[start+4]['Ends']['EndEntry'][0]['EndType'] == 'Voltage' steps[start+4]['Ends']['EndEntry'][0]['Value'] = \ float(round(diagnostic_params['diagnostic_discharge_cutoff_voltage'], 3)) # Third charge step for rpt cycle assert steps[start+6]['StepType'] == 'Charge' assert steps[start+6]['StepMode'] == 'Current' steps[start+6]['StepValue'] = float(round(nominal_capacity * diagnostic_params['RPT_charge_constant_current'], 3)) steps[start+6]['Limits']['Voltage'] = float(round(diagnostic_params['diagnostic_charge_cutoff_voltage'], 3)) assert steps[start+6]['Ends']['EndEntry'][0]['EndType'] == 'Current' steps[start+6]['Ends']['EndEntry'][0]['Value'] = float(round(nominal_capacity * diagnostic_params['diagnostic_cutoff_current'], 3)) # 2C discharge step for rpt cycle assert steps[start+7]['StepType'] == 'Dischrge' assert steps[start+7]['StepMode'] == 'Current' steps[start+7]['StepValue'] = float(round(nominal_capacity * diagnostic_params['RPT_discharge_constant_current_3'], 3)) assert steps[start+7]['Ends']['EndEntry'][0]['EndType'] == 'Voltage' steps[start+7]['Ends']['EndEntry'][0]['Value'] = \ float(round(diagnostic_params['diagnostic_discharge_cutoff_voltage'], 3)) return self
Python
def to_file(self, filename, encoding='ISO-8859-1', column_width=20, linesep="\r\n"): """ Write DashOrderedDict to a settings file in the Biologic format with a *.mps extension. Args: filename (str): output name for settings file, full path encoding (str): file encoding to use when reading the file column_width (int): number of characters per step column linesep (str): characters to use for line separation, usually CRLF for Windows based machines Returns: (None): Writes out data to filename """ data = deepcopy(self) blocks = [] meta_data_keys = list(data['Metadata'].keys()) for indx, meta_key in enumerate(meta_data_keys): if 'Technique_' in meta_key: blocks.append(' : '.join([meta_key.split('_')[0], data['Metadata'][meta_key]])) tq_number = data['Metadata'][meta_key] blocks.append(data['Technique'][tq_number]['Type']) technique_keys = list(data['Technique'][tq_number]['Step']['1'].keys()) for tq_key in technique_keys: line = tq_key.ljust(column_width) for step in data['Technique']['1']['Step'].keys(): line = line + data['Technique']['1']['Step'][step][tq_key].ljust(column_width) blocks.append(line) continue elif data['Metadata'][meta_key] is None: line = meta_key elif data['Metadata'][meta_key] == 'blank': line = '' elif data['Metadata'][meta_key] is not None: line = ' : '.join([meta_key, data['Metadata'][meta_key]]) blocks.append(line) data.unset(data['Metadata'][meta_key]) contents = linesep.join(blocks) with open(filename, 'wb') as f: f.write(contents.encode(encoding))
def to_file(self, filename, encoding='ISO-8859-1', column_width=20, linesep="\r\n"): """ Write DashOrderedDict to a settings file in the Biologic format with a *.mps extension. Args: filename (str): output name for settings file, full path encoding (str): file encoding to use when reading the file column_width (int): number of characters per step column linesep (str): characters to use for line separation, usually CRLF for Windows based machines Returns: (None): Writes out data to filename """ data = deepcopy(self) blocks = [] meta_data_keys = list(data['Metadata'].keys()) for indx, meta_key in enumerate(meta_data_keys): if 'Technique_' in meta_key: blocks.append(' : '.join([meta_key.split('_')[0], data['Metadata'][meta_key]])) tq_number = data['Metadata'][meta_key] blocks.append(data['Technique'][tq_number]['Type']) technique_keys = list(data['Technique'][tq_number]['Step']['1'].keys()) for tq_key in technique_keys: line = tq_key.ljust(column_width) for step in data['Technique']['1']['Step'].keys(): line = line + data['Technique']['1']['Step'][step][tq_key].ljust(column_width) blocks.append(line) continue elif data['Metadata'][meta_key] is None: line = meta_key elif data['Metadata'][meta_key] == 'blank': line = '' elif data['Metadata'][meta_key] is not None: line = ' : '.join([meta_key, data['Metadata'][meta_key]]) blocks.append(line) data.unset(data['Metadata'][meta_key]) contents = linesep.join(blocks) with open(filename, 'wb') as f: f.write(contents.encode(encoding))
Python
def create_sdu(self, sdu_input_name, sdu_output_name): """ Highest level function in the class. Takes a schedule file and replaces all of the steps with steps from the procedure file. Then writes the resulting schedule file to the output file. Args: sdu_input_name (str): the full path of the schedule file to use as a shell for the steps sdu_output_name (str): the full path of the schedule file to output """ schedule = Schedule.from_file(sdu_input_name) # sdu_dict = Schedule.from_file(sdu_input_name) keys = list(schedule['Schedule'].keys()) for key in keys: if 'Schedule' in key: del schedule['Schedule'][key] step_name_list, step_flow_ctrl = self.create_metadata() for step_index, step in enumerate(self.procedure_dict_steps): step_arbin = self.compile_to_arbin(self.procedure_dict_steps[step_index], step_index, step_name_list, step_flow_ctrl) key = 'Step{}'.format(step_index) schedule.set("Schedule.{}".format(key), step_arbin) schedule.to_file(sdu_output_name)
def create_sdu(self, sdu_input_name, sdu_output_name): """ Highest level function in the class. Takes a schedule file and replaces all of the steps with steps from the procedure file. Then writes the resulting schedule file to the output file. Args: sdu_input_name (str): the full path of the schedule file to use as a shell for the steps sdu_output_name (str): the full path of the schedule file to output """ schedule = Schedule.from_file(sdu_input_name) # sdu_dict = Schedule.from_file(sdu_input_name) keys = list(schedule['Schedule'].keys()) for key in keys: if 'Schedule' in key: del schedule['Schedule'][key] step_name_list, step_flow_ctrl = self.create_metadata() for step_index, step in enumerate(self.procedure_dict_steps): step_arbin = self.compile_to_arbin(self.procedure_dict_steps[step_index], step_index, step_name_list, step_flow_ctrl) key = 'Step{}'.format(step_index) schedule.set("Schedule.{}".format(key), step_arbin) schedule.to_file(sdu_output_name)
Python
def create_metadata(self): """ Creates the necessary information so that flow control for the steps can be set up correctly. Returns: list: unique strings consisting of the step number and note dict: key value pairs for the loop control steps indicating which step the Loop step should GOTO when the end condition is not matched """ step_name_list = [] step_flow_ctrl = {} for indx, step in enumerate(self.procedure_dict_steps): step_name_list.append(str(indx + 1) + '-' + str(step['StepNote'])) if 'Loop' in step['StepType']: loop_counter = int(re.search(r'\d+', step['StepType']).group()) i = 1 while (indx - i) > 1: if self.procedure_dict_steps[abs(indx - i)]['StepType'] == 'Do {}'.format(loop_counter): do_index = abs(indx - i) break i = i + 1 step_flow_ctrl.update({indx: step_name_list[do_index + 1]}) return step_name_list, step_flow_ctrl
def create_metadata(self): """ Creates the necessary information so that flow control for the steps can be set up correctly. Returns: list: unique strings consisting of the step number and note dict: key value pairs for the loop control steps indicating which step the Loop step should GOTO when the end condition is not matched """ step_name_list = [] step_flow_ctrl = {} for indx, step in enumerate(self.procedure_dict_steps): step_name_list.append(str(indx + 1) + '-' + str(step['StepNote'])) if 'Loop' in step['StepType']: loop_counter = int(re.search(r'\d+', step['StepType']).group()) i = 1 while (indx - i) > 1: if self.procedure_dict_steps[abs(indx - i)]['StepType'] == 'Do {}'.format(loop_counter): do_index = abs(indx - i) break i = i + 1 step_flow_ctrl.update({indx: step_name_list[do_index + 1]}) return step_name_list, step_flow_ctrl
Python
def add_blank_limit(self): """ Minor helper function to add a limit that immediately advances to the next step. Returns: dict: blank limit that advances to the next step immediately """ ARBIN_SCHEMA = loadfn(os.path.join(PROTOCOL_SCHEMA_DIR, "arbin_schedule_schema.yaml")) limit = ARBIN_SCHEMA['step_blank_limit'] limit['m_bStepLimit'] = "1" limit['m_bLogDataLimit'] = "0" limit['m_szGotoStep'] = "Next Step" limit['Equation0_szLeft'] = 'PV_CHAN_Step_Time' limit['Equation0_szCompareSign'] = '>' limit['Equation0_szRight'] = '0' return limit
def add_blank_limit(self): """ Minor helper function to add a limit that immediately advances to the next step. Returns: dict: blank limit that advances to the next step immediately """ ARBIN_SCHEMA = loadfn(os.path.join(PROTOCOL_SCHEMA_DIR, "arbin_schedule_schema.yaml")) limit = ARBIN_SCHEMA['step_blank_limit'] limit['m_bStepLimit'] = "1" limit['m_bLogDataLimit'] = "0" limit['m_szGotoStep'] = "Next Step" limit['Equation0_szLeft'] = 'PV_CHAN_Step_Time' limit['Equation0_szCompareSign'] = '>' limit['Equation0_szRight'] = '0' return limit