code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
from enum import Enum, unique
@unique
class Weekday(Enum):
Sun = 0
Mon = 1
Tue = 2
Web = 3
Thu = 4
Fri = 5
Sat = 6
day1 = Weekday.Mon
print('day1 =', day1)
print('Weekday.Tue =', Weekday.Tue)
print('Weekday[\'Tue\'] =', Weekday['Tue'])
print('Weekday.Tue.value =', Weekday.Tue.value)
print('day1 == Weekday.Mon ?', day1 == Weekday.Mon)
print('day1 == Weekday.Tue ?', day1 == Weekday.Tue)
print('day1 == Weekday(1) ?', day1 == Weekday(1))
for name, member in Weekday.__members__.items():
print(name, '=>', member)
Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
for name, member in Month.__members__.items():
print(name, '=>', member, ',', member.value)
class Gender(Enum):
Male = 0
Female = 1
class Student(object):
def init(self, name, gender):
self.name = name
self.gender = gender
bart = Student('Bart', Gender.Male)
if bart.gender == Gender.Male:
print('测试通过!')
else:
print('测试失败!')
| [
"enum.Enum"
] | [((605, 708), 'enum.Enum', 'Enum', (['"""Month"""', "('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',\n 'Nov', 'Dec')"], {}), "('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',\n 'Sep', 'Oct', 'Nov', 'Dec'))\n", (609, 708), False, 'from enum import Enum, unique\n')] |
#! /usr/bin/env python3
import json
import mimetypes
import os
import re
import shutil
import string
import sys
import tarfile
import urllib.parse
import urllib.request
from collections import defaultdict, namedtuple
from http.server import BaseHTTPRequestHandler, HTTPServer
from bs4 import BeautifulSoup # pip3 install beautifulsoup4
Symbol = namedtuple("Symbol", "name")
CACHEDIR = os.path.join(os.path.dirname(__file__), ".cache")
def url_cachefile(url, basename=None):
basename = basename or os.path.basename(urllib.parse.urlparse(url).path)
assert len(basename)
cachefile = os.path.join(CACHEDIR, basename)
os.makedirs(os.path.dirname(cachefile), exist_ok=True)
if not os.path.exists(cachefile):
print("Downloading", url, file=sys.stderr)
with urllib.request.urlopen(url) as response:
with open(cachefile, "wb") as output:
shutil.copyfileobj(response, output)
return cachefile
def url_text(url, basename=None):
cachefile = url_cachefile(url, basename)
with open(cachefile, "r", encoding="utf-8") as input:
return input.read()
def replace_file_contents(filename, new_bytes):
newfilename = filename + ".new"
with open(newfilename, "wb") as output:
output.write(new_bytes)
os.rename(newfilename, filename)
def to_lisp(obj, toplevel=False):
if isinstance(obj, list):
return (
"("
+ ("\n" if toplevel else " ").join(map(to_lisp, obj))
+ ")"
+ ("\n" if toplevel else "")
)
if isinstance(obj, Symbol):
return obj.name
if isinstance(obj, str):
safe = string.ascii_letters + string.digits + " !#$%&'()*+,-./:;<=>?@[\]^_`{|}~"
for ch in obj:
if ch not in safe:
raise ValueError(
"Char {} in string {} unsafe for Lisp".format(repr(ch), repr(obj))
)
return '"' + obj + '"'
if isinstance(obj, int):
return str(obj)
assert False
def emit_lisp_file(filename, obj):
lisp = to_lisp(obj, True)
replace_file_contents(filename, lisp.encode("US-ASCII"))
def emit_json_file(filename, obj):
json_ = json.dumps(obj, ensure_ascii=True, sort_keys=True, indent=4)
replace_file_contents(filename, json_.encode("US-ASCII"))
def dict_with_sorted_values(items):
dict_ = {}
for key, values in items:
dict_[key] = list(sorted(values))
return dict_
def numbers_matching_regexp(regexp, items):
matches = filter(None, (re.match(regexp, item) for item in items))
return list(sorted(set(int(match.group(1)) for match in matches)))
def is_non_placeholder_symbol(s):
return bool(re.match(r"^[a-z@*+/-][a-zA-Z0-9@?!<>*/+-]*", s))
# ================================================================================
def r4rs_tarfile():
return tarfile.open(
url_cachefile(
"https://groups.csail.mit.edu/mac/ftpdir/scheme-reports/r4rs.tar.gz"
)
)
def r5rs_tarfile():
return tarfile.open(
url_cachefile(
"https://groups.csail.mit.edu/mac/ftpdir/scheme-reports/r5rs.tar.gz"
)
)
def r6rs_tarfile():
return tarfile.open(url_cachefile("http://www.r6rs.org/final/r6rs.tar.gz"))
def r4rs_symbols():
symbols = set()
tarfile = r4rs_tarfile()
for info in tarfile:
if info.name.endswith(".tex"):
tex_file = tarfile.extractfile(info).read().decode("US-ASCII")
for symbol in re.findall(r"{\\cf (.*?)}", tex_file):
symbols.add(symbol)
return symbols
# ================================================================================
MIN_SRFI_NUMBER = 0
MAX_SRFI_NUMBER = 185
def all_srfi_numbers():
return [i for i in range(MIN_SRFI_NUMBER, MAX_SRFI_NUMBER + 1)]
def srfi_cachefile(srfi_number):
return "srfi-{}.html".format(srfi_number)
def srfi_official_html_url(srfi_number):
return "https://srfi.schemers.org/srfi-{}/srfi-{}.html".format(
srfi_number, srfi_number
)
def srfi_github_html_url(srfi_number):
return (
"https://raw.githubusercontent.com/scheme-requests-for-implementation"
"/srfi-{}/master/srfi-{}.html".format(srfi_number, srfi_number)
)
def srfi_raw_html(srfi_number):
return url_text(srfi_github_html_url(srfi_number), srfi_cachefile(srfi_number))
def srfi_html_soup(srfi_number):
return BeautifulSoup(srfi_raw_html(srfi_number), "html.parser")
def srfi_title(srfi_number):
title = srfi_html_soup(srfi_number).find("title").text.strip()
match = re.match(r"SRFI \d+: (.*)", title)
return match.group(1) if match else title
def srfi_list_heads_from_code_tags(srfi_number):
return [
match.group(1)
for match in [
re.match(r"^\(([^\s()]+)", tag.text.strip())
for tag in srfi_html_soup(srfi_number).find_all("code")
]
if match
]
def srfi_defined_symbols(srfi_number):
return list(
sorted(
filter(
is_non_placeholder_symbol,
set(srfi_list_heads_from_code_tags(srfi_number)),
)
)
)
def all_srfi_defined_symbols():
return [
(srfi_number, symbol)
for srfi_number in all_srfi_numbers()
for symbol in srfi_defined_symbols(srfi_number)
]
def srfi_to_symbol_map():
sets = defaultdict(set)
for srfi_number, symbol in all_srfi_defined_symbols():
sets[srfi_number].add(symbol)
return dict_with_sorted_values(sets.items())
def symbol_to_srfi_map():
sets = defaultdict(set)
for srfi_number, symbol in all_srfi_defined_symbols():
sets[symbol].add(srfi_number)
return dict_with_sorted_values(sets.items())
def srfi_map():
return {
srfi_number: {
"number": srfi_number,
"title": srfi_title(srfi_number),
"official_html_url": srfi_official_html_url(srfi_number),
"github_html_url": srfi_github_html_url(srfi_number),
}
for srfi_number in all_srfi_numbers()
}
def emit_srfi():
the_map = srfi_map()
for srfi_number, info in the_map.items():
the_map[srfi_number]["symbols"] = []
for srfi_number, symbols in srfi_to_symbol_map().items():
the_map[srfi_number]["symbols"] = symbols
emit_json_file("srfi.json", the_map)
emit_lisp_file(
"srfi.lisp",
[
[
srfi_number,
[Symbol("title"), info["title"]],
[Symbol("symbols")] + info["symbols"],
]
for srfi_number, info in the_map.items()
],
)
# ================================================================================
def impl_chibi_tarfile():
return tarfile.open(
url_cachefile("http://synthcode.com/scheme/chibi/chibi-scheme-0.8.0.tgz")
)
def impl_chibi_srfi_list():
return numbers_matching_regexp(
r"chibi-scheme-.*?/lib/srfi/(\d+).sld",
(entry.name for entry in impl_chibi_tarfile()),
)
def impl_chibi():
return {
"id": "chibi",
"title": "Chibi-Scheme",
"homepage_url": "http://synthcode.com/wiki/chibi-scheme",
"srfi_implemented": impl_chibi_srfi_list(),
}
def impl_guile_tarfile():
return tarfile.open(
url_cachefile("https://ftp.gnu.org/gnu/guile/guile-2.2.4.tar.gz")
)
def impl_guile_srfi_list():
# Some SRFI implementations are single files, others are directories.
return numbers_matching_regexp(
r"guile-.*?/module/srfi/srfi-(\d+)",
(entry.name for entry in impl_guile_tarfile()),
)
def impl_guile():
return {
"id": "guile",
"title": "Guile",
"homepage_url": "https://www.gnu.org/software/guile/",
"srfi_implemented": impl_guile_srfi_list(),
}
def emit_implementation():
emit_json_file("implementation.json", [impl_chibi(), impl_guile()])
| [
"os.path.exists",
"collections.namedtuple",
"shutil.copyfileobj",
"os.rename",
"json.dumps",
"os.path.join",
"re.match",
"os.path.dirname",
"collections.defaultdict",
"tarfile.extractfile",
"re.findall"
] | [((351, 379), 'collections.namedtuple', 'namedtuple', (['"""Symbol"""', '"""name"""'], {}), "('Symbol', 'name')\n", (361, 379), False, 'from collections import defaultdict, namedtuple\n'), ((405, 430), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (420, 430), False, 'import os\n'), ((601, 633), 'os.path.join', 'os.path.join', (['CACHEDIR', 'basename'], {}), '(CACHEDIR, basename)\n', (613, 633), False, 'import os\n'), ((1293, 1325), 'os.rename', 'os.rename', (['newfilename', 'filename'], {}), '(newfilename, filename)\n', (1302, 1325), False, 'import os\n'), ((2205, 2265), 'json.dumps', 'json.dumps', (['obj'], {'ensure_ascii': '(True)', 'sort_keys': '(True)', 'indent': '(4)'}), '(obj, ensure_ascii=True, sort_keys=True, indent=4)\n', (2215, 2265), False, 'import json\n'), ((4607, 4641), 're.match', 're.match', (['"""SRFI \\\\d+: (.*)"""', 'title'], {}), "('SRFI \\\\d+: (.*)', title)\n", (4615, 4641), False, 'import re\n'), ((5413, 5429), 'collections.defaultdict', 'defaultdict', (['set'], {}), '(set)\n', (5424, 5429), False, 'from collections import defaultdict, namedtuple\n'), ((5615, 5631), 'collections.defaultdict', 'defaultdict', (['set'], {}), '(set)\n', (5626, 5631), False, 'from collections import defaultdict, namedtuple\n'), ((650, 676), 'os.path.dirname', 'os.path.dirname', (['cachefile'], {}), '(cachefile)\n', (665, 676), False, 'import os\n'), ((704, 729), 'os.path.exists', 'os.path.exists', (['cachefile'], {}), '(cachefile)\n', (718, 729), False, 'import os\n'), ((2710, 2757), 're.match', 're.match', (['"""^[a-z@*+/-][a-zA-Z0-9@?!<>*/+-]*"""', 's'], {}), "('^[a-z@*+/-][a-zA-Z0-9@?!<>*/+-]*', s)\n", (2718, 2757), False, 'import re\n'), ((2544, 2566), 're.match', 're.match', (['regexp', 'item'], {}), '(regexp, item)\n', (2552, 2566), False, 'import re\n'), ((3517, 3555), 're.findall', 're.findall', (['"""{\\\\\\\\cf (.*?)}"""', 'tex_file'], {}), "('{\\\\\\\\cf (.*?)}', tex_file)\n", (3527, 3555), False, 'import re\n'), ((902, 938), 'shutil.copyfileobj', 'shutil.copyfileobj', (['response', 'output'], {}), '(response, output)\n', (920, 938), False, 'import shutil\n'), ((3439, 3464), 'tarfile.extractfile', 'tarfile.extractfile', (['info'], {}), '(info)\n', (3458, 3464), False, 'import tarfile\n')] |
import os, sys, matplotlib
import faulthandler; faulthandler.enable()
mpl_v = 'MPL-8'
daptype = 'SPX-MILESHC-MILESHC'
os.environ['STELLARMASS_PCA_RESULTSDIR'] = '/Users/admin/sas/mangawork/manga/mangapca/zachpace/CSPs_CKC14_MaNGA_20190215-1/v2_5_3/2.3.0/results'
manga_results_basedir = os.environ['STELLARMASS_PCA_RESULTSDIR']
os.environ['STELLARMASS_PCA_CSPBASE'] = '/Users/admin/sas/mangawork/manga/mangapca/zachpace/CSPs_CKC14_MaNGA_20190215-1'
csp_basedir = os.environ['STELLARMASS_PCA_CSPBASE']
mocks_results_basedir = os.path.join(
os.environ['STELLARMASS_PCA_RESULTSDIR'], 'mocks')
from astropy.cosmology import WMAP9
cosmo = WMAP9
matplotlib.rcParams['font.family'] = 'serif'
matplotlib.rcParams['text.usetex'] = True
if 'DISPLAY' not in os.environ:
matplotlib.use('agg')
| [
"matplotlib.use",
"os.path.join",
"faulthandler.enable"
] | [((48, 69), 'faulthandler.enable', 'faulthandler.enable', ([], {}), '()\n', (67, 69), False, 'import faulthandler\n'), ((526, 589), 'os.path.join', 'os.path.join', (["os.environ['STELLARMASS_PCA_RESULTSDIR']", '"""mocks"""'], {}), "(os.environ['STELLARMASS_PCA_RESULTSDIR'], 'mocks')\n", (538, 589), False, 'import os, sys, matplotlib\n'), ((770, 791), 'matplotlib.use', 'matplotlib.use', (['"""agg"""'], {}), "('agg')\n", (784, 791), False, 'import os, sys, matplotlib\n')] |
import random
r1 = random.randint(1, 40)
print("Generate a random number without a seed between a range of two numbers - Integer:", r1)
r2 = random.uniform(1, 40)
print("Generate a random number without a seed between a range of two numbers - Decimal:", r2)
| [
"random.uniform",
"random.randint"
] | [((20, 41), 'random.randint', 'random.randint', (['(1)', '(40)'], {}), '(1, 40)\n', (34, 41), False, 'import random\n'), ((144, 165), 'random.uniform', 'random.uniform', (['(1)', '(40)'], {}), '(1, 40)\n', (158, 165), False, 'import random\n')] |
#!/usr/bin/python
#use to parse ms-sql-info nmap xml
#https://nmap.org/nsedoc/scripts/ms-sql-info.html
#nmap -Pn -n -p135,445,1433 --script ms-sql-info <host> -oX results-ms-sql-info.xml
#nmap -Pn -n -p135,445,1433 --script ms-sql-info -iL <hosts_file> -oX results-ms-sql-info.xml
# python3 mssql-info-parser.py results-ms-sql-info.xml
#
#
#
# #ip,port - use for pw guessing
# python3 mssql-info-parser.py results-ms-sql-info.xml | cut -d, -f1,2
#
# ip,port,winhostname,instancename,namedpipe
# python3 mssql-info-parser.py results-ms-sql-info.xml | cut -d, -f1,2,3,4,10
#
#
# python3 mssql-info-parser.py results-ms-sql-info.xml | cut -d, -f1,5
import xml.etree.ElementTree as ET
import sys
usage = "Usage: " + sys.argv[0] + " results-ms-sql-info.xml"
if len(sys.argv) == 1:
print(usage)
sys.exit()
if "-h" in sys.argv:
print(usage)
sys.exit()
if "--help" in sys.argv:
print(usage)
sys.exit()
masssql_file = sys.argv[1]
tree = ET.parse(masssql_file)
root = tree.getroot()
#host_data = []
ipSERV= []
dnsSERV = []
winSERV= []
scriSERV= []
ipSERCO= []
#ip,winserv
comboGetwinhostname= []
#ip,tcpport
soccETTT= []
hosts = root.findall('host')
for host in hosts:
script_element = host.findall('hostscript')
try:
script_namee = script_element[0].findall('script')[0].attrib['id']
except IndexError:
script_namee = ''
#filter, only show if ms-sql-info script ran and tags exist, otherwise skip..
if not script_namee =='ms-sql-info':
continue
#print(script_namee)
#show/find ip
ip_address = host.findall('address')[0].attrib['addr']
#add ip to array, [ip,dns,winhost,script]
ipSERV.append(ip_address)
#show/find hostname DNS
host_name_element = host.findall('hostnames')
try:
host_name = host_name_element[0].findall('hostname')[0].attrib['name']
except IndexError:
host_name = ''
dnsSERV.append(host_name)
try:
scriptoutt = script_element[0].findall('script')[0].attrib['output']
except IndexError:
scriptoutt = ''
#print(scriptoutt)
#print("@@@DBPWN- " + ip_address)
#print(ip_address + "," + "," + "," + scriptoutt)
#print("hostname- " + host_name)
##################
#find details
root1=host
#look for detailssss
for sup in root1.iter('script'):
root2=ET.Element('root')
#print(supply.attrib, supply.text) #shows script id, output.. better
root2=(sup)
for tech in root2.iter('elem'):
root3 = ET.Element('root')
root3=(tech)
#printservernames
#print(tech.attrib['key'])
#if tech.attrib['key']=='Windows server name':
# print(tech.text)
#elll = host.findall('address')[0].attrib['addr']
#print(elll)
#print(tech.text)
#note of servername to
#print("##- " + elll + ",," + tech.text )
# winSERV.append(tech.text)
#print(ip_address)
try:
if tech.attrib['key']=='Windows server name':
#print(tech.text)
#print("servername " + tech.text)
#print(ip_address + "," + tech.text )
comboGetwinhostname.append(ip_address + "," + tech.text)
winSERV.append(tech.text)
#else:
#winSERV.append(" ")
except IndexError:
print("pinggg")
#ipSERCO.append(elll + ",," + tech.text)
try:
if tech.attrib['key']=='TCP port':
#print(tech.text)
#print("servername " + tech.text)
#print(ip_address + "," + tech.text)
soccETTT.append(ip_address + "," + tech.text)
#comboGetwinhostname.append(ip_address + "," + tech.text)
#winSERV.append(tech.text)
#else:
#winSERV.append(" ")
except IndexError:
print("pingggg but not rly cause faills")
#ipSERCO.append(elll + ",," + tech.text)
#else:
#print(tech.attrib['key'])
#print("222222222222222222222222 no server name?????")
#this pulls in script output per each IP
script_element = host.findall('hostscript')
script_outt = script_element[0].findall('script')[0].attrib['output']
#print(script_outt)
scriSERV.append(script_outt)
#inhere is IPADDRESS
#print(comboGetwinhostname[0].split(',')[0])
#WINHOSTNAME
#print(comboGetwinhostname[0].split(',')[0] )
#
#
#thaarray IPADDRESS,winhostname
##try:
# x = len(comboGetwinhostname)
#print(x)
# #tempppIP = comboGetwinhostname[0].split(',')[0]
#print(comboGetwinhostname[x].split(',')[0])
#print(tempppIP)
#except:
# print("a111 ")
#debug
#print(ipSERV)
#print(dnsSERV)
#print(winSERV)
#print(scriSERV)
#print(ipSERCO)
#print tha mappings of IP,windowsServerr
#print(comboGetwinhostname)
#print(comboGetwinhostname[4])
#print(comboGetwinhostname[0].split(','))
# from mappings, dis tha IP address ONLY from the first column
#print(comboGetwinhostname[0].split(',')[0])
#print(comboGetwinhostname[1])
#print(comboGetwinhostname[1].split(',') )
#print(comboGetwinhostname[1].split(',') )
#try:
#x = len(comboGetwinhostname)
#print(x) #length starting at 1
#bombsssss maybe try -1 cause thats correct array size for last item
#print(comboGetwinhostname[x].split(',') )
#print(comboGetwinhostname[x-1].split(',') ) #shows last item
#print(comboGetwinhostname[x-1] )
#tempppIP = comboGetwinhostname[0].split(',')[0]
#print(comboGetwinhostname[x].split(',')[0])
#print(tempppIP)
#except:
# print("a111 000 :) ")
#print(soccETTT)
#print(ipSERV)
#####good luck..this takes array num from scriSERV,outputs parsed dict
def parsZZ(parMEplz):
#print(parMEplz)
#pp = {}
from collections import defaultdict
d = defaultdict(list)
nameOO = ""
nameOOnumm = ""
nameOOprodd = ""
nameOOseripac = ""
name00patchtho = ""
namdddpipez = []
npp = ""
currTCP = ""
instaTT = ""
instanceTEMP = []
i=0 #mssql instance -key.
b=0 #tcp port
c=0 #named pipe
#lol d is used for dictionary.. dont overwrite :P
e=0 #if clustered check
g=0 #name of mssql version
for line in parMEplz.splitlines():
#MSSQL INSTANCE NAME-KEY
#print(line)
if "Instance" in line:
#print("yooo found it? instance name = " + line)
x = line.split(": ")
#print(x[1])
instanceTEMP.append(x[1])
d[x[1]]
i=i+1
instaTT = x[1]
#TCPPORT
if "TCP port" in line:
#print("yooo found tcp port " + line)
x = line.split(": ")
#print(x[1])
#instanceTEMP.append(x[1])
try:
d[instanceTEMP[b]].append(x[1])
currTCP = x[1]
b=b+1
except (IndexError,KeyError):
continue
#NAMEDPIPE
if "Named pipe" in line:
x = line.split(": ")
#print(x[1])
#instanceTEMP.append(x[1])
#print(b)
#print(currTCP)
#d[instanceTEMP[c]].append(x[1])
c=c+1
namdddpipez.append(x[1])
npp = x[1]
#cluster?
#if "Clustered" in line:
# #print(x[1])
# x = line.split(": ")
# d[instanceTEMP[e]].append(x[1])
# e=e+1
#mssql version installed.
#overwrites named pi???s
#if " name" in line:
# #print(line)
# x = line.split(": ")
# print(x[1])
# d[instanceTEMP[g]].append(x[1])
# g=g+1
#name
if "name" in line:
ee = line.split(": ")
#print (ee[1])
nameOO = ee[1]
if "number" in line:
ee = line.split(": ")
nameOOnumm = ee[1]
if "Product" in line:
ee = line.split(": ")
nameOOprodd = ee[1]
if "Service pack" in line:
ee = line.split(": ")
nameOOseripac = ee[1]
if "Post-SP patches" in line:
ee = line.split(": ")
name00patchtho = ee[1]
#plop = namdddpipez
#print(plop)
#print(npp)
#print(instaTT)
if instaTT == "":
instaTT = ","
dalista = instaTT + "," + nameOO + "," + nameOOnumm+ "," + nameOOprodd+ "," + nameOOseripac+ "," + name00patchtho + "," + npp
#print(nameOO + "," + nameOOnumm+ "," + nameOOprodd+ "," + nameOOseripac+ "," + name00patchtho )
#print(d)
#print(*namdddpipez )
#print(d)
#print(d.items)
#+ "," + namdddpipez
#print(instaTT)
#import numpy as np
#print(np.matrix(d))
#print(d)
#print(namdddpipez) d + "," +
aiiaseg = dalista
#print(d)
return aiiaseg
#give item1,item2
#get item2
def shoArraKEE(striin):
#print("input funcctaia " + striin)
rrir = striin.split(",")
#print(rrir)
#print(rrir[1])
return(rrir[0])
def shoArTWOOO(striin):
#print("input funcctaia " + striin)
rrir = striin.split(",")
#print(rrir)
#print(rrir[1])
return(rrir[1])
def shosocc(striin):
#print("input funcctaia " + striin)
rrir = striin.split(",")
#print(rrir)
#print(rrir[1])
return(rrir[0] + "," + rrir[1])
def printteeALL():
#print("canijsutprintll")
finifia =[]
#print("#####stat-ips found- " , len(ipSERV) , " ips found" )
#print("#####sockett-ip-port--found- " , len(soccETTT) , " ip,tcpporort found" )#mostoftehse
#print("#####ip-winhostname mapping- " , len(comboGetwinhostname) , " ips,hostnaem" )
#cyclce through each socket ip:tcpport, since thatstahkey and mostuniqq^^^
for each in soccETTT:
#each ===== ip,port
#each1 ===== ip,winhostnaem
#match winhostname-to ip
tempwinda = ""
tempIPkeyonly = shoArraKEE(each)
#print("yayayaya" , tempIPkeyonly)
#print(comboGetwinhostname)
tempneweachh = each
for each1 in comboGetwinhostname:
# print("watupeachh " , each1 )
#print("watogg? " , each ) #dontfuqwitit
#print(shoArraKEE(each1))
if tempIPkeyonly == shoArraKEE(each1):
#print(each,",", shoArTWOOO(each1) )s
tempneweachh = each + "," + shoArTWOOO(each1)
#else:
#print(each, "," )
#if shoArraKEE(each1) == tempIPkeyonly:
# print(tempIPkeyonly, "," , shoArTWOOO(each1) )
#print(shoArTWOOO(each1))
#if shoArraKEE(each)
#if each == shoArraKEE(each):
# print("somethinnsmatchin..:) " , each)
#if each in comboGetwinhostname:
# print("don0")
#print(tempneweachh)
finifia.append(tempneweachh)
#each = tempneweachh
#print(each)
#print(each)
#print(each , )
#print(finifia)
return finifia
#print(dnsSERV)
#heh this the last item in our arrya
#peep send IP, get the 2nd column.
#peep = comboGetwinhostname[18]
#shoArraKEE(peep)
#this just prints it out straight up
#shoArraKEE(comboGetwinhostname[0])
#shoArraKEE(comboGetwinhostname[3])
#printeeIPSSrit
#printteeALL()
latestyah = printteeALL()
#print(latestyah)
for each in latestyah:
#print(each)
ippp = shoArraKEE(each)
ipppo = shosocc(each)
#print(ipppo)
#print(*ipppo)
for each1 in scriSERV:
#print(each1)
if ippp in each1:
print(each + "," + parsZZ(each1) )
#sprint()
#shosocc(
#if any(s in each1 for s in each):
# print("yooo this is tha " + ippp)
#script in array with ip indexed??
#print(scriSERV[1])
#print(scriSERV[0])
#print(scriSERV[2])
#ozz = parsZZ(scriSERV[1])
#ozz = parsZZ(scriSERV[99])
#print(ozz)
#print(ozz.items())
#print(parsZZ(scriSERV[0]))
#oa = parsZZ(scriSERV[0])
#sprint(oa)
#print(parsZZ(scriSERV[15]))
#arr = [2,4,5,7,9]
#arr_2d = [[1,2],[3,4]]
#print("The Array is: ", arr) #printing the array
#print("The 2D-Array is: ", arr_2d) #printing the 2D-Array
#printing the array
#print("The Array is : ")
#for i in arr:
# print(i, end = ' ')
#printing the 2D-Array
#print("\nThe 2D-Array is:")
#for i in arr_2d:
# for j in i:
# print(j, end=" ")
# print()
#for i in comboGetwinhostname:
# for j in i:
# print(j, end=" ")
# print()
#
#+====++++++++++++++++++++++
###test change here which to parse
#parMEplz = scriSERV[7]
#print(parMEplz)
#function here, send scriSERV[x], get a response of dict file back.
#~~~~~~WIN~~~~~~~~
#print(parsZZ(scriSERV[15]))
#print(parsZZ(scriSERV[15]))
#ozz = parsZZ(scriSERV[15])
#print(ozz.items())
########legacyyyyyyyyy
#print("IP,DNS,Server,Instance,TCP,Named Pipe")
#o=0
#for index,element in enumerate(ipSERV):
#print(index,element)
#print(element +","+ dnsSERV[index] + "," + winSERV[index])
#print(element) ##prints IP only..
#multipe ip per instance below, for each -- 5example
#udpate-- this should be for every key in tha dict
#oi = parsZZ(scriSERV[index])
#print(oi)
#print(oi[1])
#for each in oi:
#for key, value in oi.items() :
#print(key, value)
#sometimes when no namedpipe, then only one val
#print(element)
#print(dnsSERV[index])
#print(index)
#try:
# print(winSERV[index])
#except:
# print('errrrrrr')
# winSERV[index] == ''
#--almost done, only missing here is instace. is that key?
#print(key)
#print(ipSERCO)
#print(element)
#if element ==
#for iz in ipSERCO:
# print(ipSERCO[iz])
#if animal == 'Bird':
# print('Chirp!')
#try:
#out of range error her....
#if element == " ":
# print("YOOOOOOOOOOOOOOOOOOOOOOOOOO")
#print(element)
#if element in comboGetwinhostname:
# print("idonoooooo")
#
#print(element +","+ dnsSERV[index] + "," + "bs" +"," + key + "," + value[0] + "," + value[1])
#print(element +","+ dnsSERV[index] + "," + winSERV[index] +"," + key + "," + value[0] + "," + value[1])
#print(element +","+ dnsSERV[index] + "," + winSERV[index] )
#except IndexError as error:
#print(element +","+ dnsSERV[index] + "," + winSERV[index] +"," + key +"," + value[0])
#print(element +","+ dnsSERV[index] + "," + "," +"," + key +"," + value[0])
#print(element +","+ dnsSERV[index] + "," + winSERV[index] +"," + each)
#print(oi)
#print(each)
#print(element + "," + each)
#print(d[each])
#good, but need to convert list to string before concating.
#listToStr = ' '.join(map(str, d[each]))
#print(listToStr)
#o=o+1
#ipSERV= []
#dnsSERV = []
#winSERV= []
#scriSERV= []
| [
"xml.etree.ElementTree.Element",
"xml.etree.ElementTree.parse",
"collections.defaultdict",
"sys.exit"
] | [((980, 1002), 'xml.etree.ElementTree.parse', 'ET.parse', (['masssql_file'], {}), '(masssql_file)\n', (988, 1002), True, 'import xml.etree.ElementTree as ET\n'), ((821, 831), 'sys.exit', 'sys.exit', ([], {}), '()\n', (829, 831), False, 'import sys\n'), ((874, 884), 'sys.exit', 'sys.exit', ([], {}), '()\n', (882, 884), False, 'import sys\n'), ((931, 941), 'sys.exit', 'sys.exit', ([], {}), '()\n', (939, 941), False, 'import sys\n'), ((6807, 6824), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (6818, 6824), False, 'from collections import defaultdict\n'), ((2579, 2597), 'xml.etree.ElementTree.Element', 'ET.Element', (['"""root"""'], {}), "('root')\n", (2589, 2597), True, 'import xml.etree.ElementTree as ET\n'), ((2771, 2789), 'xml.etree.ElementTree.Element', 'ET.Element', (['"""root"""'], {}), "('root')\n", (2781, 2789), True, 'import xml.etree.ElementTree as ET\n')] |
from kivy.app import App
from controller.game import Game
from controller.actor import Local, AI
class GameApp(App):
def build(self):
game = Game()
game.actors = [
Local(game=game, name='player1'),
AI(game=game, name='player2'),
]
view = game.actors[0].view
game.setup()
return view
if __name__ == '__main__':
GameApp().run()
| [
"controller.actor.Local",
"controller.game.Game",
"controller.actor.AI"
] | [((158, 164), 'controller.game.Game', 'Game', ([], {}), '()\n', (162, 164), False, 'from controller.game import Game\n'), ((201, 233), 'controller.actor.Local', 'Local', ([], {'game': 'game', 'name': '"""player1"""'}), "(game=game, name='player1')\n", (206, 233), False, 'from controller.actor import Local, AI\n'), ((247, 276), 'controller.actor.AI', 'AI', ([], {'game': 'game', 'name': '"""player2"""'}), "(game=game, name='player2')\n", (249, 276), False, 'from controller.actor import Local, AI\n')] |
from carp_api.routing import router
from . import endpoints # NOQA
# to use pong we need to disable common routes as they are using conflicting
# urls
router.enable(endpoints=[
endpoints.UberPong,
])
| [
"carp_api.routing.router.enable"
] | [((155, 200), 'carp_api.routing.router.enable', 'router.enable', ([], {'endpoints': '[endpoints.UberPong]'}), '(endpoints=[endpoints.UberPong])\n', (168, 200), False, 'from carp_api.routing import router\n')] |
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
An example of reading a line at a time from standard input
without blocking the reactor.
"""
from os import linesep
from twisted.internet import stdio
from twisted.protocols import basic
class Echo(basic.LineReceiver):
delimiter = linesep.encode("ascii")
def connectionMade(self):
self.transport.write(b">>> ")
def lineReceived(self, line):
self.sendLine(b"Echo: " + line)
self.transport.write(b">>> ")
def main():
stdio.StandardIO(Echo())
from twisted.internet import reactor
reactor.run()
if __name__ == "__main__":
main()
| [
"os.linesep.encode",
"twisted.internet.reactor.run"
] | [((317, 340), 'os.linesep.encode', 'linesep.encode', (['"""ascii"""'], {}), "('ascii')\n", (331, 340), False, 'from os import linesep\n'), ((612, 625), 'twisted.internet.reactor.run', 'reactor.run', ([], {}), '()\n', (623, 625), False, 'from twisted.internet import reactor\n')] |
import networkx as nx
class Hierarchy:
def __init__(self, tree, column):
self.tree = tree
self.column = column
def _leaves_below(self, node):
leaves = sum(([vv for vv in v if self.tree.out_degree(vv) == 0]
for k, v in nx.dfs_successors(self.tree, node).items()),
[])
return sorted(leaves) or [node]
def __call__(self, *nodes):
"""Return process IDs below the given nodes in the tree"""
s = set()
for node in nodes:
if self.tree.in_degree(node) == 0:
return None # all
s.update(self._leaves_below(node))
if len(s) == 1:
query = '{} == "{}"'.format(self.column, s.pop())
else:
query = '{} in {}'.format(self.column, repr(sorted(s)))
return query
| [
"networkx.dfs_successors"
] | [((275, 309), 'networkx.dfs_successors', 'nx.dfs_successors', (['self.tree', 'node'], {}), '(self.tree, node)\n', (292, 309), True, 'import networkx as nx\n')] |
# coding = utf-8
from inherit_abstract.abstractcollection import AbstractCollection
class AbstractDict(AbstractCollection):
"""
Common data and method implementations for dictionaries.
"""
def __init__(self, source_collection):
"""
Will copy items to the collection from source_collection if it's present.
"""
AbstractCollection.__init__(self)
if source_collection:
for key, value in source_collection:
self[key] = value
def __str__(self):
return "{" + ", ".join(map(str, self.items())) + "}"
def __and__(self, other):
"""
Returns a new dictionary containing the contents of self adn other.
:param other:
:return:
"""
result = type(self)(map(lambda item: (item.key, item.value), self.items()))
for key in other:
result[key] = other[key]
return result
def __eq__(self, other):
"""
Returns True if self equals other, or False otherwise.
:param other:
:return:
"""
if self is other:
return True
if type(self) != type(other) or len(self) != len(other):
return False
for key in self:
if not key in other:
return False
return True
def keys(self):
"""
Returns a iterator on the keys in the dictionary.
:return:
"""
return iter(self)
def values(self):
"""
Reutrns an iterator on the values in the dictionary.
:return:
"""
return iter(map(lambda key: self[key], self))
def items(self):
"""
Returns an iterator on the items in the dictionary.
:return:
"""
return iter(map(lambda key: Item(key, self[key]), self))
class Item(object):
"""
Represents a dictionary item. Supports comparisons by key.
"""
def __init__(self, key, value):
self.key = key
self.value = value
def __str__(self):
return str(self.key) + ":" + str(self.value)
def __eq__(self, other):
if type(self) != type(other):
return False
return self.key == other.key
def __lt__(self, other):
if type(self) != type(other):
return False
return self.key < other.key
def __le__(self, other):
if type(self) != type(other):
return False
return self.key <= other.key
| [
"inherit_abstract.abstractcollection.AbstractCollection.__init__"
] | [((361, 394), 'inherit_abstract.abstractcollection.AbstractCollection.__init__', 'AbstractCollection.__init__', (['self'], {}), '(self)\n', (388, 394), False, 'from inherit_abstract.abstractcollection import AbstractCollection\n')] |
import logging
from functools import partial
from django import forms
from django.db import models
from django.utils.translation import ugettext_lazy as _
from simple_history.admin import SimpleHistoryAdmin
from simple_history.models import HistoricalRecords
from simple_history.utils import update_change_reason
log = logging.getLogger(__name__)
def safe_update_change_reason(instance, reason):
"""Wrapper around update_change_reason to catch exceptions."""
try:
update_change_reason(instance=instance, reason=reason)
except Exception:
log.exception(
'An error occurred while updating the change reason of the instance: obj=%s',
instance,
)
class ExtraFieldsHistoricalModel(models.Model):
"""
Abstract model to allow history models track extra data.
Extra data includes:
- User information to retain after they have been deleted
- IP & browser
"""
extra_history_user_id = models.IntegerField(
_('ID'),
blank=True,
null=True,
db_index=True,
)
extra_history_user_username = models.CharField(
_('username'),
max_length=150,
null=True,
db_index=True,
)
extra_history_ip = models.CharField(
_('IP address'),
blank=True,
null=True,
max_length=250,
)
extra_history_browser = models.CharField(
_('Browser user-agent'),
max_length=250,
blank=True,
null=True,
)
class Meta:
abstract = True
ExtraHistoricalRecords = partial(HistoricalRecords, bases=[ExtraFieldsHistoricalModel])
"""Helper partial to use instead of HistoricalRecords."""
class ExtraSimpleHistoryAdmin(SimpleHistoryAdmin):
"""Set the change_reason on the model changed through this admin view."""
change_reason = None
def get_change_reason(self):
if self.change_reason:
return self.change_reason
klass = self.__class__.__name__
return f'origin=admin class={klass}'
def save_model(self, request, obj, form, change):
super().save_model(request, obj, form, change)
safe_update_change_reason(obj, self.get_change_reason())
def delete_model(self, request, obj):
super().delete_model(request, obj)
safe_update_change_reason(obj, self.change_reason)
class SimpleHistoryModelForm(forms.ModelForm):
"""Set the change_reason on the model changed through this form."""
change_reason = None
def get_change_reason(self):
if self.change_reason:
return self.change_reason
klass = self.__class__.__name__
return f'origin=form class={klass}'
def save(self, commit=True):
obj = super().save(commit=commit)
safe_update_change_reason(obj, self.get_change_reason())
return obj
class UpdateChangeReasonPostView:
"""
Set the change_reason on the model changed through the POST method of this view.
Use this class for views that don't use a form, like ``DeleteView``.
"""
change_reason = None
def get_change_reason(self):
if self.change_reason:
return self.change_reason
klass = self.__class__.__name__
return f'origin=form class={klass}'
def post(self, request, *args, **kwargs):
obj = self.get_object()
response = super().post(request, *args, **kwargs)
safe_update_change_reason(obj, self.get_change_reason())
return response
| [
"logging.getLogger",
"django.utils.translation.ugettext_lazy",
"functools.partial",
"simple_history.utils.update_change_reason"
] | [((321, 348), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (338, 348), False, 'import logging\n'), ((1575, 1637), 'functools.partial', 'partial', (['HistoricalRecords'], {'bases': '[ExtraFieldsHistoricalModel]'}), '(HistoricalRecords, bases=[ExtraFieldsHistoricalModel])\n', (1582, 1637), False, 'from functools import partial\n'), ((484, 538), 'simple_history.utils.update_change_reason', 'update_change_reason', ([], {'instance': 'instance', 'reason': 'reason'}), '(instance=instance, reason=reason)\n', (504, 538), False, 'from simple_history.utils import update_change_reason\n'), ((1000, 1007), 'django.utils.translation.ugettext_lazy', '_', (['"""ID"""'], {}), "('ID')\n", (1001, 1007), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((1137, 1150), 'django.utils.translation.ugettext_lazy', '_', (['"""username"""'], {}), "('username')\n", (1138, 1150), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((1273, 1288), 'django.utils.translation.ugettext_lazy', '_', (['"""IP address"""'], {}), "('IP address')\n", (1274, 1288), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((1413, 1436), 'django.utils.translation.ugettext_lazy', '_', (['"""Browser user-agent"""'], {}), "('Browser user-agent')\n", (1414, 1436), True, 'from django.utils.translation import ugettext_lazy as _\n')] |
#!/usr/bin/env python
import numpy
import storm_analysis
import storm_analysis.simulator.pupil_math as pupilMath
def test_pupil_math_1():
"""
Test GeometryC, intensity, no scaling.
"""
geo = pupilMath.Geometry(20, 0.1, 0.6, 1.5, 1.4)
geo_c = pupilMath.GeometryC(20, 0.1, 0.6, 1.5, 1.4)
pf = geo.createFromZernike(1.0, [[1.3, -1, 3], [1.3, -2, 2]])
z_vals = numpy.linspace(-1.0,1.0,10)
psf_py = geo.pfToPSF(pf, z_vals)
psf_c = geo_c.pfToPSF(pf, z_vals)
assert numpy.allclose(psf_c, psf_py)
def test_pupil_math_2():
"""
Test GeometryC, complex values, no scaling.
"""
geo = pupilMath.Geometry(20, 0.1, 0.6, 1.5, 1.4)
geo_c = pupilMath.GeometryC(20, 0.1, 0.6, 1.5, 1.4)
pf = geo.createFromZernike(1.0, [[1.3, -1, 3], [1.3, -2, 2]])
z_vals = numpy.linspace(-1.0,1.0,10)
psf_py = geo.pfToPSF(pf, z_vals, want_intensity = False)
psf_c = geo_c.pfToPSF(pf, z_vals, want_intensity = False)
assert numpy.allclose(psf_c, psf_py)
def test_pupil_math_3():
"""
Test GeometryC, intensity, scaling.
"""
geo = pupilMath.Geometry(20, 0.1, 0.6, 1.5, 1.4)
geo_c = pupilMath.GeometryC(20, 0.1, 0.6, 1.5, 1.4)
pf = geo.createFromZernike(1.0, [[1.3, -1, 3], [1.3, -2, 2]])
z_vals = numpy.linspace(-1.0,1.0,10)
gsf = geo.gaussianScalingFactor(1.8)
psf_py = geo.pfToPSF(pf, z_vals, scaling_factor = gsf)
psf_c = geo_c.pfToPSF(pf, z_vals, scaling_factor = gsf)
assert numpy.allclose(psf_c, psf_py)
def test_pupil_math_4():
"""
Test GeometryCVectorial, intensity, no scaling.
"""
geo = pupilMath.GeometryVectorial(20, 0.1, 0.6, 1.5, 1.4)
geo_c = pupilMath.GeometryCVectorial(20, 0.1, 0.6, 1.5, 1.4)
pf = geo.createFromZernike(1.0, [[1.3, -1, 3], [1.3, -2, 2]])
z_vals = numpy.linspace(-1.0,1.0,10)
psf_py = geo.pfToPSF(pf, z_vals)
psf_c = geo_c.pfToPSF(pf, z_vals)
assert numpy.allclose(psf_c, psf_py)
def test_pupil_math_5():
"""
Test GeometryCVectorial, intensity, scaling.
"""
geo = pupilMath.GeometryVectorial(20, 0.1, 0.6, 1.5, 1.4)
geo_c = pupilMath.GeometryCVectorial(20, 0.1, 0.6, 1.5, 1.4)
pf = geo.createFromZernike(1.0, [[1.3, -1, 3], [1.3, -2, 2]])
z_vals = numpy.linspace(-1.0,1.0,10)
gsf = geo.gaussianScalingFactor(1.8)
psf_py = geo.pfToPSF(pf, z_vals, scaling_factor = gsf)
psf_c = geo_c.pfToPSF(pf, z_vals, scaling_factor = gsf)
if (__name__ == "__main__"):
test_pupil_math_1()
test_pupil_math_2()
test_pupil_math_3()
| [
"numpy.allclose",
"storm_analysis.simulator.pupil_math.GeometryVectorial",
"storm_analysis.simulator.pupil_math.GeometryC",
"numpy.linspace",
"storm_analysis.simulator.pupil_math.GeometryCVectorial",
"storm_analysis.simulator.pupil_math.Geometry"
] | [((211, 253), 'storm_analysis.simulator.pupil_math.Geometry', 'pupilMath.Geometry', (['(20)', '(0.1)', '(0.6)', '(1.5)', '(1.4)'], {}), '(20, 0.1, 0.6, 1.5, 1.4)\n', (229, 253), True, 'import storm_analysis.simulator.pupil_math as pupilMath\n'), ((266, 309), 'storm_analysis.simulator.pupil_math.GeometryC', 'pupilMath.GeometryC', (['(20)', '(0.1)', '(0.6)', '(1.5)', '(1.4)'], {}), '(20, 0.1, 0.6, 1.5, 1.4)\n', (285, 309), True, 'import storm_analysis.simulator.pupil_math as pupilMath\n'), ((395, 424), 'numpy.linspace', 'numpy.linspace', (['(-1.0)', '(1.0)', '(10)'], {}), '(-1.0, 1.0, 10)\n', (409, 424), False, 'import numpy\n'), ((515, 544), 'numpy.allclose', 'numpy.allclose', (['psf_c', 'psf_py'], {}), '(psf_c, psf_py)\n', (529, 544), False, 'import numpy\n'), ((645, 687), 'storm_analysis.simulator.pupil_math.Geometry', 'pupilMath.Geometry', (['(20)', '(0.1)', '(0.6)', '(1.5)', '(1.4)'], {}), '(20, 0.1, 0.6, 1.5, 1.4)\n', (663, 687), True, 'import storm_analysis.simulator.pupil_math as pupilMath\n'), ((700, 743), 'storm_analysis.simulator.pupil_math.GeometryC', 'pupilMath.GeometryC', (['(20)', '(0.1)', '(0.6)', '(1.5)', '(1.4)'], {}), '(20, 0.1, 0.6, 1.5, 1.4)\n', (719, 743), True, 'import storm_analysis.simulator.pupil_math as pupilMath\n'), ((829, 858), 'numpy.linspace', 'numpy.linspace', (['(-1.0)', '(1.0)', '(10)'], {}), '(-1.0, 1.0, 10)\n', (843, 858), False, 'import numpy\n'), ((997, 1026), 'numpy.allclose', 'numpy.allclose', (['psf_c', 'psf_py'], {}), '(psf_c, psf_py)\n', (1011, 1026), False, 'import numpy\n'), ((1119, 1161), 'storm_analysis.simulator.pupil_math.Geometry', 'pupilMath.Geometry', (['(20)', '(0.1)', '(0.6)', '(1.5)', '(1.4)'], {}), '(20, 0.1, 0.6, 1.5, 1.4)\n', (1137, 1161), True, 'import storm_analysis.simulator.pupil_math as pupilMath\n'), ((1174, 1217), 'storm_analysis.simulator.pupil_math.GeometryC', 'pupilMath.GeometryC', (['(20)', '(0.1)', '(0.6)', '(1.5)', '(1.4)'], {}), '(20, 0.1, 0.6, 1.5, 1.4)\n', (1193, 1217), True, 'import storm_analysis.simulator.pupil_math as pupilMath\n'), ((1303, 1332), 'numpy.linspace', 'numpy.linspace', (['(-1.0)', '(1.0)', '(10)'], {}), '(-1.0, 1.0, 10)\n', (1317, 1332), False, 'import numpy\n'), ((1508, 1537), 'numpy.allclose', 'numpy.allclose', (['psf_c', 'psf_py'], {}), '(psf_c, psf_py)\n', (1522, 1537), False, 'import numpy\n'), ((1642, 1693), 'storm_analysis.simulator.pupil_math.GeometryVectorial', 'pupilMath.GeometryVectorial', (['(20)', '(0.1)', '(0.6)', '(1.5)', '(1.4)'], {}), '(20, 0.1, 0.6, 1.5, 1.4)\n', (1669, 1693), True, 'import storm_analysis.simulator.pupil_math as pupilMath\n'), ((1706, 1758), 'storm_analysis.simulator.pupil_math.GeometryCVectorial', 'pupilMath.GeometryCVectorial', (['(20)', '(0.1)', '(0.6)', '(1.5)', '(1.4)'], {}), '(20, 0.1, 0.6, 1.5, 1.4)\n', (1734, 1758), True, 'import storm_analysis.simulator.pupil_math as pupilMath\n'), ((1844, 1873), 'numpy.linspace', 'numpy.linspace', (['(-1.0)', '(1.0)', '(10)'], {}), '(-1.0, 1.0, 10)\n', (1858, 1873), False, 'import numpy\n'), ((1964, 1993), 'numpy.allclose', 'numpy.allclose', (['psf_c', 'psf_py'], {}), '(psf_c, psf_py)\n', (1978, 1993), False, 'import numpy\n'), ((2095, 2146), 'storm_analysis.simulator.pupil_math.GeometryVectorial', 'pupilMath.GeometryVectorial', (['(20)', '(0.1)', '(0.6)', '(1.5)', '(1.4)'], {}), '(20, 0.1, 0.6, 1.5, 1.4)\n', (2122, 2146), True, 'import storm_analysis.simulator.pupil_math as pupilMath\n'), ((2159, 2211), 'storm_analysis.simulator.pupil_math.GeometryCVectorial', 'pupilMath.GeometryCVectorial', (['(20)', '(0.1)', '(0.6)', '(1.5)', '(1.4)'], {}), '(20, 0.1, 0.6, 1.5, 1.4)\n', (2187, 2211), True, 'import storm_analysis.simulator.pupil_math as pupilMath\n'), ((2297, 2326), 'numpy.linspace', 'numpy.linspace', (['(-1.0)', '(1.0)', '(10)'], {}), '(-1.0, 1.0, 10)\n', (2311, 2326), False, 'import numpy\n')] |
import numpy as np
import gdal
from ..utils.indexing import _LocIndexer, _iLocIndexer
from libpyhat.transform.continuum import continuum_correction
from libpyhat.transform.continuum import polynomial, linear, regression
class HCube(object):
"""
A Mixin class for use with the io_gdal.GeoDataset class
to optionally add support for spectral labels, label
based indexing, and lazy loading for reads.
"""
def __init__(self, data = [], wavelengths = []):
if len(data) != 0:
self._data = data
if len(wavelengths) != 0:
self._wavelengths = wavelengths
@property
def wavelengths(self):
if not hasattr(self, '_wavelengths'):
try:
info = gdal.Info(self.file_name, format='json')
wavelengths = [float(j) for i, j in sorted(info['metadata'][''].items(),
key=lambda x: float(x[0].split('_')[-1]))]
self._original_wavelengths = wavelengths
self._wavelengths = np.round(wavelengths, self.tolerance)
except:
self._wavelengths = []
return self._wavelengths
@property
def data(self):
if not hasattr(self, '_data'):
try:
key = (slice(None, None, None),
slice(None, None, None),
slice(None, None, None))
data = self._read(key)
except Exception as e:
print(e)
data = []
self._data = data
return self._data
@property
def tolerance(self):
return getattr(self, '_tolerance', 2)
@tolerance.setter
def tolerance(self, val):
if isinstance(val, int):
self._tolerance = val
self._reindex()
else:
raise TypeError
def _reindex(self):
if self._original_wavelengths is not None:
self._wavelengths = np.round(self._original_wavelengths, decimals=self.tolerance)
def __getitem__(self, key):
i = _iLocIndexer(self)
return i[key]
@property
def loc(self):
return _LocIndexer(self)
@property
def iloc(self):
return _iLocIndexer(self)
def reduce(self, how = np.mean, axis = (1, 2)):
"""
Parameters
----------
how : function
Function to apply across along axises of the hcube
axis : tuple
List of axis to apply a given function along
Returns
-------
new_hcube : Object
A new hcube object with the reduced data set
"""
res = how(self.data, axis = axis)
new_hcube = HCube(res, self.wavelengths)
return new_hcube
def continuum_correct(self, nodes, correction_nodes = np.array([]), correction = linear,
axis=0, adaptive=False, window=3, **kwargs):
"""
Parameters
----------
nodes : list
A list of wavelengths for the continuum to be corrected along
correction_nodes : list
A list of nodes to limit the correction between
correction : function
Function specifying the type of correction to perform
along the continuum
axis : int
Axis to apply the continuum correction on
adaptive : boolean
?
window : int
?
Returns
-------
new_hcube : Object
A new hcube object with the corrected dataset
"""
continuum_data = continuum_correction(self.data, self.wavelengths, nodes = nodes,
correction_nodes = correction_nodes, correction = correction,
axis = axis, adaptive = adaptive,
window = window, **kwargs)
new_hcube = HCube(continuum_data[0], self.wavelengths)
return new_hcube
def clip_roi(self, x, y, band, tolerance=2):
"""
Parameters
----------
x : tuple
Lower and upper bound along the x axis for clipping
y : tuple
Lower and upper bound along the y axis for clipping
band : tuple
Lower and upper band along the z axis for clipping
tolerance : int
Tolerance given for trying to find wavelengths
between the upper and lower bound
Returns
-------
new_hcube : Object
A new hcube object with the clipped dataset
"""
wavelength_clip = []
for wavelength in self.wavelengths:
wavelength_upper = wavelength + tolerance
wavelength_lower = wavelength - tolerance
if wavelength_upper > band[0] and wavelength_lower < band[1]:
wavelength_clip.append(wavelength)
key = (wavelength_clip, slice(*x), slice(*y))
data_clip = _LocIndexer(self)[key]
new_hcube = HCube(np.copy(data_clip), np.array(wavelength_clip))
return new_hcube
def _read(self, key):
ifnone = lambda a, b: b if a is None else a
y = key[1]
x = key[2]
if isinstance(x, slice):
xstart = ifnone(x.start,0)
xstop = ifnone(x.stop,self.raster_size[0])
xstep = xstop - xstart
else:
raise TypeError("Loc style access elements must be slices, e.g., [:] or [10:100]")
if isinstance(y, slice):
ystart = ifnone(y.start, 0)
ystop = ifnone(y.stop, self.raster_size[1])
ystep = ystop - ystart
else:
raise TypeError("Loc style access elements must be slices, e.g., [:] or [10:100]")
pixels = (xstart, ystart, xstep, ystep)
if isinstance(key[0], (int, np.integer)):
return self.read_array(band=int(key[0]+1), pixels=pixels)
elif isinstance(key[0], slice):
# Given some slice iterate over the bands and get the bands and pixel space requested
arrs = []
for band in list(list(range(1, self.nbands + 1))[key[0]]):
arrs.append(self.read_array(band, pixels = pixels))
return np.stack(arrs)
else:
arrs = []
for b in key[0]:
arrs.append(self.read_array(band=int(b+1), pixels=pixels))
return np.stack(arrs)
| [
"numpy.copy",
"libpyhat.transform.continuum.continuum_correction",
"numpy.array",
"numpy.stack",
"gdal.Info",
"numpy.round"
] | [((2841, 2853), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2849, 2853), True, 'import numpy as np\n'), ((3684, 3867), 'libpyhat.transform.continuum.continuum_correction', 'continuum_correction', (['self.data', 'self.wavelengths'], {'nodes': 'nodes', 'correction_nodes': 'correction_nodes', 'correction': 'correction', 'axis': 'axis', 'adaptive': 'adaptive', 'window': 'window'}), '(self.data, self.wavelengths, nodes=nodes,\n correction_nodes=correction_nodes, correction=correction, axis=axis,\n adaptive=adaptive, window=window, **kwargs)\n', (3704, 3867), False, 'from libpyhat.transform.continuum import continuum_correction\n'), ((6561, 6575), 'numpy.stack', 'np.stack', (['arrs'], {}), '(arrs)\n', (6569, 6575), True, 'import numpy as np\n'), ((1971, 2032), 'numpy.round', 'np.round', (['self._original_wavelengths'], {'decimals': 'self.tolerance'}), '(self._original_wavelengths, decimals=self.tolerance)\n', (1979, 2032), True, 'import numpy as np\n'), ((5168, 5186), 'numpy.copy', 'np.copy', (['data_clip'], {}), '(data_clip)\n', (5175, 5186), True, 'import numpy as np\n'), ((5188, 5213), 'numpy.array', 'np.array', (['wavelength_clip'], {}), '(wavelength_clip)\n', (5196, 5213), True, 'import numpy as np\n'), ((741, 781), 'gdal.Info', 'gdal.Info', (['self.file_name'], {'format': '"""json"""'}), "(self.file_name, format='json')\n", (750, 781), False, 'import gdal\n'), ((1040, 1077), 'numpy.round', 'np.round', (['wavelengths', 'self.tolerance'], {}), '(wavelengths, self.tolerance)\n', (1048, 1077), True, 'import numpy as np\n'), ((6390, 6404), 'numpy.stack', 'np.stack', (['arrs'], {}), '(arrs)\n', (6398, 6404), True, 'import numpy as np\n')] |
import orderedset
def find_cycle(nodes, successors):
path = orderedset.orderedset()
visited = set()
def visit(node):
# If the node is already in the current path, we have found a cycle.
if not path.add(node):
return (path, node)
# If we have otherwise already visited this node, we don't need to visit
# it again.
if node in visited:
item = path.pop()
assert item == node
return
visited.add(node)
# Otherwise, visit all the successors.
for succ in successors(node):
cycle = visit(succ)
if cycle is not None:
return cycle
item = path.pop()
assert item == node
return None
for node in nodes:
cycle = visit(node)
if cycle is not None:
return cycle
else:
assert not path.items
return None
| [
"orderedset.orderedset"
] | [((65, 88), 'orderedset.orderedset', 'orderedset.orderedset', ([], {}), '()\n', (86, 88), False, 'import orderedset\n')] |
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for describe Memorystore Memcache instances."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import six
def FormatResponse(response, _):
"""Hook to modify gcloud describe output for maintenance windows."""
modified_response = {}
if response.authorizedNetwork:
modified_response['authorizedNetwork'] = response.authorizedNetwork
if response.createTime:
modified_response['createTime'] = response.createTime
if response.discoveryEndpoint:
modified_response['discoveryEndpoint'] = response.discoveryEndpoint
if response.maintenanceSchedule:
modified_response['maintenanceSchedule'] = response.maintenanceSchedule
if response.memcacheFullVersion:
modified_response['memcacheFullVersion'] = response.memcacheFullVersion
if response.memcacheNodes:
modified_response['memcacheNodes'] = response.memcacheNodes
if response.memcacheVersion:
modified_response['memcacheVersion'] = response.memcacheVersion
if response.name:
modified_response['name'] = response.name
if response.nodeConfig:
modified_response['nodeConfig'] = response.nodeConfig
if response.nodeCount:
modified_response['nodeCount'] = response.nodeCount
if response.parameters:
modified_response['parameters'] = response.parameters
if response.state:
modified_response['state'] = response.state
if response.updateTime:
modified_response['updateTime'] = response.updateTime
if response.zones:
modified_response['zones'] = response.zones
if response.maintenancePolicy:
modified_mw_policy = {}
modified_mw_policy['createTime'] = response.maintenancePolicy.createTime
modified_mw_policy['updateTime'] = response.maintenancePolicy.updateTime
mwlist = response.maintenancePolicy.weeklyMaintenanceWindow
modified_mwlist = []
for mw in mwlist:
item = {}
# convert seconds to minutes
duration_secs = int(mw.duration[:-1])
duration_mins = int(duration_secs/60)
item['day'] = mw.day
item['hour'] = mw.startTime.hours
item['duration'] = six.text_type(duration_mins) + ' minutes'
modified_mwlist.append(item)
modified_mw_policy['maintenanceWindow'] = modified_mwlist
modified_response['maintenancePolicy'] = modified_mw_policy
return modified_response
| [
"six.text_type"
] | [((2740, 2768), 'six.text_type', 'six.text_type', (['duration_mins'], {}), '(duration_mins)\n', (2753, 2768), False, 'import six\n')] |
#!/usr/bin/env python3
"""
Tests of ktrain text classification flows
"""
import sys
import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID";
os.environ["CUDA_VISIBLE_DEVICES"]="0"
sys.path.insert(0,'../..')
from unittest import TestCase, main, skip
import ktrain
def synthetic_multilabel():
import numpy as np
# data
X = [[1,0,0,0,0,0,0],
[1,2,0,0,0,0,0],
[3,0,0,0,0,0,0],
[3,4,0,0,0,0,0],
[2,0,0,0,0,0,0],
[3,0,0,0,0,0,0],
[4,0,0,0,0,0,0],
[2,3,0,0,0,0,0],
[1,2,3,0,0,0,0],
[1,2,3,4,0,0,0],
[0,0,0,0,0,0,0],
[1,1,2,3,0,0,0],
[2,3,3,4,0,0,0],
[4,4,1,1,2,0,0],
[1,2,3,3,3,3,3],
[2,4,2,4,2,0,0],
[1,3,3,3,0,0,0],
[4,4,0,0,0,0,0],
[3,3,0,0,0,0,0],
[1,1,4,0,0,0,0]]
Y = [[1,0,0,0],
[1,1,0,0],
[0,0,1,0],
[0,0,1,1],
[0,1,0,0],
[0,0,1,0],
[0,0,0,1],
[0,1,1,0],
[1,1,1,0],
[1,1,1,1],
[0,0,0,0],
[1,1,1,0],
[0,1,1,1],
[1,1,0,1],
[1,1,1,0],
[0,1,0,0],
[1,0,1,0],
[0,0,0,1],
[0,0,1,0],
[1,0,0,1]]
# model
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Embedding
from keras.layers import GlobalAveragePooling1D
import numpy as np
X = np.array(X)
Y = np.array(Y)
MAXLEN = 7
MAXFEATURES = 4
NUM_CLASSES = 4
model = Sequential()
model.add(Embedding(MAXFEATURES+1,
50,
input_length=MAXLEN))
model.add(GlobalAveragePooling1D())
model.add(Dense(NUM_CLASSES, activation='sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy'])
#model.fit(X, Y,
#batch_size=1,
#epochs=200,
#validation_data=(X, Y))
learner = ktrain.get_learner(model,
train_data=(X, Y),
val_data=(X, Y),
batch_size=1)
learner.lr_find()
hist = learner.fit(0.001, 200)
learner.view_top_losses(n=5)
learner.validate()
return hist
class TestMultilabel(TestCase):
def test_multilabel(self):
hist = synthetic_multilabel()
final_acc = hist.history['val_acc'][-1]
print('final_accuracy:%s' % (final_acc))
self.assertGreater(final_acc, 0.97)
if __name__ == "__main__":
main()
| [
"sys.path.insert",
"keras.layers.GlobalAveragePooling1D",
"keras.models.Sequential",
"ktrain.get_learner",
"numpy.array",
"keras.layers.Dense",
"unittest.main",
"keras.layers.Embedding"
] | [((179, 206), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""../.."""'], {}), "(0, '../..')\n", (194, 206), False, 'import sys\n'), ((1700, 1711), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (1708, 1711), True, 'import numpy as np\n'), ((1720, 1731), 'numpy.array', 'np.array', (['Y'], {}), '(Y)\n', (1728, 1731), True, 'import numpy as np\n'), ((1799, 1811), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (1809, 1811), False, 'from keras.models import Sequential\n'), ((2273, 2348), 'ktrain.get_learner', 'ktrain.get_learner', (['model'], {'train_data': '(X, Y)', 'val_data': '(X, Y)', 'batch_size': '(1)'}), '(model, train_data=(X, Y), val_data=(X, Y), batch_size=1)\n', (2291, 2348), False, 'import ktrain\n'), ((2857, 2863), 'unittest.main', 'main', ([], {}), '()\n', (2861, 2863), False, 'from unittest import TestCase, main, skip\n'), ((1826, 1877), 'keras.layers.Embedding', 'Embedding', (['(MAXFEATURES + 1)', '(50)'], {'input_length': 'MAXLEN'}), '(MAXFEATURES + 1, 50, input_length=MAXLEN)\n', (1835, 1877), False, 'from keras.layers import Embedding\n'), ((1939, 1963), 'keras.layers.GlobalAveragePooling1D', 'GlobalAveragePooling1D', ([], {}), '()\n', (1961, 1963), False, 'from keras.layers import GlobalAveragePooling1D\n'), ((1979, 2019), 'keras.layers.Dense', 'Dense', (['NUM_CLASSES'], {'activation': '"""sigmoid"""'}), "(NUM_CLASSES, activation='sigmoid')\n", (1984, 2019), False, 'from keras.layers import Dense\n')] |
"""
Keras implementation of Pix2Pix from <NAME>'s tutorial.
https://machinelearningmastery.com/how-to-develop-a-pix2pix-gan-for-image-to-image-translation/
"""
from keras.initializers import RandomNormal
from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU
from keras.models import Input, Model
from keras.optimizers import Adam
def get_discriminator_model(image_shape=(256,256,3)):
kernel_weights_init = RandomNormal(stddev=0.02)
input_src_image = Input(shape=image_shape)
input_target_image = Input(shape=image_shape)
# concatenate images channel-wise
merged = Concatenate()([input_src_image, input_target_image])
# C64
d = Conv2D(64, (4,4), strides=(2,2), padding='same', kernel_initializer=kernel_weights_init)(merged)
d = LeakyReLU(alpha=0.2)(d)
# C128
d = Conv2D(128, (4,4), strides=(2,2), padding='same', kernel_initializer=kernel_weights_init)(d)
d = BatchNormalization()(d)
d = LeakyReLU(alpha=0.2)(d)
# C256
d = Conv2D(256, (4,4), strides=(2,2), padding='same', kernel_initializer=kernel_weights_init)(d)
d = BatchNormalization()(d)
d = LeakyReLU(alpha=0.2)(d)
# C512
d = Conv2D(512, (4,4), strides=(2,2), padding='same', kernel_initializer=kernel_weights_init)(d)
d = BatchNormalization()(d)
d = LeakyReLU(alpha=0.2)(d)
# second last output layer
d = Conv2D(512, (4,4), padding='same', kernel_initializer=kernel_weights_init)(d)
d = BatchNormalization()(d)
d = LeakyReLU(alpha=0.2)(d)
# patch output
d = Conv2D(1, (4,4), padding='same', kernel_initializer=kernel_weights_init)(d)
patch_out = Activation('sigmoid')(d)
# define model
model = Model([input_src_image, input_target_image], patch_out, name='descriminator_model')
opt = Adam(lr=0.0002, beta_1=0.5)
model.compile(loss='binary_crossentropy', optimizer=opt, loss_weights=[0.5])
return model
def get_gan_model(g_model, d_model, image_shape=(256,256,3), L1_loss_lambda=100):
"""Combined generator and discriminator model. Used for updating the generator."""
d_model.trainable = False
input_src_image = Input(shape=image_shape)
gen_out = g_model(input_src_image)
# connect the source input and generator output to the discriminator input
dis_out = d_model([input_src_image, gen_out])
# src image as input, generated image and real/fake classification as output
model = Model(input_src_image, [dis_out, gen_out], name='gan_model')
opt = Adam(lr=0.0002, beta_1=0.5)
model.compile(loss=['binary_crossentropy', 'mae'], optimizer=opt, loss_weights=[1, L1_loss_lambda])
return model
def get_generator_model(image_shape=(256,256,3)):
kernel_weights_init = RandomNormal(stddev=0.02)
input_src_image = Input(shape=image_shape)
# encoder model
e1 = _encoder_block(input_src_image, 64, batchnorm=False)
e2 = _encoder_block(e1, 128)
e3 = _encoder_block(e2, 256)
e4 = _encoder_block(e3, 512)
e5 = _encoder_block(e4, 512)
e6 = _encoder_block(e5, 512)
e7 = _encoder_block(e6, 512)
# bottleneck, no batch norm and relu
b = Conv2D(512, (4,4), strides=(2,2), padding='same', kernel_initializer=kernel_weights_init)(e7)
b = Activation('relu')(b)
# decoder model
d1 = _decoder_block(b, e7, 512)
d2 = _decoder_block(d1, e6, 512)
d3 = _decoder_block(d2, e5, 512)
d4 = _decoder_block(d3, e4, 512, dropout=False)
d5 = _decoder_block(d4, e3, 256, dropout=False)
d6 = _decoder_block(d5, e2, 128, dropout=False)
d7 = _decoder_block(d6, e1, 64, dropout=False)
# output
g = Conv2DTranspose(3, (4,4), strides=(2,2), padding='same', kernel_initializer=kernel_weights_init)(d7)
out_image = Activation('tanh')(g)
# define model
model = Model(input_src_image, out_image, name='generator_model')
return model
def _decoder_block(layer_in, skip_in, n_filters, dropout=True):
kernel_weights_init = RandomNormal(stddev=0.02)
# add upsampling layer
g = Conv2DTranspose(n_filters, (4,4), strides=(2,2), padding='same', kernel_initializer=kernel_weights_init)(layer_in)
# add batch normalization
g = BatchNormalization()(g, training=True)
if dropout:
g = Dropout(0.5)(g, training=True)
# merge with skip connection
g = Concatenate()([g, skip_in])
# relu activation
g = Activation('relu')(g)
return g
def _encoder_block(layer_in, n_filters, batchnorm=True):
kernel_weights_init = RandomNormal(stddev=0.02)
# add downsampling layer
g = Conv2D(n_filters, (4,4), strides=(2,2), padding='same', kernel_initializer=kernel_weights_init)(layer_in)
if batchnorm:
g = BatchNormalization()(g, training=True)
# leaky relu activation
g = LeakyReLU(alpha=0.2)(g)
return g
| [
"keras.optimizers.Adam",
"keras.layers.Conv2D",
"keras.layers.LeakyReLU",
"keras.layers.Concatenate",
"keras.models.Model",
"keras.models.Input",
"keras.layers.Activation",
"keras.layers.Conv2DTranspose",
"keras.layers.BatchNormalization",
"keras.layers.Dropout",
"keras.initializers.RandomNormal... | [((473, 498), 'keras.initializers.RandomNormal', 'RandomNormal', ([], {'stddev': '(0.02)'}), '(stddev=0.02)\n', (485, 498), False, 'from keras.initializers import RandomNormal\n'), ((521, 545), 'keras.models.Input', 'Input', ([], {'shape': 'image_shape'}), '(shape=image_shape)\n', (526, 545), False, 'from keras.models import Input, Model\n'), ((571, 595), 'keras.models.Input', 'Input', ([], {'shape': 'image_shape'}), '(shape=image_shape)\n', (576, 595), False, 'from keras.models import Input, Model\n'), ((1734, 1822), 'keras.models.Model', 'Model', (['[input_src_image, input_target_image]', 'patch_out'], {'name': '"""descriminator_model"""'}), "([input_src_image, input_target_image], patch_out, name=\n 'descriminator_model')\n", (1739, 1822), False, 'from keras.models import Input, Model\n'), ((1828, 1855), 'keras.optimizers.Adam', 'Adam', ([], {'lr': '(0.0002)', 'beta_1': '(0.5)'}), '(lr=0.0002, beta_1=0.5)\n', (1832, 1855), False, 'from keras.optimizers import Adam\n'), ((2177, 2201), 'keras.models.Input', 'Input', ([], {'shape': 'image_shape'}), '(shape=image_shape)\n', (2182, 2201), False, 'from keras.models import Input, Model\n'), ((2464, 2524), 'keras.models.Model', 'Model', (['input_src_image', '[dis_out, gen_out]'], {'name': '"""gan_model"""'}), "(input_src_image, [dis_out, gen_out], name='gan_model')\n", (2469, 2524), False, 'from keras.models import Input, Model\n'), ((2535, 2562), 'keras.optimizers.Adam', 'Adam', ([], {'lr': '(0.0002)', 'beta_1': '(0.5)'}), '(lr=0.0002, beta_1=0.5)\n', (2539, 2562), False, 'from keras.optimizers import Adam\n'), ((2762, 2787), 'keras.initializers.RandomNormal', 'RandomNormal', ([], {'stddev': '(0.02)'}), '(stddev=0.02)\n', (2774, 2787), False, 'from keras.initializers import RandomNormal\n'), ((2810, 2834), 'keras.models.Input', 'Input', ([], {'shape': 'image_shape'}), '(shape=image_shape)\n', (2815, 2834), False, 'from keras.models import Input, Model\n'), ((3821, 3878), 'keras.models.Model', 'Model', (['input_src_image', 'out_image'], {'name': '"""generator_model"""'}), "(input_src_image, out_image, name='generator_model')\n", (3826, 3878), False, 'from keras.models import Input, Model\n'), ((3988, 4013), 'keras.initializers.RandomNormal', 'RandomNormal', ([], {'stddev': '(0.02)'}), '(stddev=0.02)\n', (4000, 4013), False, 'from keras.initializers import RandomNormal\n'), ((4519, 4544), 'keras.initializers.RandomNormal', 'RandomNormal', ([], {'stddev': '(0.02)'}), '(stddev=0.02)\n', (4531, 4544), False, 'from keras.initializers import RandomNormal\n'), ((648, 661), 'keras.layers.Concatenate', 'Concatenate', ([], {}), '()\n', (659, 661), False, 'from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU\n'), ((719, 814), 'keras.layers.Conv2D', 'Conv2D', (['(64)', '(4, 4)'], {'strides': '(2, 2)', 'padding': '"""same"""', 'kernel_initializer': 'kernel_weights_init'}), "(64, (4, 4), strides=(2, 2), padding='same', kernel_initializer=\n kernel_weights_init)\n", (725, 814), False, 'from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU\n'), ((824, 844), 'keras.layers.LeakyReLU', 'LeakyReLU', ([], {'alpha': '(0.2)'}), '(alpha=0.2)\n', (833, 844), False, 'from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU\n'), ((867, 963), 'keras.layers.Conv2D', 'Conv2D', (['(128)', '(4, 4)'], {'strides': '(2, 2)', 'padding': '"""same"""', 'kernel_initializer': 'kernel_weights_init'}), "(128, (4, 4), strides=(2, 2), padding='same', kernel_initializer=\n kernel_weights_init)\n", (873, 963), False, 'from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU\n'), ((968, 988), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (986, 988), False, 'from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU\n'), ((1000, 1020), 'keras.layers.LeakyReLU', 'LeakyReLU', ([], {'alpha': '(0.2)'}), '(alpha=0.2)\n', (1009, 1020), False, 'from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU\n'), ((1043, 1139), 'keras.layers.Conv2D', 'Conv2D', (['(256)', '(4, 4)'], {'strides': '(2, 2)', 'padding': '"""same"""', 'kernel_initializer': 'kernel_weights_init'}), "(256, (4, 4), strides=(2, 2), padding='same', kernel_initializer=\n kernel_weights_init)\n", (1049, 1139), False, 'from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU\n'), ((1144, 1164), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (1162, 1164), False, 'from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU\n'), ((1176, 1196), 'keras.layers.LeakyReLU', 'LeakyReLU', ([], {'alpha': '(0.2)'}), '(alpha=0.2)\n', (1185, 1196), False, 'from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU\n'), ((1219, 1315), 'keras.layers.Conv2D', 'Conv2D', (['(512)', '(4, 4)'], {'strides': '(2, 2)', 'padding': '"""same"""', 'kernel_initializer': 'kernel_weights_init'}), "(512, (4, 4), strides=(2, 2), padding='same', kernel_initializer=\n kernel_weights_init)\n", (1225, 1315), False, 'from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU\n'), ((1320, 1340), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (1338, 1340), False, 'from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU\n'), ((1352, 1372), 'keras.layers.LeakyReLU', 'LeakyReLU', ([], {'alpha': '(0.2)'}), '(alpha=0.2)\n', (1361, 1372), False, 'from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU\n'), ((1415, 1490), 'keras.layers.Conv2D', 'Conv2D', (['(512)', '(4, 4)'], {'padding': '"""same"""', 'kernel_initializer': 'kernel_weights_init'}), "(512, (4, 4), padding='same', kernel_initializer=kernel_weights_init)\n", (1421, 1490), False, 'from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU\n'), ((1501, 1521), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (1519, 1521), False, 'from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU\n'), ((1533, 1553), 'keras.layers.LeakyReLU', 'LeakyReLU', ([], {'alpha': '(0.2)'}), '(alpha=0.2)\n', (1542, 1553), False, 'from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU\n'), ((1585, 1658), 'keras.layers.Conv2D', 'Conv2D', (['(1)', '(4, 4)'], {'padding': '"""same"""', 'kernel_initializer': 'kernel_weights_init'}), "(1, (4, 4), padding='same', kernel_initializer=kernel_weights_init)\n", (1591, 1658), False, 'from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU\n'), ((1677, 1698), 'keras.layers.Activation', 'Activation', (['"""sigmoid"""'], {}), "('sigmoid')\n", (1687, 1698), False, 'from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU\n'), ((3166, 3262), 'keras.layers.Conv2D', 'Conv2D', (['(512)', '(4, 4)'], {'strides': '(2, 2)', 'padding': '"""same"""', 'kernel_initializer': 'kernel_weights_init'}), "(512, (4, 4), strides=(2, 2), padding='same', kernel_initializer=\n kernel_weights_init)\n", (3172, 3262), False, 'from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU\n'), ((3268, 3286), 'keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (3278, 3286), False, 'from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU\n'), ((3650, 3752), 'keras.layers.Conv2DTranspose', 'Conv2DTranspose', (['(3)', '(4, 4)'], {'strides': '(2, 2)', 'padding': '"""same"""', 'kernel_initializer': 'kernel_weights_init'}), "(3, (4, 4), strides=(2, 2), padding='same',\n kernel_initializer=kernel_weights_init)\n", (3665, 3752), False, 'from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU\n'), ((3767, 3785), 'keras.layers.Activation', 'Activation', (['"""tanh"""'], {}), "('tanh')\n", (3777, 3785), False, 'from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU\n'), ((4049, 4159), 'keras.layers.Conv2DTranspose', 'Conv2DTranspose', (['n_filters', '(4, 4)'], {'strides': '(2, 2)', 'padding': '"""same"""', 'kernel_initializer': 'kernel_weights_init'}), "(n_filters, (4, 4), strides=(2, 2), padding='same',\n kernel_initializer=kernel_weights_init)\n", (4064, 4159), False, 'from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU\n'), ((4202, 4222), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (4220, 4222), False, 'from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU\n'), ((4341, 4354), 'keras.layers.Concatenate', 'Concatenate', ([], {}), '()\n', (4352, 4354), False, 'from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU\n'), ((4399, 4417), 'keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (4409, 4417), False, 'from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU\n'), ((4582, 4683), 'keras.layers.Conv2D', 'Conv2D', (['n_filters', '(4, 4)'], {'strides': '(2, 2)', 'padding': '"""same"""', 'kernel_initializer': 'kernel_weights_init'}), "(n_filters, (4, 4), strides=(2, 2), padding='same',\n kernel_initializer=kernel_weights_init)\n", (4588, 4683), False, 'from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU\n'), ((4793, 4813), 'keras.layers.LeakyReLU', 'LeakyReLU', ([], {'alpha': '(0.2)'}), '(alpha=0.2)\n', (4802, 4813), False, 'from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU\n'), ((4269, 4281), 'keras.layers.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (4276, 4281), False, 'from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU\n'), ((4718, 4738), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (4736, 4738), False, 'from keras.layers import Activation, BatchNormalization, Concatenate, Conv2D, Conv2DTranspose, Dropout, LeakyReLU\n')] |
import lx, lxifc, lxu.command, tagger
CMD_NAME = tagger.CMD_PTAG_QUICK_SELECT_POPUP
class CommandClass(tagger.CommanderClass):
#_commander_default_values = []
def commander_arguments(self):
return [
{
'name': tagger.TAGTYPE,
'label': tagger.LABEL_TAGTYPE,
'datatype': 'string',
'default': tagger.MATERIAL,
'values_list_type': 'popup',
'values_list': tagger.POPUPS_TAGTYPES,
'flags': []
}, {
'name': tagger.TAG,
'label': self.tag_label,
'datatype': 'string',
'default': '',
'values_list_type': 'popup',
'values_list': self.list_tags,
'flags': ['query'],
}
]
def commander_execute(self, msg, flags):
if not self.commander_arg_value(1):
return
tagType = self.commander_arg_value(0, tagger.MATERIAL)
tag = self.commander_arg_value(1)
args = tagger.build_arg_string({
tagger.TAGTYPE: tagType,
tagger.TAG: tag
})
lx.eval(tagger.CMD_SELECT_ALL_BY_DIALOG + args)
notifier = tagger.Notifier()
notifier.Notify(lx.symbol.fCMDNOTIFY_DATATYPE)
def tag_label(self):
tagType = self.commander_arg_value(0, tagger.MATERIAL)
label = tagger.convert_to_tagType_label(tagType)
return "%s %s" % (tagger.LABEL_SELECT_TAG, label)
def list_tags(self):
tagType = self.commander_arg_value(0, tagger.MATERIAL)
i_POLYTAG = tagger.convert_to_iPOLYTAG(tagType)
tags = tagger.scene.all_tags_by_type(i_POLYTAG)
return tags
def commander_notifiers(self):
return [('notifier.editAction',''), ("select.event", "item +ldt"), ("tagger.notifier", "")]
lx.bless(CommandClass, CMD_NAME)
| [
"lx.eval",
"tagger.convert_to_iPOLYTAG",
"tagger.scene.all_tags_by_type",
"tagger.build_arg_string",
"tagger.convert_to_tagType_label",
"lx.bless",
"tagger.Notifier"
] | [((1966, 1998), 'lx.bless', 'lx.bless', (['CommandClass', 'CMD_NAME'], {}), '(CommandClass, CMD_NAME)\n', (1974, 1998), False, 'import lx, lxifc, lxu.command, tagger\n'), ((1148, 1215), 'tagger.build_arg_string', 'tagger.build_arg_string', (['{tagger.TAGTYPE: tagType, tagger.TAG: tag}'], {}), '({tagger.TAGTYPE: tagType, tagger.TAG: tag})\n', (1171, 1215), False, 'import lx, lxifc, lxu.command, tagger\n'), ((1259, 1306), 'lx.eval', 'lx.eval', (['(tagger.CMD_SELECT_ALL_BY_DIALOG + args)'], {}), '(tagger.CMD_SELECT_ALL_BY_DIALOG + args)\n', (1266, 1306), False, 'import lx, lxifc, lxu.command, tagger\n'), ((1327, 1344), 'tagger.Notifier', 'tagger.Notifier', ([], {}), '()\n', (1342, 1344), False, 'import lx, lxifc, lxu.command, tagger\n'), ((1505, 1545), 'tagger.convert_to_tagType_label', 'tagger.convert_to_tagType_label', (['tagType'], {}), '(tagType)\n', (1536, 1545), False, 'import lx, lxifc, lxu.command, tagger\n'), ((1714, 1749), 'tagger.convert_to_iPOLYTAG', 'tagger.convert_to_iPOLYTAG', (['tagType'], {}), '(tagType)\n', (1740, 1749), False, 'import lx, lxifc, lxu.command, tagger\n'), ((1766, 1806), 'tagger.scene.all_tags_by_type', 'tagger.scene.all_tags_by_type', (['i_POLYTAG'], {}), '(i_POLYTAG)\n', (1795, 1806), False, 'import lx, lxifc, lxu.command, tagger\n')] |
import tensorflow as tf
from tensorflow.keras.applications import MobileNetV2
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D, Add,\
GlobalMaxPooling2D
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
def MobileNetV2_avg_max(input_shape, num_classes):
base_model = MobileNetV2(weights='imagenet', include_top=False, input_shape=input_shape)
for layer in base_model.layers:
layer.trainable = False
x = GlobalAveragePooling2D()(base_model.output)
x = Dense(32, activation='relu')(x)
# x = Dense(128, activation='relu')(x)
predictions = Dense(num_classes, activation="softmax")(x)
# y = GlobalMaxPooling2D()(base_model.output)
# y = Dense(32, activation='relu')(y)
# y = Dense(128, activation='relu')(y)
# concatenated = Add()([x,y])
# concatenated = Concatenate()([x,y])
# concatenated = Dense(32, activation='relu')(concatenated)
# predictions = Dense(classes, activation="softmax")(concatenated)
model = Model(inputs=base_model.input, outputs=predictions)
optimizer = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)
model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])
return model | [
"tensorflow.keras.optimizers.Adam",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.models.Model",
"tensorflow.keras.applications.MobileNetV2",
"tensorflow.keras.layers.GlobalAveragePooling2D"
] | [((330, 405), 'tensorflow.keras.applications.MobileNetV2', 'MobileNetV2', ([], {'weights': '"""imagenet"""', 'include_top': '(False)', 'input_shape': 'input_shape'}), "(weights='imagenet', include_top=False, input_shape=input_shape)\n", (341, 405), False, 'from tensorflow.keras.applications import MobileNetV2\n'), ((1035, 1086), 'tensorflow.keras.models.Model', 'Model', ([], {'inputs': 'base_model.input', 'outputs': 'predictions'}), '(inputs=base_model.input, outputs=predictions)\n', (1040, 1086), False, 'from tensorflow.keras.models import Model\n'), ((1104, 1189), 'tensorflow.keras.optimizers.Adam', 'Adam', ([], {'lr': '(0.001)', 'beta_1': '(0.9)', 'beta_2': '(0.999)', 'epsilon': 'None', 'decay': '(0.0)', 'amsgrad': '(False)'}), '(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False\n )\n', (1108, 1189), False, 'from tensorflow.keras.optimizers import Adam\n'), ((483, 507), 'tensorflow.keras.layers.GlobalAveragePooling2D', 'GlobalAveragePooling2D', ([], {}), '()\n', (505, 507), False, 'from tensorflow.keras.layers import Dense, GlobalAveragePooling2D, Add, GlobalMaxPooling2D\n'), ((535, 563), 'tensorflow.keras.layers.Dense', 'Dense', (['(32)'], {'activation': '"""relu"""'}), "(32, activation='relu')\n", (540, 563), False, 'from tensorflow.keras.layers import Dense, GlobalAveragePooling2D, Add, GlobalMaxPooling2D\n'), ((628, 668), 'tensorflow.keras.layers.Dense', 'Dense', (['num_classes'], {'activation': '"""softmax"""'}), "(num_classes, activation='softmax')\n", (633, 668), False, 'from tensorflow.keras.layers import Dense, GlobalAveragePooling2D, Add, GlobalMaxPooling2D\n')] |
import json
import pytest
from asynctest import TestCase as AsyncTestCase, mock as async_mock
from copy import deepcopy
from pathlib import Path
from shutil import rmtree
import base58
from ....config.injection_context import InjectionContext
from ....storage.base import BaseStorage
from ....storage.basic import BasicStorage
from ...error import RevocationError
from ..revocation_registry import RevocationRegistry
from .. import revocation_registry as test_module
TEST_DID = "FkjWznKwA4N1JEp2iPiKPG"
CRED_DEF_ID = f"{TEST_DID}:3:CL:12:tag1"
REV_REG_ID = f"{TEST_DID}:4:{CRED_DEF_ID}:CL_ACCUM:tag1"
TAILS_DIR = "/tmp/indy/revocation/tails_files"
TAILS_HASH = "8UW1Sz5cqoUnK9hqQk7nvtKK65t7Chu3ui866J23sFyJ"
TAILS_LOCAL = f"{TAILS_DIR}/{TAILS_HASH}"
REV_REG_DEF = {
"ver": "1.0",
"id": REV_REG_ID,
"revocDefType": "CL_ACCUM",
"tag": "tag1",
"credDefId": CRED_DEF_ID,
"value": {
"issuanceType": "ISSUANCE_ON_DEMAND",
"maxCredNum": 5,
"publicKeys": {
"accumKey": {
"z": "1 21C2C33125242BF80E85DECC0DD7D81197C2CA827179724081623CEBB03C3DBE 1 0ACA5C9CDBAF5348E8F4783AB5FFBDA480C5075F549BBD53A4D71613C584C97B 1 0EB5326BF28738CEA8863A1F6783AEA97847E7C42C7713C356C8FCF8B8187723 1 174D9052BAABB63B1D6CDC4C468CC00095BF9C7ECCEC941B3B1493EF57644237 1 18A38A66728EF7C7E206A1C15B052848E4AC6281878A7957C54C8FFFFC96A0D7 1 1F9414C188301F4A1DBCD16D6B4B68B27072034F1FA12B6437E5FB174D819DAB 1 094C0D112DD652D1B224FFDC79679CCB08D4BDC2820C354C07B9F55570D0E79E 1 25066D0C941E0090A780B0E3468FAB8529B3C3671A7E93CC57CE1D563B856A23 1 01DF5AAC4322FE2A0AC2BEF491E4FE8B438C79C876B960F9C64FC893A01164BA 1 21E5D8CAA97DD06498C845E544C75D5843B729CC3B1FFCB26BB3380146E4A468 1 2315EAAACFB957A56F75DB8856350D193F62D895E37B8C258F690AA97235D9C2 1 1A763EC7BEC67E521A69A0C4CC482FF98C9D7FE49DFB6EEC77978614C2FE91C8"
}
},
"tailsHash": TAILS_HASH,
"tailsLocation": TAILS_LOCAL,
},
}
class TestRevocationRegistry(AsyncTestCase):
def setUp(self):
self.context = InjectionContext(
settings={"holder.revocation.tails_files.path": TAILS_DIR},
enforce_typing=False,
)
self.storage = BasicStorage()
self.context.injector.bind_instance(BaseStorage, self.storage)
def tearDown(self):
rmtree(TAILS_DIR, ignore_errors=True)
async def test_init(self):
rev_reg = RevocationRegistry()
assert str(rev_reg).startswith("<RevocationRegistry")
for public in (True, False):
rev_reg = RevocationRegistry.from_definition(REV_REG_DEF, public_def=public)
if public:
assert not rev_reg.tails_local_path
assert rev_reg.tails_public_uri
else:
assert rev_reg.tails_local_path
assert not rev_reg.tails_public_uri
async def test_temp_dir(self):
assert RevocationRegistry.get_temp_dir()
async def test_properties(self):
rev_reg = RevocationRegistry.from_definition(REV_REG_DEF, public_def=False)
assert rev_reg.cred_def_id == REV_REG_DEF["credDefId"]
assert rev_reg.issuer_did == TEST_DID
assert rev_reg.max_creds == 5
assert rev_reg.reg_def_type == "CL_ACCUM"
assert rev_reg.registry_id == REV_REG_ID
assert rev_reg.tag == "tag1"
assert rev_reg.tails_hash == "8UW1Sz5cqoUnK9hqQk7nvtKK65t7Chu3ui866J23sFyJ"
rev_reg.tails_local_path = "dummy"
assert rev_reg.tails_local_path == "dummy"
rev_reg.tails_public_uri = "dummy"
assert rev_reg.tails_public_uri == "dummy"
return rev_reg.reg_def == REV_REG_DEF
async def test_tails_local_path(self):
rr_def_public = deepcopy(REV_REG_DEF)
rr_def_public["value"]["tailsLocation"] = "http://sample.ca:8088/path"
rev_reg_pub = RevocationRegistry.from_definition(rr_def_public, public_def=True)
assert rev_reg_pub.get_receiving_tails_local_path(self.context) == TAILS_LOCAL
rev_reg_loc = RevocationRegistry.from_definition(REV_REG_DEF, public_def=False)
assert rev_reg_loc.get_receiving_tails_local_path(self.context) == TAILS_LOCAL
with async_mock.patch.object(Path, "is_file", autospec=True) as mock_is_file:
mock_is_file.return_value = True
assert (
await rev_reg_loc.get_or_fetch_local_tails_path(self.context)
== TAILS_LOCAL
)
rmtree(TAILS_DIR, ignore_errors=True)
assert not rev_reg_loc.has_local_tails_file(self.context)
async def test_retrieve_tails(self):
rev_reg = RevocationRegistry.from_definition(REV_REG_DEF, public_def=False)
with self.assertRaises(RevocationError) as x_retrieve:
await rev_reg.retrieve_tails(self.context)
assert x_retrieve.message.contains("Tails file public URI is empty")
rr_def_public = deepcopy(REV_REG_DEF)
rr_def_public["value"]["tailsLocation"] = "http://sample.ca:8088/path"
rev_reg = RevocationRegistry.from_definition(rr_def_public, public_def=True)
more_magic = async_mock.MagicMock()
with async_mock.patch.object(
test_module, "Session", autospec=True
) as mock_session:
mock_session.return_value.__enter__ = async_mock.MagicMock(
return_value=more_magic
)
more_magic.get = async_mock.MagicMock(
side_effect=test_module.RequestException("Not this time")
)
with self.assertRaises(RevocationError) as x_retrieve:
await rev_reg.retrieve_tails(self.context)
assert x_retrieve.message.contains("Error retrieving tails file")
rmtree(TAILS_DIR, ignore_errors=True)
more_magic = async_mock.MagicMock()
with async_mock.patch.object(
test_module, "Session", autospec=True
) as mock_session:
mock_session.return_value.__enter__ = async_mock.MagicMock(
return_value=more_magic
)
more_magic.get = async_mock.MagicMock(
return_value=async_mock.MagicMock(
iter_content=async_mock.MagicMock(
side_effect=[(b"abcd1234",), (b"",)]
)
)
)
with self.assertRaises(RevocationError) as x_retrieve:
await rev_reg.retrieve_tails(self.context)
assert x_retrieve.message.contains(
"The hash of the downloaded tails file does not match."
)
rmtree(TAILS_DIR, ignore_errors=True)
more_magic = async_mock.MagicMock()
with async_mock.patch.object(
test_module, "Session", autospec=True
) as mock_session, async_mock.patch.object(
base58, "b58encode", async_mock.MagicMock()
) as mock_b58enc, async_mock.patch.object(
Path, "is_file", autospec=True
) as mock_is_file:
mock_session.return_value.__enter__ = async_mock.MagicMock(
return_value=more_magic
)
more_magic.get = async_mock.MagicMock(
return_value=async_mock.MagicMock(
iter_content=async_mock.MagicMock(
side_effect=[(b"abcd1234",), (b"",)]
)
)
)
mock_is_file.return_value = False
mock_b58enc.return_value = async_mock.MagicMock(
decode=async_mock.MagicMock(return_value=TAILS_HASH)
)
await rev_reg.get_or_fetch_local_tails_path(self.context)
rmtree(TAILS_DIR, ignore_errors=True)
| [
"asynctest.mock.MagicMock",
"asynctest.mock.patch.object",
"copy.deepcopy",
"shutil.rmtree"
] | [((2332, 2369), 'shutil.rmtree', 'rmtree', (['TAILS_DIR'], {'ignore_errors': '(True)'}), '(TAILS_DIR, ignore_errors=True)\n', (2338, 2369), False, 'from shutil import rmtree\n'), ((3748, 3769), 'copy.deepcopy', 'deepcopy', (['REV_REG_DEF'], {}), '(REV_REG_DEF)\n', (3756, 3769), False, 'from copy import deepcopy\n'), ((4488, 4525), 'shutil.rmtree', 'rmtree', (['TAILS_DIR'], {'ignore_errors': '(True)'}), '(TAILS_DIR, ignore_errors=True)\n', (4494, 4525), False, 'from shutil import rmtree\n'), ((4942, 4963), 'copy.deepcopy', 'deepcopy', (['REV_REG_DEF'], {}), '(REV_REG_DEF)\n', (4950, 4963), False, 'from copy import deepcopy\n'), ((5150, 5172), 'asynctest.mock.MagicMock', 'async_mock.MagicMock', ([], {}), '()\n', (5170, 5172), True, 'from asynctest import TestCase as AsyncTestCase, mock as async_mock\n'), ((5835, 5857), 'asynctest.mock.MagicMock', 'async_mock.MagicMock', ([], {}), '()\n', (5855, 5857), True, 'from asynctest import TestCase as AsyncTestCase, mock as async_mock\n'), ((6717, 6739), 'asynctest.mock.MagicMock', 'async_mock.MagicMock', ([], {}), '()\n', (6737, 6739), True, 'from asynctest import TestCase as AsyncTestCase, mock as async_mock\n'), ((4216, 4271), 'asynctest.mock.patch.object', 'async_mock.patch.object', (['Path', '"""is_file"""'], {'autospec': '(True)'}), "(Path, 'is_file', autospec=True)\n", (4239, 4271), True, 'from asynctest import TestCase as AsyncTestCase, mock as async_mock\n'), ((5186, 5248), 'asynctest.mock.patch.object', 'async_mock.patch.object', (['test_module', '"""Session"""'], {'autospec': '(True)'}), "(test_module, 'Session', autospec=True)\n", (5209, 5248), True, 'from asynctest import TestCase as AsyncTestCase, mock as async_mock\n'), ((5338, 5383), 'asynctest.mock.MagicMock', 'async_mock.MagicMock', ([], {'return_value': 'more_magic'}), '(return_value=more_magic)\n', (5358, 5383), True, 'from asynctest import TestCase as AsyncTestCase, mock as async_mock\n'), ((5775, 5812), 'shutil.rmtree', 'rmtree', (['TAILS_DIR'], {'ignore_errors': '(True)'}), '(TAILS_DIR, ignore_errors=True)\n', (5781, 5812), False, 'from shutil import rmtree\n'), ((5871, 5933), 'asynctest.mock.patch.object', 'async_mock.patch.object', (['test_module', '"""Session"""'], {'autospec': '(True)'}), "(test_module, 'Session', autospec=True)\n", (5894, 5933), True, 'from asynctest import TestCase as AsyncTestCase, mock as async_mock\n'), ((6023, 6068), 'asynctest.mock.MagicMock', 'async_mock.MagicMock', ([], {'return_value': 'more_magic'}), '(return_value=more_magic)\n', (6043, 6068), True, 'from asynctest import TestCase as AsyncTestCase, mock as async_mock\n'), ((6657, 6694), 'shutil.rmtree', 'rmtree', (['TAILS_DIR'], {'ignore_errors': '(True)'}), '(TAILS_DIR, ignore_errors=True)\n', (6663, 6694), False, 'from shutil import rmtree\n'), ((6753, 6815), 'asynctest.mock.patch.object', 'async_mock.patch.object', (['test_module', '"""Session"""'], {'autospec': '(True)'}), "(test_module, 'Session', autospec=True)\n", (6776, 6815), True, 'from asynctest import TestCase as AsyncTestCase, mock as async_mock\n'), ((6962, 7017), 'asynctest.mock.patch.object', 'async_mock.patch.object', (['Path', '"""is_file"""'], {'autospec': '(True)'}), "(Path, 'is_file', autospec=True)\n", (6985, 7017), True, 'from asynctest import TestCase as AsyncTestCase, mock as async_mock\n'), ((7107, 7152), 'asynctest.mock.MagicMock', 'async_mock.MagicMock', ([], {'return_value': 'more_magic'}), '(return_value=more_magic)\n', (7127, 7152), True, 'from asynctest import TestCase as AsyncTestCase, mock as async_mock\n'), ((7729, 7766), 'shutil.rmtree', 'rmtree', (['TAILS_DIR'], {'ignore_errors': '(True)'}), '(TAILS_DIR, ignore_errors=True)\n', (7735, 7766), False, 'from shutil import rmtree\n'), ((6913, 6935), 'asynctest.mock.MagicMock', 'async_mock.MagicMock', ([], {}), '()\n', (6933, 6935), True, 'from asynctest import TestCase as AsyncTestCase, mock as async_mock\n'), ((7586, 7631), 'asynctest.mock.MagicMock', 'async_mock.MagicMock', ([], {'return_value': 'TAILS_HASH'}), '(return_value=TAILS_HASH)\n', (7606, 7631), True, 'from asynctest import TestCase as AsyncTestCase, mock as async_mock\n'), ((6234, 6292), 'asynctest.mock.MagicMock', 'async_mock.MagicMock', ([], {'side_effect': "[(b'abcd1234',), (b'',)]"}), "(side_effect=[(b'abcd1234',), (b'',)])\n", (6254, 6292), True, 'from asynctest import TestCase as AsyncTestCase, mock as async_mock\n'), ((7318, 7376), 'asynctest.mock.MagicMock', 'async_mock.MagicMock', ([], {'side_effect': "[(b'abcd1234',), (b'',)]"}), "(side_effect=[(b'abcd1234',), (b'',)])\n", (7338, 7376), True, 'from asynctest import TestCase as AsyncTestCase, mock as async_mock\n')] |
#!/usr/bin/env python
import os
import sys
from optparse import OptionParser
def parse_args():
parser = OptionParser()
parser.add_option('-s', '--settings', help='Define settings.')
parser.add_option('-t', '--unittest', help='Define which test to run. Default all.')
options, args = parser.parse_args()
if not options.settings:
parser.print_help()
sys.exit(1)
if not options.unittest:
options.unittest = ['aggregation']
return options
def get_runner(settings_module):
'''
Asks Django for the TestRunner defined in settings or the default one.
'''
os.environ['DJANGO_SETTINGS_MODULE'] = settings_module
import django
from django.test.utils import get_runner
from django.conf import settings
if hasattr(django, 'setup'):
django.setup()
return get_runner(settings)
def runtests():
options = parse_args()
TestRunner = get_runner(options.settings)
runner = TestRunner(verbosity=1, interactive=True, failfast=False)
sys.exit(runner.run_tests([]))
if __name__ == '__main__':
runtests()
| [
"django.setup",
"optparse.OptionParser",
"django.test.utils.get_runner",
"sys.exit"
] | [((111, 125), 'optparse.OptionParser', 'OptionParser', ([], {}), '()\n', (123, 125), False, 'from optparse import OptionParser\n'), ((848, 868), 'django.test.utils.get_runner', 'get_runner', (['settings'], {}), '(settings)\n', (858, 868), False, 'from django.test.utils import get_runner\n'), ((931, 959), 'django.test.utils.get_runner', 'get_runner', (['options.settings'], {}), '(options.settings)\n', (941, 959), False, 'from django.test.utils import get_runner\n'), ((388, 399), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (396, 399), False, 'import sys\n'), ((821, 835), 'django.setup', 'django.setup', ([], {}), '()\n', (833, 835), False, 'import django\n')] |
import os
def Usage():
print("Commands : ") #输出帮助信息
print("+----------------------------------------------------+")
print("|Num|Command | Describe |")
print("+----------------------------------------------------+")
print("|0. | help | Get Usage(This Page) |")
print("|1. | shell | Get into the Single Shell |")
print("|2. | send | Send a Command to All servers |")
print("|3. | down | Download the Source code |")
print("|4. | upload | Upload a file to the website |")
print("|5. | log | Download the log of WebServer |")
print("|6. | script | Get the Attack Script list |")
print("+----------------------------------------------------+")
print("You Can type Num or Command to enter the Function which you want,Input 'exit' to break.\n")
def Print_Welcome_Message(): #输出欢迎信息
print("+---------------------------------------+")
print("| AWD Framework |")
print("+---------------------------------------+")
print("| Made By AdianGg |")
print("| AdianGg's Blog:www.e-wolf.top |")
print("| WgpSec:www.wgpsec.org |")
print("| Have Fun |")
print("+---------------------------------------+")
def Scriptlist(): #输出Script目录下所有文件列表
print("All The Scipts from Internet!")
for root,dirs,files in os.walk(r"Scripts/"):
for file in files:
print(os.path.join(root,file))
| [
"os.path.join",
"os.walk"
] | [((1580, 1599), 'os.walk', 'os.walk', (['"""Scripts/"""'], {}), "('Scripts/')\n", (1587, 1599), False, 'import os\n'), ((1632, 1656), 'os.path.join', 'os.path.join', (['root', 'file'], {}), '(root, file)\n', (1644, 1656), False, 'import os\n')] |
import smbus
class AtlasOEM(object):
DEFAULT_BUS = 1
def __init__(self, address, name = "", bus=None):
self._address = address
self.bus = smbus.SMBus(bus or self.DEFAULT_BUS)
self._name = name
def read_byte(self, reg):
return self.bus.read_byte_data(self._address, reg)
def read_16(self, reg):
data = 0
data = self.bus.read_byte_data(self._address, reg)<<8
data |= self.bus.read_byte(self._address)
return data
def read_32u(self, reg):
data = 0
data = self.bus.read_byte_data(self._address, reg)<<24
data |= self.bus.read_byte(self._address)<<16
data |= self.bus.read_byte(self._address)<<8
data |= self.bus.read_byte(self._address)
return data
def read_32(self, reg):
data = 0
data = self.bus.read_byte_data(self._address, reg)<<24
data |= self.bus.read_byte(self._address)<<16
data |= self.bus.read_byte(self._address)<<8
data |= self.bus.read_byte(self._address)
# python requires that we do it old school?
if((data >> 31) & 0x01):
return -((~data & 0xFFFFFFFF) + 1)
else:
return data
def write_byte(self, reg, val):
self.bus.write_byte_data(self._address, reg, val)
def write_16(self, reg, val):
self.bus.write_byte_data(self._address, reg, (val>>8) & 0xFF)
self.bus.write_byte_data(self._address, reg+1,(val) & 0xFF)
def write_32(self, reg, val):
self.bus.write_byte_data(self._address, reg, ((val>>24) & 0xFF))
self.bus.write_byte_data(self._address, reg+1, (val>>16) & 0xFF)
self.bus.write_byte_data(self._address, reg+2, (val>>8) & 0xFF)
self.bus.write_byte_data(self._address, reg+3,(val) & 0xFF)
def get_name(self):
return self._name
def read_device_data(self):
return self.read_byte(0)
def read_firmware_version(self):
return self.read_byte(1)
#address change regs here
def read_interrrupt_control(self):
return self.read_byte(0x04)
def write_interrupt_control(self, val):
self.write_byte(0x04, val)
def read_led(self):
return self.read_byte(0x05)
def write_led(self, val):
self.write_byte(0x05, val)
def read_active_hibernate(self):
return self.read_byte(0x06)
def write_active_hibernate(self, val):
self.write_byte(0x06, val) | [
"smbus.SMBus"
] | [((168, 204), 'smbus.SMBus', 'smbus.SMBus', (['(bus or self.DEFAULT_BUS)'], {}), '(bus or self.DEFAULT_BUS)\n', (179, 204), False, 'import smbus\n')] |
import threading
import os
import obd
from random import random
from pathlib import Path
conn = obd.OBD()
connect = obd.Async(fast=False)
speed=""
fueli=""
tem =""
def get_temp(t):
if not t.is_null():
tem=str(t.value)
if t.is_null():
tem=str(0)
def get_fuel(f):
if not f.is_null():
fueli=str(f.value)
if f.is_null():
fueli= str(0)
def get_speed(s):
if not s.is_null():
speed = str(s.value)
if s.is_null():
speed = str(0)
connect.watch(obd.commands.INTAKE_TEMP,callback=get_temp)
connect.watch(obd.commands.FUEL_LEVEL,callback=get_fuel)
connect.watch(obd.commands.SPEED,callback=get_speed)
while True:
tempz = open("temp.txt","w+")
fuel1 = open("fuel.txt","w+")
speed1 = open("speed.txt","w+")
speed1.write(speed)
tempz.write(tem)
fuel1.write(fueli)
print(speed)
| [
"obd.OBD",
"obd.Async"
] | [((109, 118), 'obd.OBD', 'obd.OBD', ([], {}), '()\n', (116, 118), False, 'import obd\n'), ((129, 150), 'obd.Async', 'obd.Async', ([], {'fast': '(False)'}), '(fast=False)\n', (138, 150), False, 'import obd\n')] |
from django.contrib import admin
from django import forms
from . import models
class PizzaFlavorAdminForm(forms.ModelForm):
class Meta:
model = models.PizzaFlavor
fields = "__all__"
class PizzaFlavorAdmin(admin.ModelAdmin):
form = PizzaFlavorAdminForm
list_display = [
"id",
"name",
"s_size_price",
"m_size_price",
"l_size_price",
]
readonly_fields = [
"m_size_price",
"s_size_price",
"l_size_price",
"id",
"name",
]
class OrderedPizzaAdminForm(forms.ModelForm):
class Meta:
model = models.OrderedPizza
fields = "__all__"
class OrderedPizzaAdmin(admin.ModelAdmin):
form = OrderedPizzaAdminForm
list_display = [
"id",
"size",
"created",
"count",
]
readonly_fields = [
"id",
"size",
"created",
"count",
]
class OrderAdminForm(forms.ModelForm):
class Meta:
model = models.Order
fields = "__all__"
class OrderAdmin(admin.ModelAdmin):
form = OrderAdminForm
list_display = [
"id",
"customer_id",
"last_updated",
"created",
"is_paid",
]
readonly_fields = [
"customer_id",
"last_updated",
"created",
"is_paid",
"id",
]
class DeliveryDetailAdminForm(forms.ModelForm):
class Meta:
model = models.DeliveryDetail
fields = "__all__"
class DeliveryDetailAdmin(admin.ModelAdmin):
form = DeliveryDetailAdminForm
list_display = [
"id",
"assigned_courier_id",
"status",
"created",
]
readonly_fields = [
"assigned_courier_id",
"status",
"id",
"created",
]
admin.site.register(models.PizzaFlavor, PizzaFlavorAdmin)
admin.site.register(models.OrderedPizza, OrderedPizzaAdmin)
admin.site.register(models.Order, OrderAdmin)
admin.site.register(models.DeliveryDetail, DeliveryDetailAdmin) | [
"django.contrib.admin.site.register"
] | [((1808, 1865), 'django.contrib.admin.site.register', 'admin.site.register', (['models.PizzaFlavor', 'PizzaFlavorAdmin'], {}), '(models.PizzaFlavor, PizzaFlavorAdmin)\n', (1827, 1865), False, 'from django.contrib import admin\n'), ((1866, 1925), 'django.contrib.admin.site.register', 'admin.site.register', (['models.OrderedPizza', 'OrderedPizzaAdmin'], {}), '(models.OrderedPizza, OrderedPizzaAdmin)\n', (1885, 1925), False, 'from django.contrib import admin\n'), ((1926, 1971), 'django.contrib.admin.site.register', 'admin.site.register', (['models.Order', 'OrderAdmin'], {}), '(models.Order, OrderAdmin)\n', (1945, 1971), False, 'from django.contrib import admin\n'), ((1972, 2035), 'django.contrib.admin.site.register', 'admin.site.register', (['models.DeliveryDetail', 'DeliveryDetailAdmin'], {}), '(models.DeliveryDetail, DeliveryDetailAdmin)\n', (1991, 2035), False, 'from django.contrib import admin\n')] |
#!/usr/bin/env python2.7
#
# This file is part of peakAnalysis, http://github.com/alexjgriffith/peaks/,
# and is Copyright (C) University of Ottawa, 2014. It is Licensed under
# the three-clause BSD License; see doc/LICENSE.txt.
# Contact: <EMAIL>
#
# Created : AUG262014
# File : buildPeaksClass
# Author : <NAME>
# Lab : Dr. Brand and Dr. Perkins
import sys
import numpy
import argparse
from peak_functions import *
from buildPeaksClass import buildPeaks
from peakClass import peak,peakCap,peakCapHandler
from defineClass import define
from subsetClass import subsetWraper
def fromStdin():
parser=argparse.ArgumentParser(prog="TAG",description="Combine and tag input files.",epilog="File Format: <bed file location><catagory><value>...")
parser.add_argument('-i','--in-file',dest='fileLocation')
parser.add_argument('-c','--chromosome',dest='chromosomeLoc')
parser.add_argument('-m','--macs',dest='MACS',action='store_true')
parser.add_argument('-t','--tags',dest='TAGS',action='store_true')
parser.add_argument('-s','--summits',dest='SUMMITS',action='store_true')
return parser.parse_args(sys.argv[1:])
def zeroTest(double,value):
lower=double-value
upper=double+value-1
if lower<0:
double=0
upper=upper-lower
return str(int(lower)),str(int(upper))
def main():
args=fromStdin()
rawpeaks=(buildPeaks(args.fileLocation,trip=False,chromosomeLoc=args.chromosomeLoc))()
peaks=peakCapHandler()
peaks.add(rawpeaks)
peaks.overlap(350)
a=lambda i :i.data[0].chro
b=lambda i :i.define.data["name"]
c=lambda i ,o :zeroTest(i.summit,o)
d=lambda i : [str(j.score) for j in i.data]
e=lambda i : [str(j.summit) for j in i.data]
x=[[a(i),c(i,150),d(i),b(i),e(i)] for i in peaks.data]
for i in range(len(peaks.data)):
sys.stdout.write( x[i][0]+"\t"+ str(x[i][1][0])+"\t"+ str(x[i][1][1])+"\t")
if(args.MACS):
sys.stdout.write("{")
for j in range(len(x[i][2])-1):
sys.stdout.write(str(x[i][3][j])+":"+str(x[i][2][j])+",")
sys.stdout.write(str(x[i][3][-1])+":"+x[i][2][-1]+"}\t")
if(args.SUMMITS):
sys.stdout.write("{")
for j in range(len(x[i][4])-1):
sys.stdout.write(str(x[i][3][j])+":"+str(x[i][4][j])+",")
sys.stdout.write(str(x[i][3][-1])+":"+x[i][4][-1]+"}\t")
if(args.TAGS):
for j in range(len(x[i][3])-1):
sys.stdout.write(str(x[i][3][j])+"-")
sys.stdout.write(x[i][3][-1])
sys.stdout.write("\n")
if __name__=='__main__':
main()
| [
"peakClass.peakCapHandler",
"buildPeaksClass.buildPeaks",
"argparse.ArgumentParser",
"sys.stdout.write"
] | [((615, 767), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': '"""TAG"""', 'description': '"""Combine and tag input files."""', 'epilog': '"""File Format: <bed file location><catagory><value>..."""'}), "(prog='TAG', description=\n 'Combine and tag input files.', epilog=\n 'File Format: <bed file location><catagory><value>...')\n", (638, 767), False, 'import argparse\n'), ((1460, 1476), 'peakClass.peakCapHandler', 'peakCapHandler', ([], {}), '()\n', (1474, 1476), False, 'from peakClass import peak, peakCap, peakCapHandler\n'), ((1373, 1448), 'buildPeaksClass.buildPeaks', 'buildPeaks', (['args.fileLocation'], {'trip': '(False)', 'chromosomeLoc': 'args.chromosomeLoc'}), '(args.fileLocation, trip=False, chromosomeLoc=args.chromosomeLoc)\n', (1383, 1448), False, 'from buildPeaksClass import buildPeaks\n'), ((2574, 2596), 'sys.stdout.write', 'sys.stdout.write', (['"""\n"""'], {}), "('\\n')\n", (2590, 2596), False, 'import sys\n'), ((1947, 1968), 'sys.stdout.write', 'sys.stdout.write', (['"""{"""'], {}), "('{')\n", (1963, 1968), False, 'import sys\n'), ((2194, 2215), 'sys.stdout.write', 'sys.stdout.write', (['"""{"""'], {}), "('{')\n", (2210, 2215), False, 'import sys\n'), ((2536, 2565), 'sys.stdout.write', 'sys.stdout.write', (['x[i][3][-1]'], {}), '(x[i][3][-1])\n', (2552, 2565), False, 'import sys\n')] |
# -*- coding: utf-8 -*-
"""
.. module:: skimpy
:platform: Unix, Windows
:synopsis: Simple Kinetic Models in Python
.. moduleauthor:: SKiMPy team
[---------]
Copyright 2017 Laboratory of Computational Systems Biotechnology (LCSB),
Ecole Polytechnique Federale de Lausanne (EPFL), Switzerland
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import numpy as np
import pytfa
from pytfa.io import import_matlab_model, load_thermoDB
from pytfa.io.viz import get_reaction_data
from skimpy.core import *
from skimpy.mechanisms import *
from skimpy.utils.namespace import *
from skimpy.sampling.simple_parameter_sampler import SimpleParameterSampler
from skimpy.core.parameters import ParameterValuePopulation
from skimpy.core.solution import ODESolutionPopulation
from skimpy.io.generate_from_pytfa import FromPyTFA
from skimpy.utils.general import sanitize_cobra_vars
from skimpy.utils.tabdict import TabDict
from skimpy.analysis.ode.utils import make_flux_fun
from skimpy.analysis.oracle import *
from optlang.exceptions import SolverError
CONCENTRATION_SCALING = 1e6 # 1 mol to 1 mmol
TIME_SCALING = 1 # 1hr
# Parameters of the E. Coli cell
DENSITY = 1200 # g/L
GDW_GWW_RATIO = 0.3 # Assumes 70% Water
flux_scaling_factor = 1e-3 * (GDW_GWW_RATIO * DENSITY) \
* CONCENTRATION_SCALING \
/ TIME_SCALING
"""
Import and curate a model
"""
this_cobra_model = import_matlab_model('../../models/toy_model.mat',
'model')
"""
Make tfa analysis of the model
"""
# Convert to a thermodynamics model
thermo_data = load_thermoDB('../../data/thermo_data.thermodb')
this_pytfa_model = pytfa.ThermoModel(thermo_data, this_cobra_model)
CPLEX = 'optlang-cplex'
this_pytfa_model.solver = CPLEX
# TFA conversion
this_pytfa_model.prepare()
this_pytfa_model.convert(add_displacement=True)
# We choose a flux directionality profile (FDP)
# with minium fluxes of 1e-3
this_bounds = {'DM_13dpg': (-10.0, -2.0),
'DM_2h3oppan': (1e-3, 100.0),
'DM_adp': (-100.0, -1e-3),
'DM_atp': (1e-3, 100.0),
'DM_h': (1e-3, 100.0),
'DM_h2o': (1e-3, 100.0),
'DM_nad': (-100.0, -1e-3),
'DM_nadh': (1e-3, 100.0),
'DM_pep': (1e-3, 100.0),
'ENO': (2.0, 100.0),
'GLYCK': (1e-3, 100.0),
'GLYCK2': (1e-3, 100.0),
'PGK': (1e-3, 100.0),
'PGM': (2.0, 2.0),
'TRSARr': (2.0, 10.0),
'Trp_adp': (-100.0, 100.0),
'Trp_atp': (-100.0, 100.0),
'Trp_h': (-100.0, 100.0),
'Trp_h2o': (-100.0, 100.0),
'Trp_nad': (-100.0, 100.0),
'Trp_nadh': (-100.0, 100.0)}
for k,v in this_bounds.items():
this_pytfa_model.reactions.get_by_id(k).bounds = v
# Find a solution for this FDP
solution = this_pytfa_model.optimize()
# Force a minimal thermodynamic displacement
min_log_displacement = 1e-1
add_min_log_displacement(this_pytfa_model, min_log_displacement)
# Find a solution for the model
solution = this_pytfa_model.optimize()
this_pytfa_model.thermo_displacement.PGM.variable.lb = np.log(1e-1)
this_pytfa_model.thermo_displacement.PGM.variable.ub = np.log(1e-1)
solution = this_pytfa_model.optimize()
"""
Get a Kinetic Model
"""
# Generate the KineticModel
# Define the molecules that should be considered small-molecules
# These molecules will not be accounted explicitly in the kinetic mechanism as
# substrates and products
small_molecules = ['h_c', 'h_e']
model_gen = FromPyTFA(small_molecules=small_molecules)
this_skimpy_model = model_gen.import_model(this_pytfa_model, solution.raw)
"""
Load the reference solutions
"""
fluxes = load_fluxes(solution.raw, this_pytfa_model, this_skimpy_model,
density=DENSITY,
ratio_gdw_gww=GDW_GWW_RATIO,
concentration_scaling=CONCENTRATION_SCALING,
time_scaling=TIME_SCALING)
concentrations = load_concentrations(solution.raw, this_pytfa_model, this_skimpy_model,
concentration_scaling=CONCENTRATION_SCALING)
load_equilibrium_constants(solution.raw, this_pytfa_model, this_skimpy_model,
concentration_scaling=CONCENTRATION_SCALING,
in_place=True)
"""
Sample the kinetic parameters based on linear stablity
"""
this_skimpy_model.parameters.km_substrate_ENO.bounds = (1e-4, 1e-3)
this_skimpy_model.parameters.km_product_ENO.bounds = (1e-4, 1e-3)
this_skimpy_model.prepare(mca=True)
# Compile MCA functions
this_skimpy_model.compile_mca(sim_type=QSSA)
# Initialize parameter sampler
sampling_parameters = SimpleParameterSampler.Parameters(n_samples=1)
sampler = SimpleParameterSampler(sampling_parameters)
# Sample the model
parameter_population = sampler.sample(this_skimpy_model,
fluxes,
concentrations)
parameter_population = ParameterValuePopulation(parameter_population, this_skimpy_model, index=range(1))
"""
Calculate control coefficients
"""
parameter_list = TabDict([(k, p.symbol) for k, p in
this_skimpy_model.parameters.items() if
p.name.startswith('vmax_forward')])
this_skimpy_model.compile_mca(mca_type=SPLIT,sim_type=QSSA, parameter_list=parameter_list)
flux_control_coeff = this_skimpy_model.flux_control_fun(fluxes,
concentrations,
parameter_population)
"""
Integrate the ODEs
"""
this_skimpy_model.compile_ode(sim_type=QSSA)
this_skimpy_model.initial_conditions = TabDict([(k,v) for k,v in concentrations.iteritems()])
solutions = []
this_parameters = parameter_population[0]
vmax_glyck2 = this_parameters['vmax_forward_GLYCK2']
# For each solution calulate the fluxes
calc_fluxes = make_flux_fun(this_skimpy_model, QSSA)
fluxes_pgm_expression = []
this_skimpy_model.parameters = this_parameters
for rel_e in np.logspace(-3, 3, 100):
this_parameters['vmax_forward_GLYCK2'] = vmax_glyck2*rel_e
this_skimpy_model.parameters = this_parameters
sol = this_skimpy_model.solve_ode(np.linspace(0.0, 1.0, 1000),
solver_type='cvode',
rtol=1e-9,
atol=1e-9,
max_steps=1e9,)
solutions.append(sol)
steady_state_fluxes = calc_fluxes(sol.concentrations.iloc[-1], parameters=this_parameters)
fluxes_pgm_expression.append(steady_state_fluxes)
fluxes_pgm_expression = pd.DataFrame(fluxes_pgm_expression)/flux_scaling_factor
| [
"skimpy.analysis.ode.utils.make_flux_fun",
"skimpy.io.generate_from_pytfa.FromPyTFA",
"pytfa.io.import_matlab_model",
"numpy.log",
"skimpy.sampling.simple_parameter_sampler.SimpleParameterSampler.Parameters",
"pytfa.io.load_thermoDB",
"skimpy.sampling.simple_parameter_sampler.SimpleParameterSampler",
... | [((1890, 1948), 'pytfa.io.import_matlab_model', 'import_matlab_model', (['"""../../models/toy_model.mat"""', '"""model"""'], {}), "('../../models/toy_model.mat', 'model')\n", (1909, 1948), False, 'from pytfa.io import import_matlab_model, load_thermoDB\n'), ((2080, 2128), 'pytfa.io.load_thermoDB', 'load_thermoDB', (['"""../../data/thermo_data.thermodb"""'], {}), "('../../data/thermo_data.thermodb')\n", (2093, 2128), False, 'from pytfa.io import import_matlab_model, load_thermoDB\n'), ((2148, 2196), 'pytfa.ThermoModel', 'pytfa.ThermoModel', (['thermo_data', 'this_cobra_model'], {}), '(thermo_data, this_cobra_model)\n', (2165, 2196), False, 'import pytfa\n'), ((3807, 3818), 'numpy.log', 'np.log', (['(0.1)'], {}), '(0.1)\n', (3813, 3818), True, 'import numpy as np\n'), ((3875, 3886), 'numpy.log', 'np.log', (['(0.1)'], {}), '(0.1)\n', (3881, 3886), True, 'import numpy as np\n'), ((4203, 4245), 'skimpy.io.generate_from_pytfa.FromPyTFA', 'FromPyTFA', ([], {'small_molecules': 'small_molecules'}), '(small_molecules=small_molecules)\n', (4212, 4245), False, 'from skimpy.io.generate_from_pytfa import FromPyTFA\n'), ((5357, 5403), 'skimpy.sampling.simple_parameter_sampler.SimpleParameterSampler.Parameters', 'SimpleParameterSampler.Parameters', ([], {'n_samples': '(1)'}), '(n_samples=1)\n', (5390, 5403), False, 'from skimpy.sampling.simple_parameter_sampler import SimpleParameterSampler\n'), ((5414, 5457), 'skimpy.sampling.simple_parameter_sampler.SimpleParameterSampler', 'SimpleParameterSampler', (['sampling_parameters'], {}), '(sampling_parameters)\n', (5436, 5457), False, 'from skimpy.sampling.simple_parameter_sampler import SimpleParameterSampler\n'), ((6605, 6643), 'skimpy.analysis.ode.utils.make_flux_fun', 'make_flux_fun', (['this_skimpy_model', 'QSSA'], {}), '(this_skimpy_model, QSSA)\n', (6618, 6643), False, 'from skimpy.analysis.ode.utils import make_flux_fun\n'), ((6734, 6757), 'numpy.logspace', 'np.logspace', (['(-3)', '(3)', '(100)'], {}), '(-3, 3, 100)\n', (6745, 6757), True, 'import numpy as np\n'), ((6913, 6940), 'numpy.linspace', 'np.linspace', (['(0.0)', '(1.0)', '(1000)'], {}), '(0.0, 1.0, 1000)\n', (6924, 6940), True, 'import numpy as np\n')] |
from opswat import MetaDefenderApi
if __name__ == "__main__":
md = MetaDefenderApi(ip="10.26.50.15", port=8008)
#dir = "files"
dir = "C:\\Users\\10694\\dev"
results = md.scan_directory(dir)
print(results) | [
"opswat.MetaDefenderApi"
] | [((74, 118), 'opswat.MetaDefenderApi', 'MetaDefenderApi', ([], {'ip': '"""10.26.50.15"""', 'port': '(8008)'}), "(ip='10.26.50.15', port=8008)\n", (89, 118), False, 'from opswat import MetaDefenderApi\n')] |
import os
import pytest
@pytest.fixture(scope="module")
def some_context():
return [1,2,3,4,5]
def get_scripts():
with open(config_file) as f:
scripts = [line.strip('\n') for line in f.readlines()]
return scripts
config_file = os.environ["RECIPY_TEST_CASES_CONFIG"]
def case_name(value):
return "script_" + str(value)
@pytest.mark.parametrize("script", get_scripts(), ids=case_name)
def test_script(some_context, script):
print(some_context)
if script == "sklearn":
pytest.fail(script, " failed its test")
else:
pass
| [
"pytest.fixture",
"pytest.fail"
] | [((26, 56), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (40, 56), False, 'import pytest\n'), ((511, 550), 'pytest.fail', 'pytest.fail', (['script', '""" failed its test"""'], {}), "(script, ' failed its test')\n", (522, 550), False, 'import pytest\n')] |
import builtins
from larval_gonad.mock import MockSnake
from larval_gonad.config import read_config
builtins.snakemake = MockSnake(
input="../../output/paper_submission/fig1_data_avg_tpm_per_chrom.feather",
params=dict(colors=read_config("../../config/colors.yaml")),
)
| [
"larval_gonad.config.read_config"
] | [((236, 275), 'larval_gonad.config.read_config', 'read_config', (['"""../../config/colors.yaml"""'], {}), "('../../config/colors.yaml')\n", (247, 275), False, 'from larval_gonad.config import read_config\n')] |
from wsgiserver import WSGIServer
import sys
class Server(WSGIServer):
def error_log(self, msg="", level=20, traceback=False):
# Override this in subclasses as desired
import logging
lgr = logging.getLogger('theonionbox')
e = sys.exc_info()[1]
if e.args[1].find('UNKNOWN_CA') > 0:
lgr.warn("{} -> Your CA certificate could not be located or "
"couldn't be matched with a known, trusted CA.".format(e.args[1]))
else:
lgr.warn('HTTP Server: {}'.format(e.args[1]))
| [
"logging.getLogger",
"sys.exc_info"
] | [((220, 252), 'logging.getLogger', 'logging.getLogger', (['"""theonionbox"""'], {}), "('theonionbox')\n", (237, 252), False, 'import logging\n'), ((265, 279), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (277, 279), False, 'import sys\n')] |
# Generated by Django 2.1 on 2018-08-16 20:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fpl', '0016_auto_20180816_2020'),
]
operations = [
migrations.AlterField(
model_name='classicleague',
name='fpl_league_id',
field=models.IntegerField(),
),
migrations.AlterField(
model_name='headtoheadleague',
name='fpl_league_id',
field=models.IntegerField(),
),
]
| [
"django.db.models.IntegerField"
] | [((344, 365), 'django.db.models.IntegerField', 'models.IntegerField', ([], {}), '()\n', (363, 365), False, 'from django.db import migrations, models\n'), ((504, 525), 'django.db.models.IntegerField', 'models.IntegerField', ([], {}), '()\n', (523, 525), False, 'from django.db import migrations, models\n')] |
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from rest_framework.request import Request
from rest_framework.test import APIClient, APIRequestFactory
from user import models, serializers
FAMILY_DATA_URL = reverse('user:familydata-list')
# creating a test request
factory = APIRequestFactory()
request = factory.get('/')
# create serializer context
serializer_context = {'request': Request(request)}
def family_data_detail_url(family_data_id):
"""return url for the family_data detail"""
return reverse('user:familydata-detail', args=[family_data_id])
def sample_biodata(user, **kwargs):
"""create and return sample biodata"""
return models.Biodata.objects.create(user=user, **kwargs)
def sample_family_data(biodata, **kwargs):
"""create and return sample family_data"""
return models.FamilyData.objects.create(biodata=biodata, **kwargs)
def test_all_model_attributes(insance, payload, model, serializer):
"""test model attributes against a payload, with instance being self in a testcase class """
ignored_keys = ['image']
relevant_keys = sorted(set(payload.keys()).difference(ignored_keys))
for key in relevant_keys:
try:
insance.assertEqual(payload[key], getattr(model, key))
except Exception:
insance.assertEqual(payload[key], serializer.data[key])
class PublicFamilyDataApiTest(TestCase):
"""test public access to the family_data api"""
def setUp(self):
self.client = APIClient()
def test_authentication_required(self):
"""test that authentication is required"""
res = self.client.get(FAMILY_DATA_URL)
self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
class PrivateFamilyDataApiTest(TestCase):
"""test authenticated access to the family_data api"""
def setUp(self):
self.client = APIClient()
self.user = get_user_model().objects.create_superuser(
email='<EMAIL>',
password='<PASSWORD>'
)
self.biodata = sample_biodata(user=self.user)
self.serializer = serializers.BiodataSerializer(self.biodata, context=serializer_context)
self.client.force_authenticate(self.user)
def tearDown(self):
pass
def test_retrieve_family_data(self):
"""test retrieving a list of family_data"""
sample_family_data(biodata=self.biodata)
family_data = models.FamilyData.objects.all()
serializer = serializers.FamilyDataSerializer(family_data, many=True, context=serializer_context)
res = self.client.get(FAMILY_DATA_URL)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(res.data['results'], serializer.data)
def test_retrieve_family_data_detail(self):
"""test retrieving a family_data's detail"""
family_data = sample_family_data(biodata=self.biodata)
serializer = serializers.FamilyDataSerializer(family_data, context=serializer_context)
url = family_data_detail_url(family_data_id=family_data.id)
res = self.client.get(url)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(res.data, serializer.data)
def test_create_family_data(self):
"""test creating a family_data"""
payload = {
'biodata': self.serializer.data['url'],
'guardian_full_name': 'Test Guardian',
}
res = self.client.post(FAMILY_DATA_URL, payload)
family_data = models.FamilyData.objects.get(id=res.data['id'])
family_data_serializer = serializers.FamilyDataSerializer(family_data, context=serializer_context)
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
test_all_model_attributes(self, payload, family_data, family_data_serializer)
def test_partial_update_family_data(self):
"""test partially updating a family_data's detail using patch"""
family_data = sample_family_data(biodata=self.biodata)
payload = {
'guardian_full_name': '<NAME>',
}
url = family_data_detail_url(family_data.id)
res = self.client.patch(url, payload)
family_data.refresh_from_db()
family_data_serializer = serializers.FamilyDataSerializer(family_data, context=serializer_context)
self.assertEqual(res.status_code, status.HTTP_200_OK)
test_all_model_attributes(self, payload, family_data, family_data_serializer)
def test_full_update_family_data(self):
"""test updating a family_data's detail using put"""
family_data = sample_family_data(biodata=self.biodata)
payload = {
'biodata': self.serializer.data['url'],
'guardian_full_name': '<NAME>',
}
url = family_data_detail_url(family_data.id)
res = self.client.put(url, payload)
family_data.refresh_from_db()
family_data_serializer = serializers.FamilyDataSerializer(family_data, context=serializer_context)
self.assertEqual(res.status_code, status.HTTP_200_OK)
test_all_model_attributes(self, payload, family_data, family_data_serializer)
| [
"django.contrib.auth.get_user_model",
"user.serializers.BiodataSerializer",
"user.models.FamilyData.objects.create",
"user.models.FamilyData.objects.all",
"rest_framework.test.APIClient",
"user.serializers.FamilyDataSerializer",
"user.models.FamilyData.objects.get",
"django.urls.reverse",
"user.mode... | [((307, 338), 'django.urls.reverse', 'reverse', (['"""user:familydata-list"""'], {}), "('user:familydata-list')\n", (314, 338), False, 'from django.urls import reverse\n'), ((376, 395), 'rest_framework.test.APIRequestFactory', 'APIRequestFactory', ([], {}), '()\n', (393, 395), False, 'from rest_framework.test import APIClient, APIRequestFactory\n'), ((484, 500), 'rest_framework.request.Request', 'Request', (['request'], {}), '(request)\n', (491, 500), False, 'from rest_framework.request import Request\n'), ((607, 663), 'django.urls.reverse', 'reverse', (['"""user:familydata-detail"""'], {'args': '[family_data_id]'}), "('user:familydata-detail', args=[family_data_id])\n", (614, 663), False, 'from django.urls import reverse\n'), ((756, 806), 'user.models.Biodata.objects.create', 'models.Biodata.objects.create', ([], {'user': 'user'}), '(user=user, **kwargs)\n', (785, 806), False, 'from user import models, serializers\n'), ((910, 969), 'user.models.FamilyData.objects.create', 'models.FamilyData.objects.create', ([], {'biodata': 'biodata'}), '(biodata=biodata, **kwargs)\n', (942, 969), False, 'from user import models, serializers\n'), ((1582, 1593), 'rest_framework.test.APIClient', 'APIClient', ([], {}), '()\n', (1591, 1593), False, 'from rest_framework.test import APIClient, APIRequestFactory\n'), ((1956, 1967), 'rest_framework.test.APIClient', 'APIClient', ([], {}), '()\n', (1965, 1967), False, 'from rest_framework.test import APIClient, APIRequestFactory\n'), ((2184, 2255), 'user.serializers.BiodataSerializer', 'serializers.BiodataSerializer', (['self.biodata'], {'context': 'serializer_context'}), '(self.biodata, context=serializer_context)\n', (2213, 2255), False, 'from user import models, serializers\n'), ((2509, 2540), 'user.models.FamilyData.objects.all', 'models.FamilyData.objects.all', ([], {}), '()\n', (2538, 2540), False, 'from user import models, serializers\n'), ((2562, 2651), 'user.serializers.FamilyDataSerializer', 'serializers.FamilyDataSerializer', (['family_data'], {'many': '(True)', 'context': 'serializer_context'}), '(family_data, many=True, context=\n serializer_context)\n', (2594, 2651), False, 'from user import models, serializers\n'), ((3007, 3080), 'user.serializers.FamilyDataSerializer', 'serializers.FamilyDataSerializer', (['family_data'], {'context': 'serializer_context'}), '(family_data, context=serializer_context)\n', (3039, 3080), False, 'from user import models, serializers\n'), ((3596, 3644), 'user.models.FamilyData.objects.get', 'models.FamilyData.objects.get', ([], {'id': "res.data['id']"}), "(id=res.data['id'])\n", (3625, 3644), False, 'from user import models, serializers\n'), ((3678, 3751), 'user.serializers.FamilyDataSerializer', 'serializers.FamilyDataSerializer', (['family_data'], {'context': 'serializer_context'}), '(family_data, context=serializer_context)\n', (3710, 3751), False, 'from user import models, serializers\n'), ((4337, 4410), 'user.serializers.FamilyDataSerializer', 'serializers.FamilyDataSerializer', (['family_data'], {'context': 'serializer_context'}), '(family_data, context=serializer_context)\n', (4369, 4410), False, 'from user import models, serializers\n'), ((5026, 5099), 'user.serializers.FamilyDataSerializer', 'serializers.FamilyDataSerializer', (['family_data'], {'context': 'serializer_context'}), '(family_data, context=serializer_context)\n', (5058, 5099), False, 'from user import models, serializers\n'), ((1988, 2004), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (2002, 2004), False, 'from django.contrib.auth import get_user_model\n')] |
#!/usr/bin/env python
import datetime
import json
import pathlib
import re
import sys
from typing import List, Optional
from vaccine_feed_ingest_schema import location as schema
from vaccine_feed_ingest.utils.log import getLogger
logger = getLogger(__file__)
RUNNER_ID = "az_pinal_ph_vaccinelocations_gov"
def _get_id(site: dict) -> str:
id = f"{_get_name(site)}_{_get_city(site)}".lower()
id = id.replace(" ", "_").replace(".", "_").replace("\u2019", "_")
id = id.replace("(", "_").replace(")", "_").replace("/", "_")
return id
def _get_name(site: dict) -> str:
return site["providerName"]
def _get_city(site: dict) -> str:
return site["city"].lstrip().rstrip()
# address is loosely structured and inconsistent, so we're going to bash our
# way through it, mostly parsing from the end of the string
def _get_address(site: dict) -> Optional[schema.Address]:
if "address" not in site or not site["address"]:
return None
address = site["address"]
address = re.sub("\\s+", " ", address)
address = re.sub("\\s*,+", ",", address)
address = address.strip()
# pull a zip code off the end
zip = None
if match := re.search(" (\\d\\d\\d\\d\\d-\\d\\d\\d\\d)$", address):
zip = match.group(1)
address = address.rstrip(f" {zip}")
if match := re.search(" (\\d\\d\\d\\d\\d)$", address):
zip = match.group(1)
address = address.rstrip(f" {zip}")
state = "AZ"
address = address.rstrip()
address = address.rstrip(",")
address = address.rstrip(".")
address = address.rstrip(f" {state}")
address = address.rstrip()
address = address.rstrip(",")
address = address.rstrip(f" {_get_city(site)}")
address = address.rstrip()
address = address.rstrip(",")
address_split = address.split(",")
street1 = address_split[0]
street2 = ", ".join(address_split[1:]) if len(address_split) > 1 else None
return schema.Address(
street1=street1,
street2=street2,
city=_get_city(site),
state=state,
zip=zip,
)
def _get_contacts(site: dict) -> schema.Contact:
ret = []
if "phoneNumber" in site and site["phoneNumber"]:
raw_phone = str(site["phoneNumber"]).lstrip("1").lstrip("-")
if raw_phone[3] == "-" or raw_phone[7] == "-":
phone = "(" + raw_phone[0:3] + ") " + raw_phone[4:7] + "-" + raw_phone[8:12]
elif len(raw_phone) == 10:
phone = "(" + raw_phone[0:3] + ") " + raw_phone[3:6] + "-" + raw_phone[6:10]
else:
phone = raw_phone[0:14]
ret.append(schema.Contact(phone=phone))
if "website" in site and site["website"]:
ret.append(schema.Contact(website=site["website"]))
return ret
def _get_inventories(site: dict) -> List[schema.Vaccine]:
ret = []
if "vaccineType" in site and site["vaccineType"]:
if "Moderna" in site["vaccineType"]:
ret.append(schema.Vaccine(vaccine=schema.VaccineType.MODERNA))
if "Pfizer" in site["vaccineType"]:
ret.append(schema.Vaccine(vaccine=schema.VaccineType.PFIZER_BIONTECH))
if "Janssen" in site["vaccineType"]:
ret.append(
schema.Vaccine(vaccine=schema.VaccineType.JOHNSON_JOHNSON_JANSSEN)
)
return ret
def _get_organization(site: dict) -> Optional[schema.Organization]:
if "Kroger" in site["providerName"]:
return schema.Organization(id=schema.VaccineProvider.KROGER)
if "Safeway" in site["providerName"]:
return schema.Organization(id=schema.VaccineProvider.SAFEWAY)
if "Walgreen" in site["providerName"]:
return schema.Organization(id=schema.VaccineProvider.WALGREENS)
if "Walmart" in site["providerName"]:
return schema.Organization(id=schema.VaccineProvider.WALMART)
if "CVS" in site["providerName"]:
return schema.Organization(id=schema.VaccineProvider.CVS)
return None
def _get_source(site: dict, timestamp: str) -> schema.Source:
return schema.Source(
data=site,
fetched_at=timestamp,
fetched_from_uri="https://www.pinalcountyaz.gov/publichealth/CoronaVirus/Pages/vaccinelocations.aspx",
id=_get_id(site),
source=RUNNER_ID,
)
def normalize(site: dict, timestamp: str) -> str:
normalized = schema.NormalizedLocation(
id=f"{RUNNER_ID}:{_get_id(site)}",
name=_get_name(site),
address=_get_address(site),
contact=_get_contacts(site),
inventory=_get_inventories(site),
parent_organization=_get_organization(site),
source=_get_source(site, timestamp),
).dict()
return normalized
parsed_at_timestamp = datetime.datetime.utcnow().isoformat()
input_dir = pathlib.Path(sys.argv[2])
input_file = input_dir / "data.parsed.ndjson"
output_dir = pathlib.Path(sys.argv[1])
output_file = output_dir / "data.normalized.ndjson"
with input_file.open() as parsed_lines:
with output_file.open("w") as fout:
for line in parsed_lines:
site_blob = json.loads(line)
normalized_site = normalize(site_blob, parsed_at_timestamp)
json.dump(normalized_site, fout)
fout.write("\n")
| [
"json.loads",
"pathlib.Path",
"datetime.datetime.utcnow",
"vaccine_feed_ingest.utils.log.getLogger",
"vaccine_feed_ingest_schema.location.Vaccine",
"vaccine_feed_ingest_schema.location.Contact",
"vaccine_feed_ingest_schema.location.Organization",
"re.sub",
"json.dump",
"re.search"
] | [((243, 262), 'vaccine_feed_ingest.utils.log.getLogger', 'getLogger', (['__file__'], {}), '(__file__)\n', (252, 262), False, 'from vaccine_feed_ingest.utils.log import getLogger\n'), ((4761, 4786), 'pathlib.Path', 'pathlib.Path', (['sys.argv[2]'], {}), '(sys.argv[2])\n', (4773, 4786), False, 'import pathlib\n'), ((4846, 4871), 'pathlib.Path', 'pathlib.Path', (['sys.argv[1]'], {}), '(sys.argv[1])\n', (4858, 4871), False, 'import pathlib\n'), ((1014, 1042), 're.sub', 're.sub', (['"""\\\\s+"""', '""" """', 'address'], {}), "('\\\\s+', ' ', address)\n", (1020, 1042), False, 'import re\n'), ((1057, 1087), 're.sub', 're.sub', (['"""\\\\s*,+"""', '""","""', 'address'], {}), "('\\\\s*,+', ',', address)\n", (1063, 1087), False, 'import re\n'), ((1184, 1238), 're.search', 're.search', (['""" (\\\\d\\\\d\\\\d\\\\d\\\\d-\\\\d\\\\d\\\\d\\\\d)$"""', 'address'], {}), "(' (\\\\d\\\\d\\\\d\\\\d\\\\d-\\\\d\\\\d\\\\d\\\\d)$', address)\n", (1193, 1238), False, 'import re\n'), ((1329, 1370), 're.search', 're.search', (['""" (\\\\d\\\\d\\\\d\\\\d\\\\d)$"""', 'address'], {}), "(' (\\\\d\\\\d\\\\d\\\\d\\\\d)$', address)\n", (1338, 1370), False, 'import re\n'), ((3447, 3500), 'vaccine_feed_ingest_schema.location.Organization', 'schema.Organization', ([], {'id': 'schema.VaccineProvider.KROGER'}), '(id=schema.VaccineProvider.KROGER)\n', (3466, 3500), True, 'from vaccine_feed_ingest_schema import location as schema\n'), ((3558, 3612), 'vaccine_feed_ingest_schema.location.Organization', 'schema.Organization', ([], {'id': 'schema.VaccineProvider.SAFEWAY'}), '(id=schema.VaccineProvider.SAFEWAY)\n', (3577, 3612), True, 'from vaccine_feed_ingest_schema import location as schema\n'), ((3671, 3727), 'vaccine_feed_ingest_schema.location.Organization', 'schema.Organization', ([], {'id': 'schema.VaccineProvider.WALGREENS'}), '(id=schema.VaccineProvider.WALGREENS)\n', (3690, 3727), True, 'from vaccine_feed_ingest_schema import location as schema\n'), ((3785, 3839), 'vaccine_feed_ingest_schema.location.Organization', 'schema.Organization', ([], {'id': 'schema.VaccineProvider.WALMART'}), '(id=schema.VaccineProvider.WALMART)\n', (3804, 3839), True, 'from vaccine_feed_ingest_schema import location as schema\n'), ((3893, 3943), 'vaccine_feed_ingest_schema.location.Organization', 'schema.Organization', ([], {'id': 'schema.VaccineProvider.CVS'}), '(id=schema.VaccineProvider.CVS)\n', (3912, 3943), True, 'from vaccine_feed_ingest_schema import location as schema\n'), ((4709, 4735), 'datetime.datetime.utcnow', 'datetime.datetime.utcnow', ([], {}), '()\n', (4733, 4735), False, 'import datetime\n'), ((2614, 2641), 'vaccine_feed_ingest_schema.location.Contact', 'schema.Contact', ([], {'phone': 'phone'}), '(phone=phone)\n', (2628, 2641), True, 'from vaccine_feed_ingest_schema import location as schema\n'), ((2709, 2748), 'vaccine_feed_ingest_schema.location.Contact', 'schema.Contact', ([], {'website': "site['website']"}), "(website=site['website'])\n", (2723, 2748), True, 'from vaccine_feed_ingest_schema import location as schema\n'), ((5063, 5079), 'json.loads', 'json.loads', (['line'], {}), '(line)\n', (5073, 5079), False, 'import json\n'), ((5166, 5198), 'json.dump', 'json.dump', (['normalized_site', 'fout'], {}), '(normalized_site, fout)\n', (5175, 5198), False, 'import json\n'), ((2961, 3011), 'vaccine_feed_ingest_schema.location.Vaccine', 'schema.Vaccine', ([], {'vaccine': 'schema.VaccineType.MODERNA'}), '(vaccine=schema.VaccineType.MODERNA)\n', (2975, 3011), True, 'from vaccine_feed_ingest_schema import location as schema\n'), ((3080, 3138), 'vaccine_feed_ingest_schema.location.Vaccine', 'schema.Vaccine', ([], {'vaccine': 'schema.VaccineType.PFIZER_BIONTECH'}), '(vaccine=schema.VaccineType.PFIZER_BIONTECH)\n', (3094, 3138), True, 'from vaccine_feed_ingest_schema import location as schema\n'), ((3225, 3291), 'vaccine_feed_ingest_schema.location.Vaccine', 'schema.Vaccine', ([], {'vaccine': 'schema.VaccineType.JOHNSON_JOHNSON_JANSSEN'}), '(vaccine=schema.VaccineType.JOHNSON_JOHNSON_JANSSEN)\n', (3239, 3291), True, 'from vaccine_feed_ingest_schema import location as schema\n')] |
from sqlalchemy import Boolean, Column, Integer, String
from app.models.base import Base
class OJ(Base):
__tablename__ = 'oj'
fields = ['id', 'name', 'status', 'need_password']
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(100), unique=True)
url = Column(String(1000))
status = Column(Integer, nullable=False)
need_password = Column(Boolean, nullable=False, default=False)
need_single_thread = Column(Boolean, nullable=False, default=False)
@classmethod
def get_by_name(cls, name):
r = cls.search(name=name)['data']
if r:
return r[0]
return cls.create(name=name, status=0)
| [
"sqlalchemy.String",
"sqlalchemy.Column"
] | [((199, 252), 'sqlalchemy.Column', 'Column', (['Integer'], {'primary_key': '(True)', 'autoincrement': '(True)'}), '(Integer, primary_key=True, autoincrement=True)\n', (205, 252), False, 'from sqlalchemy import Boolean, Column, Integer, String\n'), ((341, 372), 'sqlalchemy.Column', 'Column', (['Integer'], {'nullable': '(False)'}), '(Integer, nullable=False)\n', (347, 372), False, 'from sqlalchemy import Boolean, Column, Integer, String\n'), ((393, 439), 'sqlalchemy.Column', 'Column', (['Boolean'], {'nullable': '(False)', 'default': '(False)'}), '(Boolean, nullable=False, default=False)\n', (399, 439), False, 'from sqlalchemy import Boolean, Column, Integer, String\n'), ((465, 511), 'sqlalchemy.Column', 'Column', (['Boolean'], {'nullable': '(False)', 'default': '(False)'}), '(Boolean, nullable=False, default=False)\n', (471, 511), False, 'from sqlalchemy import Boolean, Column, Integer, String\n'), ((271, 282), 'sqlalchemy.String', 'String', (['(100)'], {}), '(100)\n', (277, 282), False, 'from sqlalchemy import Boolean, Column, Integer, String\n'), ((314, 326), 'sqlalchemy.String', 'String', (['(1000)'], {}), '(1000)\n', (320, 326), False, 'from sqlalchemy import Boolean, Column, Integer, String\n')] |
"""
Usage Instructions:
10-shot sinusoid:
python main.py --datasource=sinusoid --logdir=logs/sine/ --metatrain_iterations=70000 --norm=None --update_batch_size=10
10-shot sinusoid baselines:
python main.py --datasource=sinusoid --logdir=logs/sine/ --pretrain_iterations=70000 --metatrain_iterations=0 --norm=None --update_batch_size=10 --baseline=oracle
python main.py --datasource=sinusoid --logdir=logs/sine/ --pretrain_iterations=70000 --metatrain_iterations=0 --norm=None --update_batch_size=10
5-way, 1-shot omniglot:
python main.py --datasource=omniglot --metatrain_iterations=60000 --meta_batch_size=32 --update_batch_size=1 --update_lr=0.4 --num_updates=1 --logdir=logs/omniglot5way/
20-way, 1-shot omniglot:
python main.py --datasource=omniglot --metatrain_iterations=60000 --meta_batch_size=16 --update_batch_size=1 --num_classes=20 --update_lr=0.1 --num_updates=5 --logdir=logs/omniglot20way/
5-way 1-shot mini imagenet:
python main.py --datasource=miniimagenet --metatrain_iterations=60000 --meta_batch_size=4 --update_batch_size=1 --update_lr=0.01 --num_updates=5 --num_classes=5 --logdir=logs/miniimagenet1shot/ --num_filters=32 --max_pool=True
5-way 5-shot mini imagenet:
python main.py --datasource=miniimagenet --metatrain_iterations=60000 --meta_batch_size=4 --update_batch_size=5 --update_lr=0.01 --num_updates=5 --num_classes=5 --logdir=logs/miniimagenet5shot/ --num_filters=32 --max_pool=True
To run evaluation, use the '--train=False' flag and the '--test_set=True' flag to use the test set.
For omniglot and miniimagenet training, acquire the dataset online, put it in the correspoding data directory, and see the python script instructions in that directory to preprocess the data.
Note that better sinusoid results can be achieved by using a larger network.
"""
import csv
import numpy as np
import pickle
import random
import tensorflow as tf
import matplotlib.pyplot as plt
from data_generator import DataGenerator
from maml import MAML
from tensorflow.python.platform import flags
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
FLAGS = flags.FLAGS
## Dataset/method options
flags.DEFINE_string('datasource', 'sinusoid', 'sinusoid or omniglot or miniimagenet')
flags.DEFINE_integer('num_classes', 5, 'number of classes used in classification (e.g. 5-way classification).')
# oracle means task id is input (only suitable for sinusoid)
# flags.DEFINE_string('baseline', "oracle", 'oracle, or None')
flags.DEFINE_string('baseline', None, 'oracle, or None')
## Training options
flags.DEFINE_integer('pretrain_iterations', 0, 'number of pre-training iterations.')
flags.DEFINE_integer('metatrain_iterations', 15000, 'number of metatraining iterations.') # 15k for omniglot, 50k for sinusoid
flags.DEFINE_integer('meta_batch_size', 25, 'number of tasks sampled per meta-update')
flags.DEFINE_float('meta_lr', 0.001, 'the base learning rate of the generator')
flags.DEFINE_integer('update_batch_size', 5, 'number of examples used for inner gradient update (K for K-shot learning).')
flags.DEFINE_float('update_lr', 1e-3, 'step size alpha for inner gradient update.') # 0.1 for omniglot
# flags.DEFINE_float('update_lr', 1e-2, 'step size alpha for inner gradient update.') # 0.1 for omniglot
flags.DEFINE_integer('num_updates', 1, 'number of inner gradient updates during training.')
## Model options
flags.DEFINE_string('norm', 'batch_norm', 'batch_norm, layer_norm, or None')
flags.DEFINE_integer('num_filters', 64, 'number of filters for conv nets -- 32 for miniimagenet, 64 for omiglot.')
flags.DEFINE_bool('conv', True, 'whether or not to use a convolutional network, only applicable in some cases')
flags.DEFINE_bool('max_pool', False, 'Whether or not to use max pooling rather than strided convolutions')
flags.DEFINE_bool('stop_grad', False, 'if True, do not use second derivatives in meta-optimization (for speed)')
flags.DEFINE_float('keep_prob', 0.5, 'if not None, used as keep_prob for all layers')
flags.DEFINE_bool('drop_connect', True, 'if True, use dropconnect, otherwise, use dropout')
# flags.DEFINE_float('keep_prob', None, 'if not None, used as keep_prob for all layers')
## Logging, saving, and testing options
flags.DEFINE_bool('log', True, 'if false, do not log summaries, for debugging code.')
flags.DEFINE_string('logdir', '/tmp/data', 'directory for summaries and checkpoints.')
flags.DEFINE_bool('resume', False, 'resume training if there is a model available')
flags.DEFINE_bool('train', True, 'True to train, False to test.')
flags.DEFINE_integer('test_iter', -1, 'iteration to load model (-1 for latest model)')
flags.DEFINE_bool('test_set', False, 'Set to true to test on the the test set, False for the validation set.')
flags.DEFINE_integer('train_update_batch_size', -1, 'number of examples used for gradient update during training (use if you want to test with a different number).')
flags.DEFINE_float('train_update_lr', -1, 'value of inner gradient step step during training. (use if you want to test with a different value)') # 0.1 for omniglot
def train(model, saver, sess, exp_string, data_generator, resume_itr=0):
SUMMARY_INTERVAL = 100
SAVE_INTERVAL = 1000
if FLAGS.datasource == 'sinusoid':
PRINT_INTERVAL = 1000
TEST_PRINT_INTERVAL = PRINT_INTERVAL*5
else:
PRINT_INTERVAL = 100
TEST_PRINT_INTERVAL = PRINT_INTERVAL*5
if FLAGS.log:
train_writer = tf.summary.FileWriter(FLAGS.logdir + '/' + exp_string, sess.graph)
print('Done initializing, starting training.')
prelosses, postlosses = [], []
num_classes = data_generator.num_classes # for classification, 1 otherwise
multitask_weights, reg_weights = [], []
for itr in range(resume_itr, FLAGS.pretrain_iterations + FLAGS.metatrain_iterations):
feed_dict = {}
if 'generate' in dir(data_generator):
batch_x, batch_y, amp, phase = data_generator.generate()
if FLAGS.baseline == 'oracle':
batch_x = np.concatenate([batch_x, np.zeros([batch_x.shape[0], batch_x.shape[1], 2])], 2)
for i in range(FLAGS.meta_batch_size):
batch_x[i, :, 1] = amp[i]
batch_x[i, :, 2] = phase[i]
inputa = batch_x[:, :num_classes*FLAGS.update_batch_size, :]
labela = batch_y[:, :num_classes*FLAGS.update_batch_size, :]
inputb = batch_x[:, num_classes*FLAGS.update_batch_size:, :] # b used for testing
labelb = batch_y[:, num_classes*FLAGS.update_batch_size:, :]
feed_dict = {model.inputa: inputa, model.inputb: inputb, model.labela: labela, model.labelb: labelb}
if itr < FLAGS.pretrain_iterations:
input_tensors = [model.pretrain_op]
else:
input_tensors = [model.metatrain_op]
if (itr % SUMMARY_INTERVAL == 0 or itr % PRINT_INTERVAL == 0):
input_tensors.extend([model.summ_op, model.total_loss1, model.total_losses2[FLAGS.num_updates-1]])
if model.classification:
input_tensors.extend([model.total_accuracy1, model.total_accuracies2[FLAGS.num_updates-1]])
result = sess.run(input_tensors, feed_dict)
if itr % SUMMARY_INTERVAL == 0:
prelosses.append(result[-2])
if FLAGS.log:
train_writer.add_summary(result[1], itr)
postlosses.append(result[-1])
if (itr!=0) and itr % PRINT_INTERVAL == 0:
if itr < FLAGS.pretrain_iterations:
print_str = 'Pretrain Iteration ' + str(itr)
else:
print_str = 'Iteration ' + str(itr - FLAGS.pretrain_iterations)
print_str += ': ' + str(np.mean(prelosses)) + ', ' + str(np.mean(postlosses))
print(print_str)
prelosses, postlosses = [], []
if (itr!=0) and itr % SAVE_INTERVAL == 0:
saver.save(sess, FLAGS.logdir + '/' + exp_string + '/model' + str(itr))
# sinusoid is infinite data, so no need to test on meta-validation set.
if (itr!=0) and itr % TEST_PRINT_INTERVAL == 0 and FLAGS.datasource !='sinusoid':
if 'generate' not in dir(data_generator):
feed_dict = {}
if model.classification:
input_tensors = [model.metaval_total_accuracy1, model.metaval_total_accuracies2[FLAGS.num_updates-1], model.summ_op]
else:
input_tensors = [model.metaval_total_loss1, model.metaval_total_losses2[FLAGS.num_updates-1], model.summ_op]
else:
batch_x, batch_y, amp, phase = data_generator.generate(train=False)
inputa = batch_x[:, :num_classes*FLAGS.update_batch_size, :]
inputb = batch_x[:, num_classes*FLAGS.update_batch_size:, :]
labela = batch_y[:, :num_classes*FLAGS.update_batch_size, :]
labelb = batch_y[:, num_classes*FLAGS.update_batch_size:, :]
feed_dict = {model.inputa: inputa, model.inputb: inputb, model.labela: labela, model.labelb: labelb, model.meta_lr: 0.0}
if model.classification:
input_tensors = [model.total_accuracy1, model.total_accuracies2[FLAGS.num_updates-1]]
else:
input_tensors = [model.total_loss1, model.total_losses2[FLAGS.num_updates-1]]
result = sess.run(input_tensors, feed_dict)
print('Validation results: ' + str(result[0]) + ', ' + str(result[1]))
saver.save(sess, FLAGS.logdir + '/' + exp_string + '/model' + str(itr))
# calculated for omniglot
NUM_TEST_POINTS = 600
def generate_test():
batch_size = 2
num_points = 101
# amp = np.array([3, 5])
# phase = np.array([0, 2.3])
amp = np.array([5, 3])
phase = np.array([2.3, 0])
outputs = np.zeros([batch_size, num_points, 1])
init_inputs = np.zeros([batch_size, num_points, 1])
for func in range(batch_size):
init_inputs[func, :, 0] = np.linspace(-5, 5, num_points)
outputs[func] = amp[func] * np.sin(init_inputs[func] - phase[func])
if FLAGS.baseline == 'oracle': # NOTE - this flag is specific to sinusoid
init_inputs = np.concatenate([init_inputs, np.zeros([init_inputs.shape[0], init_inputs.shape[1], 2])], 2)
for i in range(batch_size):
init_inputs[i, :, 1] = amp[i]
init_inputs[i, :, 2] = phase[i]
return init_inputs, outputs, amp, phase
def test_line_limit_Baye(model, sess, exp_string, mc_simulation=20, points_train=10, random_seed=1999):
inputs_all, outputs_all, amp_test, phase_test = generate_test()
np.random.seed(random_seed)
index = np.random.choice(inputs_all.shape[1], [inputs_all.shape[0], points_train], replace=False)
inputs_a = np.zeros([inputs_all.shape[0], points_train, inputs_all.shape[2]])
outputs_a = np.zeros([outputs_all.shape[0], points_train, outputs_all.shape[2]])
for line in range(len(index)):
inputs_a[line] = inputs_all[line, index[line], :]
outputs_a[line] = outputs_all[line, index[line], :]
feed_dict_line = {model.inputa: inputs_a, model.inputb: inputs_all, model.labela: outputs_a, model.labelb: outputs_all, model.meta_lr: 0.0}
mc_prediction = []
for mc_iter in range(mc_simulation):
predictions_all = sess.run(model.outputbs, feed_dict_line)
mc_prediction.append(np.array(predictions_all))
print("total mc simulation: ", mc_simulation)
print("shape of predictions_all is: ", predictions_all[0].shape)
prob_mean = np.nanmean(mc_prediction, axis=0)
prob_variance = np.var(mc_prediction, axis=0)
for line in range(len(inputs_all)):
plt.figure()
plt.plot(inputs_all[line, ..., 0].squeeze(), outputs_all[line, ..., 0].squeeze(), "r-", label="ground_truth")
# for update_step in range(len(predictions_all)):
for update_step in [0, len(predictions_all)-1]:
X = inputs_all[line, ..., 0].squeeze()
mu = prob_mean[update_step][line, ...].squeeze()
uncertainty = np.sqrt(prob_variance[update_step][line, ...].squeeze())
plt.plot(X, mu, "--", label="update_step_{:d}".format(update_step))
plt.fill_between(X, mu + uncertainty, mu - uncertainty, alpha=0.1)
plt.legend()
out_figure = FLAGS.logdir + '/' + exp_string + '/' + 'test_ubs' + str(
FLAGS.update_batch_size) + '_stepsize' + str(FLAGS.update_lr) + 'line_{0:d}_numtrain_{1:d}_seed_{2:d}.png'.format(line, points_train, random_seed)
plt.plot(inputs_a[line, :, 0], outputs_a[line, :, 0], "b*", label="training points")
plt.savefig(out_figure, bbox_inches="tight", dpi=300)
plt.close()
def test_line_limit(model, sess, exp_string, num_train=10, random_seed=1999):
inputs_all, outputs_all, amp_test, phase_test = generate_test()
np.random.seed(random_seed)
index = np.random.choice(inputs_all.shape[1], [inputs_all.shape[0], num_train], replace=False)
inputs_a = np.zeros([inputs_all.shape[0], num_train, inputs_all.shape[2]])
outputs_a = np.zeros([outputs_all.shape[0], num_train, outputs_all.shape[2]])
for line in range(len(index)):
inputs_a[line] = inputs_all[line, index[line], :]
outputs_a[line] = outputs_all[line, index[line], :]
feed_dict_line = {model.inputa: inputs_a, model.inputb: inputs_all, model.labela: outputs_a, model.labelb: outputs_all, model.meta_lr: 0.0}
predictions_all = sess.run([model.outputas, model.outputbs], feed_dict_line)
print("shape of predictions_all is: ", predictions_all[0].shape)
for line in range(len(inputs_all)):
plt.figure()
plt.plot(inputs_all[line, ..., 0].squeeze(), outputs_all[line, ..., 0].squeeze(), "r-", label="ground_truth")
for update_step in range(len(predictions_all[1])):
plt.plot(inputs_all[line, ..., 0].squeeze(), predictions_all[1][update_step][line, ...].squeeze(), "--", label="update_step_{:d}".format(update_step))
plt.legend()
out_figure = FLAGS.logdir + '/' + exp_string + '/' + 'test_ubs' + str(
FLAGS.update_batch_size) + '_stepsize' + str(FLAGS.update_lr) + 'line_{0:d}_numtrain_{1:d}_seed_{2:d}.png'.format(line, num_train, random_seed)
plt.plot(inputs_a[line, :, 0], outputs_a[line, :, 0], "b*", label="training points")
plt.savefig(out_figure, bbox_inches="tight", dpi=300)
plt.close()
def test_line(model, sess, exp_string):
inputs_all, outputs_all, amp_test, phase_test = generate_test()
feed_dict_line = {model.inputa: inputs_all, model.inputb: inputs_all, model.labela: outputs_all, model.labelb: outputs_all, model.meta_lr: 0.0}
predictions_all = sess.run([model.outputas, model.outputbs], feed_dict_line)
print("shape of predictions_all is: ", predictions_all[0].shape)
for line in range(len(inputs_all)):
plt.figure()
plt.plot(inputs_all[line, ..., 0].squeeze(), outputs_all[line, ..., 0].squeeze(), "r-", label="ground_truth")
for update_step in range(len(predictions_all[1])):
plt.plot(inputs_all[line, ..., 0].squeeze(), predictions_all[1][update_step][line, ...].squeeze(), "--", label="update_step_{:d}".format(update_step))
plt.legend()
out_figure = FLAGS.logdir + '/' + exp_string + '/' + 'test_ubs' + str(
FLAGS.update_batch_size) + '_stepsize' + str(FLAGS.update_lr) + 'line_{0:d}.png'.format(line)
plt.savefig(out_figure, bbox_inches="tight", dpi=300)
plt.close()
# for line in range(len(inputs_all)):
# plt.figure()
# plt.plot(inputs_all[line, ..., 0].squeeze(), outputs_all[line, ..., 0].squeeze(), "r-", label="ground_truth")
#
# plt.plot(inputs_all[line, ..., 0].squeeze(), predictions_all[0][line, ...].squeeze(), "--",
# label="initial")
# plt.legend()
#
# out_figure = FLAGS.logdir + '/' + exp_string + '/' + 'test_ubs' + str(
# FLAGS.update_batch_size) + '_stepsize' + str(FLAGS.update_lr) + 'init_line_{0:d}.png'.format(line)
#
# plt.savefig(out_figure, bbox_inches="tight", dpi=300)
# plt.close()
def test(model, saver, sess, exp_string, data_generator, test_num_updates=None):
num_classes = data_generator.num_classes # for classification, 1 otherwise
np.random.seed(1)
random.seed(1)
metaval_accuracies = []
for _ in range(NUM_TEST_POINTS):
if 'generate' not in dir(data_generator):
feed_dict = {}
feed_dict = {model.meta_lr : 0.0}
else:
batch_x, batch_y, amp, phase = data_generator.generate(train=False)
if FLAGS.baseline == 'oracle': # NOTE - this flag is specific to sinusoid
batch_x = np.concatenate([batch_x, np.zeros([batch_x.shape[0], batch_x.shape[1], 2])], 2)
batch_x[0, :, 1] = amp[0]
batch_x[0, :, 2] = phase[0]
inputa = batch_x[:, :num_classes*FLAGS.update_batch_size, :]
inputb = batch_x[:,num_classes*FLAGS.update_batch_size:, :]
labela = batch_y[:, :num_classes*FLAGS.update_batch_size, :]
labelb = batch_y[:,num_classes*FLAGS.update_batch_size:, :]
feed_dict = {model.inputa: inputa, model.inputb: inputb, model.labela: labela, model.labelb: labelb, model.meta_lr: 0.0}
if model.classification:
result = sess.run([model.metaval_total_accuracy1] + model.metaval_total_accuracies2, feed_dict)
else: # this is for sinusoid
result = sess.run([model.total_loss1] + model.total_losses2, feed_dict)
metaval_accuracies.append(result)
metaval_accuracies = np.array(metaval_accuracies)
means = np.mean(metaval_accuracies, 0)
stds = np.std(metaval_accuracies, 0)
ci95 = 1.96*stds/np.sqrt(NUM_TEST_POINTS)
print('Mean validation accuracy/loss, stddev, and confidence intervals')
print((means, stds, ci95))
out_filename = FLAGS.logdir +'/'+ exp_string + '/' + 'test_ubs' + str(FLAGS.update_batch_size) + '_stepsize' + str(FLAGS.update_lr) + '.csv'
out_pkl = FLAGS.logdir +'/'+ exp_string + '/' + 'test_ubs' + str(FLAGS.update_batch_size) + '_stepsize' + str(FLAGS.update_lr) + '.pkl'
with open(out_pkl, 'wb') as f:
pickle.dump({'mses': metaval_accuracies}, f)
with open(out_filename, 'w') as f:
writer = csv.writer(f, delimiter=',')
writer.writerow(['update'+str(i) for i in range(len(means))])
writer.writerow(means)
writer.writerow(stds)
writer.writerow(ci95)
def main():
if FLAGS.datasource == 'sinusoid':
if FLAGS.train:
test_num_updates = 5
else:
test_num_updates = 10
else:
if FLAGS.datasource == 'miniimagenet':
if FLAGS.train == True:
test_num_updates = 1 # eval on at least one update during training
else:
test_num_updates = 10
else:
test_num_updates = 10
if FLAGS.train == False:
orig_meta_batch_size = FLAGS.meta_batch_size
# always use meta batch size of 1 when testing.
FLAGS.meta_batch_size = 1
if FLAGS.datasource == 'sinusoid':
data_generator = DataGenerator(FLAGS.update_batch_size*2, FLAGS.meta_batch_size)
else:
if FLAGS.metatrain_iterations == 0 and FLAGS.datasource == 'miniimagenet':
assert FLAGS.meta_batch_size == 1
assert FLAGS.update_batch_size == 1
data_generator = DataGenerator(1, FLAGS.meta_batch_size) # only use one datapoint,
else:
if FLAGS.datasource == 'miniimagenet': # TODO - use 15 val examples for imagenet?
if FLAGS.train:
data_generator = DataGenerator(FLAGS.update_batch_size+15, FLAGS.meta_batch_size) # only use one datapoint for testing to save memory
else:
data_generator = DataGenerator(FLAGS.update_batch_size*2, FLAGS.meta_batch_size) # only use one datapoint for testing to save memory
else:
data_generator = DataGenerator(FLAGS.update_batch_size*2, FLAGS.meta_batch_size) # only use one datapoint for testing to save memory
dim_output = data_generator.dim_output
if FLAGS.baseline == 'oracle':
assert FLAGS.datasource == 'sinusoid'
dim_input = 3
FLAGS.pretrain_iterations += FLAGS.metatrain_iterations
FLAGS.metatrain_iterations = 0
else:
dim_input = data_generator.dim_input
if FLAGS.datasource == 'miniimagenet' or FLAGS.datasource == 'omniglot':
tf_data_load = True
num_classes = data_generator.num_classes
if FLAGS.train: # only construct training model if needed
random.seed(5)
image_tensor, label_tensor = data_generator.make_data_tensor()
inputa = tf.slice(image_tensor, [0,0,0], [-1,num_classes*FLAGS.update_batch_size, -1])
inputb = tf.slice(image_tensor, [0,num_classes*FLAGS.update_batch_size, 0], [-1,-1,-1])
labela = tf.slice(label_tensor, [0,0,0], [-1,num_classes*FLAGS.update_batch_size, -1])
labelb = tf.slice(label_tensor, [0,num_classes*FLAGS.update_batch_size, 0], [-1,-1,-1])
input_tensors = {'inputa': inputa, 'inputb': inputb, 'labela': labela, 'labelb': labelb}
random.seed(6)
image_tensor, label_tensor = data_generator.make_data_tensor(train=False)
inputa = tf.slice(image_tensor, [0,0,0], [-1,num_classes*FLAGS.update_batch_size, -1])
inputb = tf.slice(image_tensor, [0,num_classes*FLAGS.update_batch_size, 0], [-1,-1,-1])
labela = tf.slice(label_tensor, [0,0,0], [-1,num_classes*FLAGS.update_batch_size, -1])
labelb = tf.slice(label_tensor, [0,num_classes*FLAGS.update_batch_size, 0], [-1,-1,-1])
metaval_input_tensors = {'inputa': inputa, 'inputb': inputb, 'labela': labela, 'labelb': labelb}
else:
tf_data_load = False
input_tensors = None
model = MAML(dim_input, dim_output, test_num_updates=test_num_updates)
if FLAGS.train or not tf_data_load:
model.construct_model(input_tensors=input_tensors, prefix='metatrain_')
if tf_data_load:
model.construct_model(input_tensors=metaval_input_tensors, prefix='metaval_')
model.summ_op = tf.summary.merge_all()
saver = loader = tf.train.Saver(tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES), max_to_keep=10)
sess = tf.InteractiveSession()
if FLAGS.train == False:
# change to original meta batch size when loading model.
FLAGS.meta_batch_size = orig_meta_batch_size
if FLAGS.train_update_batch_size == -1:
FLAGS.train_update_batch_size = FLAGS.update_batch_size
if FLAGS.train_update_lr == -1:
FLAGS.train_update_lr = FLAGS.update_lr
exp_string = 'cls_'+str(FLAGS.num_classes)+'.mbs_'+str(FLAGS.meta_batch_size) + '.ubs_' + str(FLAGS.train_update_batch_size) + '.numstep' + str(FLAGS.num_updates) + '.updatelr' + str(FLAGS.train_update_lr)
if FLAGS.num_filters != 64:
exp_string += 'hidden' + str(FLAGS.num_filters)
if FLAGS.max_pool:
exp_string += 'maxpool'
if FLAGS.stop_grad:
exp_string += 'stopgrad'
if FLAGS.baseline:
exp_string += FLAGS.baseline
if FLAGS.norm == 'batch_norm':
exp_string += 'batchnorm'
elif FLAGS.norm == 'layer_norm':
exp_string += 'layernorm'
elif FLAGS.norm == 'None':
exp_string += 'nonorm'
else:
print('Norm setting not recognized.')
if FLAGS.pretrain_iterations != 0:
exp_string += '.pt' + str(FLAGS.pretrain_iterations)
if FLAGS.metatrain_iterations != 0:
exp_string += '.mt' + str(FLAGS.metatrain_iterations)
if FLAGS.keep_prob is not None:
exp_string += "kp{:.2f}".format(FLAGS.keep_prob)
if FLAGS.drop_connect is True:
exp_string += ".dropconn"
resume_itr = 0
model_file = None
tf.global_variables_initializer().run()
tf.train.start_queue_runners()
if FLAGS.resume or not FLAGS.train:
if exp_string == 'cls_5.mbs_25.ubs_10.numstep1.updatelr0.001nonorm.mt70000':
model_file = 'logs/sine//cls_5.mbs_25.ubs_10.numstep1.updatelr0.001nonorm.mt70000/model69999'
else:
model_file = tf.train.latest_checkpoint(FLAGS.logdir + '/' + exp_string)
# model_file = 'logs/sine//cls_5.mbs_25.ubs_10.numstep1.updatelr0.001nonorm.mt70000/model69999'
if FLAGS.test_iter > 0:
model_file = model_file[:model_file.index('model')] + 'model' + str(FLAGS.test_iter)
if model_file:
ind1 = model_file.index('model')
resume_itr = int(model_file[ind1+5:])
print("Restoring model weights from " + model_file)
saver.restore(sess, model_file)
if FLAGS.train:
train(model, saver, sess, exp_string, data_generator, resume_itr)
else:
# test_line(model, sess, exp_string)
# test_line_limit(model, sess, exp_string, num_train=2, random_seed=1999)
test_line_limit_Baye(model, sess, exp_string, mc_simulation=20, points_train=10, random_seed=1999)
# test(model, saver, sess, exp_string, data_generator, test_num_updates)
if __name__ == "__main__":
main()
# import matplotlib.pyplot as plt
# plt.plot(inputa.squeeze(), labela.squeeze(), "*")
# re = sess.run(model.result, feed_dict)
# plt.plot(inputa.squeeze(), re[0].squeeze(), "*")
# plt.savefig("/home/cougarnet.uh.edu/pyuan2/Projects2019/maml/Figures/maml/preda.png", bbox_inches="tight", dpi=300)
# for i in range(len(re[1])):
# plt.figure()
# plt.plot(inputb.squeeze(), labelb.squeeze(), "*")
# plt.plot(inputb.squeeze(), re[1][i].squeeze(), "*")
# plt.savefig("/home/cougarnet.uh.edu/pyuan2/Projects2019/maml/Figures/maml/predb_{:d}.png".format(i), bbox_inches="tight", dpi=300)
# plt.close()
# plt.figure()
# plt.imshow(metaval_accuracies)
# plt.savefig("/home/cougarnet.uh.edu/pyuan2/Projects2019/maml/Figures/maml/losses.png", bbox_inches="tight", dpi=300)
## Generate all sine
# def generate_test():
# amp_range = [0.1, 5.0]
# phase_range = [0, np.pi]
# batch_size = 100
# num_points = 101
# # amp = np.array([3, 5])
# # phase = np.array([0, 2.3])
# amp = np.random.uniform(amp_range[0], amp_range[1], [batch_size])
# phase = np.random.uniform(phase_range[0], phase_range[1], [batch_size])
# outputs = np.zeros([batch_size, num_points, 1])
# init_inputs = np.zeros([batch_size, num_points, 1])
# for func in range(batch_size):
# init_inputs[func, :, 0] = np.linspace(-5, 5, num_points)
# outputs[func] = amp[func] * np.sin(init_inputs[func] - phase[func])
# return init_inputs, outputs, amp, phase
# init_inputs, outputs, amp, phase = generate_test()
# plt.figure()
# for i in range(len(init_inputs)):
# plt.plot(init_inputs[i].squeeze(), outputs[i].squeeze())
| [
"numpy.sqrt",
"matplotlib.pyplot.fill_between",
"numpy.array",
"numpy.nanmean",
"numpy.sin",
"numpy.mean",
"tensorflow.slice",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.close",
"numpy.linspace",
"numpy.random.seed",
"tensorflow.summary.merge_all",
"tensorflow.python.platform.flags.DEFINE_... | [((2210, 2299), 'tensorflow.python.platform.flags.DEFINE_string', 'flags.DEFINE_string', (['"""datasource"""', '"""sinusoid"""', '"""sinusoid or omniglot or miniimagenet"""'], {}), "('datasource', 'sinusoid',\n 'sinusoid or omniglot or miniimagenet')\n", (2229, 2299), False, 'from tensorflow.python.platform import flags\n'), ((2296, 2411), 'tensorflow.python.platform.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""num_classes"""', '(5)', '"""number of classes used in classification (e.g. 5-way classification)."""'], {}), "('num_classes', 5,\n 'number of classes used in classification (e.g. 5-way classification).')\n", (2316, 2411), False, 'from tensorflow.python.platform import flags\n'), ((2532, 2588), 'tensorflow.python.platform.flags.DEFINE_string', 'flags.DEFINE_string', (['"""baseline"""', 'None', '"""oracle, or None"""'], {}), "('baseline', None, 'oracle, or None')\n", (2551, 2588), False, 'from tensorflow.python.platform import flags\n'), ((2610, 2698), 'tensorflow.python.platform.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""pretrain_iterations"""', '(0)', '"""number of pre-training iterations."""'], {}), "('pretrain_iterations', 0,\n 'number of pre-training iterations.')\n", (2630, 2698), False, 'from tensorflow.python.platform import flags\n'), ((2695, 2788), 'tensorflow.python.platform.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""metatrain_iterations"""', '(15000)', '"""number of metatraining iterations."""'], {}), "('metatrain_iterations', 15000,\n 'number of metatraining iterations.')\n", (2715, 2788), False, 'from tensorflow.python.platform import flags\n'), ((2822, 2912), 'tensorflow.python.platform.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""meta_batch_size"""', '(25)', '"""number of tasks sampled per meta-update"""'], {}), "('meta_batch_size', 25,\n 'number of tasks sampled per meta-update')\n", (2842, 2912), False, 'from tensorflow.python.platform import flags\n'), ((2909, 2988), 'tensorflow.python.platform.flags.DEFINE_float', 'flags.DEFINE_float', (['"""meta_lr"""', '(0.001)', '"""the base learning rate of the generator"""'], {}), "('meta_lr', 0.001, 'the base learning rate of the generator')\n", (2927, 2988), False, 'from tensorflow.python.platform import flags\n'), ((2989, 3120), 'tensorflow.python.platform.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""update_batch_size"""', '(5)', '"""number of examples used for inner gradient update (K for K-shot learning)."""'], {}), "('update_batch_size', 5,\n 'number of examples used for inner gradient update (K for K-shot learning).'\n )\n", (3009, 3120), False, 'from tensorflow.python.platform import flags\n'), ((3112, 3200), 'tensorflow.python.platform.flags.DEFINE_float', 'flags.DEFINE_float', (['"""update_lr"""', '(0.001)', '"""step size alpha for inner gradient update."""'], {}), "('update_lr', 0.001,\n 'step size alpha for inner gradient update.')\n", (3130, 3200), False, 'from tensorflow.python.platform import flags\n'), ((3320, 3415), 'tensorflow.python.platform.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""num_updates"""', '(1)', '"""number of inner gradient updates during training."""'], {}), "('num_updates', 1,\n 'number of inner gradient updates during training.')\n", (3340, 3415), False, 'from tensorflow.python.platform import flags\n'), ((3430, 3506), 'tensorflow.python.platform.flags.DEFINE_string', 'flags.DEFINE_string', (['"""norm"""', '"""batch_norm"""', '"""batch_norm, layer_norm, or None"""'], {}), "('norm', 'batch_norm', 'batch_norm, layer_norm, or None')\n", (3449, 3506), False, 'from tensorflow.python.platform import flags\n'), ((3507, 3625), 'tensorflow.python.platform.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""num_filters"""', '(64)', '"""number of filters for conv nets -- 32 for miniimagenet, 64 for omiglot."""'], {}), "('num_filters', 64,\n 'number of filters for conv nets -- 32 for miniimagenet, 64 for omiglot.')\n", (3527, 3625), False, 'from tensorflow.python.platform import flags\n'), ((3622, 3742), 'tensorflow.python.platform.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""conv"""', '(True)', '"""whether or not to use a convolutional network, only applicable in some cases"""'], {}), "('conv', True,\n 'whether or not to use a convolutional network, only applicable in some cases'\n )\n", (3639, 3742), False, 'from tensorflow.python.platform import flags\n'), ((3734, 3844), 'tensorflow.python.platform.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""max_pool"""', '(False)', '"""Whether or not to use max pooling rather than strided convolutions"""'], {}), "('max_pool', False,\n 'Whether or not to use max pooling rather than strided convolutions')\n", (3751, 3844), False, 'from tensorflow.python.platform import flags\n'), ((3841, 3957), 'tensorflow.python.platform.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""stop_grad"""', '(False)', '"""if True, do not use second derivatives in meta-optimization (for speed)"""'], {}), "('stop_grad', False,\n 'if True, do not use second derivatives in meta-optimization (for speed)')\n", (3858, 3957), False, 'from tensorflow.python.platform import flags\n'), ((3954, 4043), 'tensorflow.python.platform.flags.DEFINE_float', 'flags.DEFINE_float', (['"""keep_prob"""', '(0.5)', '"""if not None, used as keep_prob for all layers"""'], {}), "('keep_prob', 0.5,\n 'if not None, used as keep_prob for all layers')\n", (3972, 4043), False, 'from tensorflow.python.platform import flags\n'), ((4040, 4135), 'tensorflow.python.platform.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""drop_connect"""', '(True)', '"""if True, use dropconnect, otherwise, use dropout"""'], {}), "('drop_connect', True,\n 'if True, use dropconnect, otherwise, use dropout')\n", (4057, 4135), False, 'from tensorflow.python.platform import flags\n'), ((4262, 4351), 'tensorflow.python.platform.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""log"""', '(True)', '"""if false, do not log summaries, for debugging code."""'], {}), "('log', True,\n 'if false, do not log summaries, for debugging code.')\n", (4279, 4351), False, 'from tensorflow.python.platform import flags\n'), ((4348, 4438), 'tensorflow.python.platform.flags.DEFINE_string', 'flags.DEFINE_string', (['"""logdir"""', '"""/tmp/data"""', '"""directory for summaries and checkpoints."""'], {}), "('logdir', '/tmp/data',\n 'directory for summaries and checkpoints.')\n", (4367, 4438), False, 'from tensorflow.python.platform import flags\n'), ((4435, 4522), 'tensorflow.python.platform.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""resume"""', '(False)', '"""resume training if there is a model available"""'], {}), "('resume', False,\n 'resume training if there is a model available')\n", (4452, 4522), False, 'from tensorflow.python.platform import flags\n'), ((4519, 4584), 'tensorflow.python.platform.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""train"""', '(True)', '"""True to train, False to test."""'], {}), "('train', True, 'True to train, False to test.')\n", (4536, 4584), False, 'from tensorflow.python.platform import flags\n'), ((4585, 4675), 'tensorflow.python.platform.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""test_iter"""', '(-1)', '"""iteration to load model (-1 for latest model)"""'], {}), "('test_iter', -1,\n 'iteration to load model (-1 for latest model)')\n", (4605, 4675), False, 'from tensorflow.python.platform import flags\n'), ((4672, 4786), 'tensorflow.python.platform.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""test_set"""', '(False)', '"""Set to true to test on the the test set, False for the validation set."""'], {}), "('test_set', False,\n 'Set to true to test on the the test set, False for the validation set.')\n", (4689, 4786), False, 'from tensorflow.python.platform import flags\n'), ((4783, 4957), 'tensorflow.python.platform.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""train_update_batch_size"""', '(-1)', '"""number of examples used for gradient update during training (use if you want to test with a different number)."""'], {}), "('train_update_batch_size', -1,\n 'number of examples used for gradient update during training (use if you want to test with a different number).'\n )\n", (4803, 4957), False, 'from tensorflow.python.platform import flags\n'), ((4949, 5102), 'tensorflow.python.platform.flags.DEFINE_float', 'flags.DEFINE_float', (['"""train_update_lr"""', '(-1)', '"""value of inner gradient step step during training. (use if you want to test with a different value)"""'], {}), "('train_update_lr', -1,\n 'value of inner gradient step step during training. (use if you want to test with a different value)'\n )\n", (4967, 5102), False, 'from tensorflow.python.platform import flags\n'), ((9817, 9833), 'numpy.array', 'np.array', (['[5, 3]'], {}), '([5, 3])\n', (9825, 9833), True, 'import numpy as np\n'), ((9846, 9864), 'numpy.array', 'np.array', (['[2.3, 0]'], {}), '([2.3, 0])\n', (9854, 9864), True, 'import numpy as np\n'), ((9879, 9916), 'numpy.zeros', 'np.zeros', (['[batch_size, num_points, 1]'], {}), '([batch_size, num_points, 1])\n', (9887, 9916), True, 'import numpy as np\n'), ((9935, 9972), 'numpy.zeros', 'np.zeros', (['[batch_size, num_points, 1]'], {}), '([batch_size, num_points, 1])\n', (9943, 9972), True, 'import numpy as np\n'), ((10688, 10715), 'numpy.random.seed', 'np.random.seed', (['random_seed'], {}), '(random_seed)\n', (10702, 10715), True, 'import numpy as np\n'), ((10728, 10821), 'numpy.random.choice', 'np.random.choice', (['inputs_all.shape[1]', '[inputs_all.shape[0], points_train]'], {'replace': '(False)'}), '(inputs_all.shape[1], [inputs_all.shape[0], points_train],\n replace=False)\n', (10744, 10821), True, 'import numpy as np\n'), ((10833, 10899), 'numpy.zeros', 'np.zeros', (['[inputs_all.shape[0], points_train, inputs_all.shape[2]]'], {}), '([inputs_all.shape[0], points_train, inputs_all.shape[2]])\n', (10841, 10899), True, 'import numpy as np\n'), ((10916, 10984), 'numpy.zeros', 'np.zeros', (['[outputs_all.shape[0], points_train, outputs_all.shape[2]]'], {}), '([outputs_all.shape[0], points_train, outputs_all.shape[2]])\n', (10924, 10984), True, 'import numpy as np\n'), ((11607, 11640), 'numpy.nanmean', 'np.nanmean', (['mc_prediction'], {'axis': '(0)'}), '(mc_prediction, axis=0)\n', (11617, 11640), True, 'import numpy as np\n'), ((11661, 11690), 'numpy.var', 'np.var', (['mc_prediction'], {'axis': '(0)'}), '(mc_prediction, axis=0)\n', (11667, 11690), True, 'import numpy as np\n'), ((12927, 12954), 'numpy.random.seed', 'np.random.seed', (['random_seed'], {}), '(random_seed)\n', (12941, 12954), True, 'import numpy as np\n'), ((12967, 13057), 'numpy.random.choice', 'np.random.choice', (['inputs_all.shape[1]', '[inputs_all.shape[0], num_train]'], {'replace': '(False)'}), '(inputs_all.shape[1], [inputs_all.shape[0], num_train],\n replace=False)\n', (12983, 13057), True, 'import numpy as np\n'), ((13069, 13132), 'numpy.zeros', 'np.zeros', (['[inputs_all.shape[0], num_train, inputs_all.shape[2]]'], {}), '([inputs_all.shape[0], num_train, inputs_all.shape[2]])\n', (13077, 13132), True, 'import numpy as np\n'), ((13149, 13214), 'numpy.zeros', 'np.zeros', (['[outputs_all.shape[0], num_train, outputs_all.shape[2]]'], {}), '([outputs_all.shape[0], num_train, outputs_all.shape[2]])\n', (13157, 13214), True, 'import numpy as np\n'), ((16413, 16430), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (16427, 16430), True, 'import numpy as np\n'), ((16435, 16449), 'random.seed', 'random.seed', (['(1)'], {}), '(1)\n', (16446, 16449), False, 'import random\n'), ((17772, 17800), 'numpy.array', 'np.array', (['metaval_accuracies'], {}), '(metaval_accuracies)\n', (17780, 17800), True, 'import numpy as np\n'), ((17813, 17843), 'numpy.mean', 'np.mean', (['metaval_accuracies', '(0)'], {}), '(metaval_accuracies, 0)\n', (17820, 17843), True, 'import numpy as np\n'), ((17855, 17884), 'numpy.std', 'np.std', (['metaval_accuracies', '(0)'], {}), '(metaval_accuracies, 0)\n', (17861, 17884), True, 'import numpy as np\n'), ((22125, 22187), 'maml.MAML', 'MAML', (['dim_input', 'dim_output'], {'test_num_updates': 'test_num_updates'}), '(dim_input, dim_output, test_num_updates=test_num_updates)\n', (22129, 22187), False, 'from maml import MAML\n'), ((22435, 22457), 'tensorflow.summary.merge_all', 'tf.summary.merge_all', ([], {}), '()\n', (22455, 22457), True, 'import tensorflow as tf\n'), ((22576, 22599), 'tensorflow.InteractiveSession', 'tf.InteractiveSession', ([], {}), '()\n', (22597, 22599), True, 'import tensorflow as tf\n'), ((24126, 24156), 'tensorflow.train.start_queue_runners', 'tf.train.start_queue_runners', ([], {}), '()\n', (24154, 24156), True, 'import tensorflow as tf\n'), ((5483, 5549), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (["(FLAGS.logdir + '/' + exp_string)", 'sess.graph'], {}), "(FLAGS.logdir + '/' + exp_string, sess.graph)\n", (5504, 5549), True, 'import tensorflow as tf\n'), ((10042, 10072), 'numpy.linspace', 'np.linspace', (['(-5)', '(5)', 'num_points'], {}), '(-5, 5, num_points)\n', (10053, 10072), True, 'import numpy as np\n'), ((11740, 11752), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (11750, 11752), True, 'import matplotlib.pyplot as plt\n'), ((12347, 12359), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (12357, 12359), True, 'import matplotlib.pyplot as plt\n'), ((12607, 12696), 'matplotlib.pyplot.plot', 'plt.plot', (['inputs_a[line, :, 0]', 'outputs_a[line, :, 0]', '"""b*"""'], {'label': '"""training points"""'}), "(inputs_a[line, :, 0], outputs_a[line, :, 0], 'b*', label=\n 'training points')\n", (12615, 12696), True, 'import matplotlib.pyplot as plt\n'), ((12701, 12754), 'matplotlib.pyplot.savefig', 'plt.savefig', (['out_figure'], {'bbox_inches': '"""tight"""', 'dpi': '(300)'}), "(out_figure, bbox_inches='tight', dpi=300)\n", (12712, 12754), True, 'import matplotlib.pyplot as plt\n'), ((12763, 12774), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (12772, 12774), True, 'import matplotlib.pyplot as plt\n'), ((13712, 13724), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (13722, 13724), True, 'import matplotlib.pyplot as plt\n'), ((14073, 14085), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (14083, 14085), True, 'import matplotlib.pyplot as plt\n'), ((14330, 14419), 'matplotlib.pyplot.plot', 'plt.plot', (['inputs_a[line, :, 0]', 'outputs_a[line, :, 0]', '"""b*"""'], {'label': '"""training points"""'}), "(inputs_a[line, :, 0], outputs_a[line, :, 0], 'b*', label=\n 'training points')\n", (14338, 14419), True, 'import matplotlib.pyplot as plt\n'), ((14424, 14477), 'matplotlib.pyplot.savefig', 'plt.savefig', (['out_figure'], {'bbox_inches': '"""tight"""', 'dpi': '(300)'}), "(out_figure, bbox_inches='tight', dpi=300)\n", (14435, 14477), True, 'import matplotlib.pyplot as plt\n'), ((14486, 14497), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (14495, 14497), True, 'import matplotlib.pyplot as plt\n'), ((14958, 14970), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (14968, 14970), True, 'import matplotlib.pyplot as plt\n'), ((15319, 15331), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (15329, 15331), True, 'import matplotlib.pyplot as plt\n'), ((15527, 15580), 'matplotlib.pyplot.savefig', 'plt.savefig', (['out_figure'], {'bbox_inches': '"""tight"""', 'dpi': '(300)'}), "(out_figure, bbox_inches='tight', dpi=300)\n", (15538, 15580), True, 'import matplotlib.pyplot as plt\n'), ((15589, 15600), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (15598, 15600), True, 'import matplotlib.pyplot as plt\n'), ((17906, 17930), 'numpy.sqrt', 'np.sqrt', (['NUM_TEST_POINTS'], {}), '(NUM_TEST_POINTS)\n', (17913, 17930), True, 'import numpy as np\n'), ((18369, 18413), 'pickle.dump', 'pickle.dump', (["{'mses': metaval_accuracies}", 'f'], {}), "({'mses': metaval_accuracies}, f)\n", (18380, 18413), False, 'import pickle\n'), ((18470, 18498), 'csv.writer', 'csv.writer', (['f'], {'delimiter': '""","""'}), "(f, delimiter=',')\n", (18480, 18498), False, 'import csv\n'), ((19336, 19401), 'data_generator.DataGenerator', 'DataGenerator', (['(FLAGS.update_batch_size * 2)', 'FLAGS.meta_batch_size'], {}), '(FLAGS.update_batch_size * 2, FLAGS.meta_batch_size)\n', (19349, 19401), False, 'from data_generator import DataGenerator\n'), ((21460, 21474), 'random.seed', 'random.seed', (['(6)'], {}), '(6)\n', (21471, 21474), False, 'import random\n'), ((21574, 21661), 'tensorflow.slice', 'tf.slice', (['image_tensor', '[0, 0, 0]', '[-1, num_classes * FLAGS.update_batch_size, -1]'], {}), '(image_tensor, [0, 0, 0], [-1, num_classes * FLAGS.\n update_batch_size, -1])\n', (21582, 21661), True, 'import tensorflow as tf\n'), ((21669, 21757), 'tensorflow.slice', 'tf.slice', (['image_tensor', '[0, num_classes * FLAGS.update_batch_size, 0]', '[-1, -1, -1]'], {}), '(image_tensor, [0, num_classes * FLAGS.update_batch_size, 0], [-1, \n -1, -1])\n', (21677, 21757), True, 'import tensorflow as tf\n'), ((21765, 21852), 'tensorflow.slice', 'tf.slice', (['label_tensor', '[0, 0, 0]', '[-1, num_classes * FLAGS.update_batch_size, -1]'], {}), '(label_tensor, [0, 0, 0], [-1, num_classes * FLAGS.\n update_batch_size, -1])\n', (21773, 21852), True, 'import tensorflow as tf\n'), ((21860, 21948), 'tensorflow.slice', 'tf.slice', (['label_tensor', '[0, num_classes * FLAGS.update_batch_size, 0]', '[-1, -1, -1]'], {}), '(label_tensor, [0, num_classes * FLAGS.update_batch_size, 0], [-1, \n -1, -1])\n', (21868, 21948), True, 'import tensorflow as tf\n'), ((22495, 22546), 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.TRAINABLE_VARIABLES'], {}), '(tf.GraphKeys.TRAINABLE_VARIABLES)\n', (22512, 22546), True, 'import tensorflow as tf\n'), ((10109, 10148), 'numpy.sin', 'np.sin', (['(init_inputs[func] - phase[func])'], {}), '(init_inputs[func] - phase[func])\n', (10115, 10148), True, 'import numpy as np\n'), ((11444, 11469), 'numpy.array', 'np.array', (['predictions_all'], {}), '(predictions_all)\n', (11452, 11469), True, 'import numpy as np\n'), ((12272, 12338), 'matplotlib.pyplot.fill_between', 'plt.fill_between', (['X', '(mu + uncertainty)', '(mu - uncertainty)'], {'alpha': '(0.1)'}), '(X, mu + uncertainty, mu - uncertainty, alpha=0.1)\n', (12288, 12338), True, 'import matplotlib.pyplot as plt\n'), ((19616, 19655), 'data_generator.DataGenerator', 'DataGenerator', (['(1)', 'FLAGS.meta_batch_size'], {}), '(1, FLAGS.meta_batch_size)\n', (19629, 19655), False, 'from data_generator import DataGenerator\n'), ((20862, 20876), 'random.seed', 'random.seed', (['(5)'], {}), '(5)\n', (20873, 20876), False, 'import random\n'), ((20973, 21060), 'tensorflow.slice', 'tf.slice', (['image_tensor', '[0, 0, 0]', '[-1, num_classes * FLAGS.update_batch_size, -1]'], {}), '(image_tensor, [0, 0, 0], [-1, num_classes * FLAGS.\n update_batch_size, -1])\n', (20981, 21060), True, 'import tensorflow as tf\n'), ((21072, 21160), 'tensorflow.slice', 'tf.slice', (['image_tensor', '[0, num_classes * FLAGS.update_batch_size, 0]', '[-1, -1, -1]'], {}), '(image_tensor, [0, num_classes * FLAGS.update_batch_size, 0], [-1, \n -1, -1])\n', (21080, 21160), True, 'import tensorflow as tf\n'), ((21172, 21259), 'tensorflow.slice', 'tf.slice', (['label_tensor', '[0, 0, 0]', '[-1, num_classes * FLAGS.update_batch_size, -1]'], {}), '(label_tensor, [0, 0, 0], [-1, num_classes * FLAGS.\n update_batch_size, -1])\n', (21180, 21259), True, 'import tensorflow as tf\n'), ((21271, 21359), 'tensorflow.slice', 'tf.slice', (['label_tensor', '[0, num_classes * FLAGS.update_batch_size, 0]', '[-1, -1, -1]'], {}), '(label_tensor, [0, num_classes * FLAGS.update_batch_size, 0], [-1, \n -1, -1])\n', (21279, 21359), True, 'import tensorflow as tf\n'), ((24082, 24115), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (24113, 24115), True, 'import tensorflow as tf\n'), ((24428, 24487), 'tensorflow.train.latest_checkpoint', 'tf.train.latest_checkpoint', (["(FLAGS.logdir + '/' + exp_string)"], {}), "(FLAGS.logdir + '/' + exp_string)\n", (24454, 24487), True, 'import tensorflow as tf\n'), ((10280, 10337), 'numpy.zeros', 'np.zeros', (['[init_inputs.shape[0], init_inputs.shape[1], 2]'], {}), '([init_inputs.shape[0], init_inputs.shape[1], 2])\n', (10288, 10337), True, 'import numpy as np\n'), ((20205, 20270), 'data_generator.DataGenerator', 'DataGenerator', (['(FLAGS.update_batch_size * 2)', 'FLAGS.meta_batch_size'], {}), '(FLAGS.update_batch_size * 2, FLAGS.meta_batch_size)\n', (20218, 20270), False, 'from data_generator import DataGenerator\n'), ((7788, 7807), 'numpy.mean', 'np.mean', (['postlosses'], {}), '(postlosses)\n', (7795, 7807), True, 'import numpy as np\n'), ((19860, 19926), 'data_generator.DataGenerator', 'DataGenerator', (['(FLAGS.update_batch_size + 15)', 'FLAGS.meta_batch_size'], {}), '(FLAGS.update_batch_size + 15, FLAGS.meta_batch_size)\n', (19873, 19926), False, 'from data_generator import DataGenerator\n'), ((20037, 20102), 'data_generator.DataGenerator', 'DataGenerator', (['(FLAGS.update_batch_size * 2)', 'FLAGS.meta_batch_size'], {}), '(FLAGS.update_batch_size * 2, FLAGS.meta_batch_size)\n', (20050, 20102), False, 'from data_generator import DataGenerator\n'), ((6084, 6133), 'numpy.zeros', 'np.zeros', (['[batch_x.shape[0], batch_x.shape[1], 2]'], {}), '([batch_x.shape[0], batch_x.shape[1], 2])\n', (6092, 6133), True, 'import numpy as np\n'), ((16872, 16921), 'numpy.zeros', 'np.zeros', (['[batch_x.shape[0], batch_x.shape[1], 2]'], {}), '([batch_x.shape[0], batch_x.shape[1], 2])\n', (16880, 16921), True, 'import numpy as np\n'), ((7755, 7773), 'numpy.mean', 'np.mean', (['prelosses'], {}), '(prelosses)\n', (7762, 7773), True, 'import numpy as np\n')] |
from typing import Callable, AsyncGenerator, Generator
import asyncio
import httpx
import pytest
from asgi_lifespan import LifespanManager
from fastapi import FastAPI
from fastapi.testclient import TestClient
TestClientGenerator = Callable[[FastAPI], AsyncGenerator[httpx.AsyncClient, None]]
@pytest.fixture(scope="session")
def event_loop():
loop = asyncio.get_event_loop()
yield loop
loop.close()
@pytest.fixture
async def client(
request: pytest.FixtureRequest,
) -> AsyncGenerator[httpx.AsyncClient, None]:
marker = request.node.get_closest_marker("fastapi")
if marker is None:
raise ValueError("client fixture: the marker fastapi must be provided")
try:
app = marker.kwargs["app"]
except KeyError:
raise ValueError(
"client fixture: keyword argument app must be provided in the marker"
)
if not isinstance(app, FastAPI):
raise ValueError("client fixture: app must be a FastAPI instance")
dependency_overrides = marker.kwargs.get("dependency_overrides")
if dependency_overrides:
if not isinstance(dependency_overrides, dict):
raise ValueError(
"client fixture: dependency_overrides must be a dictionary"
)
app.dependency_overrides = dependency_overrides
run_lifespan_events = marker.kwargs.get("run_lifespan_events", True)
if not isinstance(run_lifespan_events, bool):
raise ValueError("client fixture: run_lifespan_events must be a bool")
test_client_generator = httpx.AsyncClient(app=app, base_url="http://app.io")
if run_lifespan_events:
async with LifespanManager(app):
async with test_client_generator as test_client:
yield test_client
else:
async with test_client_generator as test_client:
yield test_client
@pytest.fixture
def websocket_client(
request: pytest.FixtureRequest,
event_loop: asyncio.AbstractEventLoop,
) -> Generator[TestClient, None, None]:
asyncio.set_event_loop(event_loop)
marker = request.node.get_closest_marker("fastapi")
if marker is None:
raise ValueError("client fixture: the marker fastapi must be provided")
try:
app = marker.kwargs["app"]
except KeyError:
raise ValueError(
"client fixture: keyword argument app must be provided in the marker"
)
if not isinstance(app, FastAPI):
raise ValueError("client fixture: app must be a FastAPI instance")
dependency_overrides = marker.kwargs.get("dependency_overrides")
if dependency_overrides:
if not isinstance(dependency_overrides, dict):
raise ValueError(
"client fixture: dependency_overrides must be a dictionary"
)
app.dependency_overrides = dependency_overrides
with TestClient(app) as test_client:
yield test_client
| [
"fastapi.testclient.TestClient",
"httpx.AsyncClient",
"pytest.fixture",
"asyncio.set_event_loop",
"asyncio.get_event_loop",
"asgi_lifespan.LifespanManager"
] | [((297, 328), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (311, 328), False, 'import pytest\n'), ((358, 382), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (380, 382), False, 'import asyncio\n'), ((1549, 1601), 'httpx.AsyncClient', 'httpx.AsyncClient', ([], {'app': 'app', 'base_url': '"""http://app.io"""'}), "(app=app, base_url='http://app.io')\n", (1566, 1601), False, 'import httpx\n'), ((2026, 2060), 'asyncio.set_event_loop', 'asyncio.set_event_loop', (['event_loop'], {}), '(event_loop)\n', (2048, 2060), False, 'import asyncio\n'), ((2856, 2871), 'fastapi.testclient.TestClient', 'TestClient', (['app'], {}), '(app)\n', (2866, 2871), False, 'from fastapi.testclient import TestClient\n'), ((1649, 1669), 'asgi_lifespan.LifespanManager', 'LifespanManager', (['app'], {}), '(app)\n', (1664, 1669), False, 'from asgi_lifespan import LifespanManager\n')] |
import numpy as np
import torch
from scipy.stats import norm
from codes.worker import ByzantineWorker
from codes.aggregator import DecentralizedAggregator
class DecentralizedByzantineWorker(ByzantineWorker):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# The target of attack
self.target = None
self.tagg = None
self.target_good_neighbors = None
def _initialize_target(self):
if self.target is None:
assert len(self.running["neighbor_workers"]) == 1
self.target = self.running["neighbor_workers"][0]
self.tagg = self.target.running["aggregator"]
self.target_good_neighbors = self.simulator.get_good_neighbor_workers(
self.target.running["node"]
)
class DissensusWorker(DecentralizedByzantineWorker):
def __init__(self, epsilon, *args, **kwargs):
super().__init__(*args, **kwargs)
self.epsilon = epsilon
def _attack_decentralized_aggregator(self, mixing=None):
tm = self.target.running["flattened_model"]
# Compute Byzantine weights
partial_sum = []
partial_byz_weights = []
for neighbor in self.target.running["neighbor_workers"]:
nm = neighbor.running["flattened_model"]
nn = neighbor.running["node"]
nw = mixing or self.tagg.weights[nn.index]
if isinstance(neighbor, ByzantineWorker):
partial_byz_weights.append(nw)
else:
partial_sum.append(nw * (nm - tm))
partial_sum = sum(partial_sum)
partial_byz_weights = sum(partial_byz_weights)
return tm, partial_sum / partial_byz_weights
def pre_aggr(self, epoch, batch):
self._initialize_target()
if isinstance(self.tagg, DecentralizedAggregator):
# Dissensus using the gossip weight
tm, v = self._attack_decentralized_aggregator()
self.running["flattened_model"] = tm - self.epsilon * v
else:
# TODO: check
# Dissensus using the gossip weight
mixing = 1 / (len(self.target.running["neighbor_workers"]) + 1)
tm, v = self._attack_decentralized_aggregator(mixing)
self.running["flattened_model"] = tm - self.epsilon * v
class BitFlippingWorker(ByzantineWorker):
def __str__(self) -> str:
return "BitFlippingWorker"
def pre_aggr(self, epoch, batch):
self.running["flattened_model"] = -self.running["flattened_model"]
class LabelFlippingWorker(ByzantineWorker):
def __init__(self, revertible_label_transformer, *args, **kwargs):
"""
Args:
revertible_label_transformer (callable):
E.g. lambda label: 9 - label
"""
super().__init__(*args, **kwargs)
self.revertible_label_transformer = revertible_label_transformer
def train_epoch_start(self) -> None:
super().train_epoch_start()
self.running["train_loader_iterator"].__next__ = self._wrap_iterator(
self.running["train_loader_iterator"].__next__
)
def _wrap_iterator(self, func):
def wrapper():
data, target = func()
return data, self.revertible_label_transformer(target)
return wrapper
def _wrap_metric(self, func):
def wrapper(output, target):
return func(output, self.revertible_label_transformer(target))
return wrapper
def add_metric(self, name, callback):
if name in self.metrics or name in ["loss", "length"]:
raise KeyError(f"Metrics ({name}) already added.")
self.metrics[name] = self._wrap_metric(callback)
def __str__(self) -> str:
return "LabelFlippingWorker"
class ALittleIsEnoughAttack(DecentralizedByzantineWorker):
"""
Adapted for the decentralized environment.
Args:
n (int): Total number of workers
m (int): Number of Byzantine workers
"""
def __init__(self, n, m, z=None, *args, **kwargs):
super().__init__(*args, **kwargs)
# Number of supporters
if z is not None:
self.z_max = z
else:
s = np.floor(n / 2 + 1) - m
cdf_value = (n - m - s) / (n - m)
self.z_max = norm.ppf(cdf_value)
self.n_good = n - m
def get_gradient(self):
return 0
def set_gradient(self, gradient):
pass
def apply_gradient(self):
pass
def pre_aggr(self, epoch, batch):
self._initialize_target()
tm = self.target.running["flattened_model"]
models = [tm]
for neighbor in self.target_good_neighbors:
models.append(neighbor.running["flattened_model"])
stacked_models = torch.stack(models, 1)
mu = torch.mean(stacked_models, 1)
std = torch.std(stacked_models, 1)
self.running["flattened_model"] = mu - std * self.z_max
class IPMAttack(DecentralizedByzantineWorker):
def __init__(self, epsilon, *args, **kwargs):
super().__init__(*args, **kwargs)
self.epsilon = epsilon
def get_gradient(self):
return 0
def set_gradient(self, gradient):
pass
def apply_gradient(self):
pass
def pre_aggr(self, epoch, batch):
self._initialize_target()
tm = self.target.running["flattened_model"]
models = [tm]
for neighbor in self.target_good_neighbors:
models.append(neighbor.running["flattened_model"])
self.running["flattened_model"] = -self.epsilon * sum(models) / len(models)
def get_attackers(
args, rank, trainer, model, opt, loss_func, loader, device, lr_scheduler
):
if args.attack == "BF":
return BitFlippingWorker(
simulator=trainer,
index=rank,
data_loader=loader,
model=model,
loss_func=loss_func,
device=device,
optimizer=opt,
lr_scheduler=lr_scheduler,
)
if args.attack == "LF":
return LabelFlippingWorker(
revertible_label_transformer=lambda label: 9 - label,
simulator=trainer,
index=rank,
data_loader=loader,
model=model,
loss_func=loss_func,
device=device,
optimizer=opt,
lr_scheduler=lr_scheduler,
)
if args.attack.startswith("ALIE"):
if args.attack == "ALIE":
z = None
else:
z = float(args.attack[4:])
attacker = ALittleIsEnoughAttack(
n=args.n,
m=args.f,
z=z,
simulator=trainer,
index=rank,
data_loader=loader,
model=model,
loss_func=loss_func,
device=device,
optimizer=opt,
lr_scheduler=lr_scheduler,
)
return attacker
if args.attack == "IPM":
attacker = IPMAttack(
epsilon=0.1,
simulator=trainer,
index=rank,
data_loader=loader,
model=model,
loss_func=loss_func,
device=device,
optimizer=opt,
lr_scheduler=lr_scheduler,
)
return attacker
if args.attack.startswith("dissensus"):
epsilon = float(args.attack[len("dissensus") :])
attacker = DissensusWorker(
epsilon=epsilon,
simulator=trainer,
index=rank,
data_loader=loader,
model=model,
loss_func=loss_func,
device=device,
optimizer=opt,
lr_scheduler=lr_scheduler,
)
return attacker
raise NotImplementedError(f"No such attack {args.attack}")
| [
"torch.mean",
"torch.stack",
"scipy.stats.norm.ppf",
"numpy.floor",
"torch.std"
] | [((4811, 4833), 'torch.stack', 'torch.stack', (['models', '(1)'], {}), '(models, 1)\n', (4822, 4833), False, 'import torch\n'), ((4847, 4876), 'torch.mean', 'torch.mean', (['stacked_models', '(1)'], {}), '(stacked_models, 1)\n', (4857, 4876), False, 'import torch\n'), ((4891, 4919), 'torch.std', 'torch.std', (['stacked_models', '(1)'], {}), '(stacked_models, 1)\n', (4900, 4919), False, 'import torch\n'), ((4332, 4351), 'scipy.stats.norm.ppf', 'norm.ppf', (['cdf_value'], {}), '(cdf_value)\n', (4340, 4351), False, 'from scipy.stats import norm\n'), ((4237, 4256), 'numpy.floor', 'np.floor', (['(n / 2 + 1)'], {}), '(n / 2 + 1)\n', (4245, 4256), True, 'import numpy as np\n')] |
#!/usr/bin/env python
#coding: utf8
"""Zipper
A class that can zip and unzip files.
"""
__author__ = "<NAME>"
__license__ = "GPLv3+"
import os
import zipfile
try:
import zlib
has_zlib = True
except:
has_zlib = False
class Zipper(object):
"""This is the main class.
Can zip and unzip files.
"""
def zip(self, file_to_zip, dir="./", name="Zipped_File.zip", mode="w"):
"""Zips file into dir with name.
Mode can be w to write a new file or
a to append in an existing file.
"""
if not name.endswith(".zip"):
name += ".zip"
if has_zlib:
compression = zipfile.ZIP_DEFLATED
else:
compression = zipfile.ZIP_STORED
zf = zipfile.ZipFile(name, mode)
zf.write(file_to_zip, compress_type=compression)
zf.close()
def unzip(self, file_to_unzip, dir="./"):
"""Unzips file into dir."""
zf = zipfile.ZipFile(file_to_unzip)
for content in zf.namelist():
if content.endswith('/'):
os.makedirs(content)
else:
out_file= open(os.path.join(dir, content), "wb")
out_file.write(zf.read(content))
out_file.close()
#EOF
| [
"os.makedirs",
"os.path.join",
"zipfile.ZipFile"
] | [((812, 839), 'zipfile.ZipFile', 'zipfile.ZipFile', (['name', 'mode'], {}), '(name, mode)\n', (827, 839), False, 'import zipfile\n'), ((1025, 1055), 'zipfile.ZipFile', 'zipfile.ZipFile', (['file_to_unzip'], {}), '(file_to_unzip)\n', (1040, 1055), False, 'import zipfile\n'), ((1157, 1177), 'os.makedirs', 'os.makedirs', (['content'], {}), '(content)\n', (1168, 1177), False, 'import os\n'), ((1240, 1266), 'os.path.join', 'os.path.join', (['dir', 'content'], {}), '(dir, content)\n', (1252, 1266), False, 'import os\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Author: <NAME> <<EMAIL>>
# PGP: https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x00bebdd0437ad513a4a0e13d93435cab4ca92fb9
# Date: 05.11.2021
import argparse
import os
# Unicode placeholders and their replacements
uc_table = {
b"LRE": chr(0x202a).encode(),
b"RLE": chr(0x202b).encode(),
b"PDF": chr(0x202c).encode(),
b"LRO": chr(0x202d).encode(),
b"RLO": chr(0x202e).encode(),
b"LRI": chr(0x2066).encode(),
b"RLI": chr(0x2067).encode(),
b"FSI": chr(0x2068).encode(),
b"PDI": chr(0x2069).encode(),
b"EOL": chr(0x000a).encode()
}
# Reverted and decoded Unicode table
# to `unbidi` files
unbidi_table = {
chr(0x202a): "LRE",
chr(0x202b): "RLE",
chr(0x202c): "PDF",
chr(0x202d): "LRO",
chr(0x202e): "RLO",
chr(0x2066): "LRI",
chr(0x2067): "RLI",
chr(0x2068): "FSI",
chr(0x2069): "PDI",
}
def table():
# Print bidi-related Unicode characters (taken from unicode.org, see source below)
print("Abbreviation Code Point Name Description")
print("------------ ---------- ---- -----------")
print("LRE U+202A Left-to-Right Embedding Try treating following text as left-to-right.")
print("RLE U+202B Right-to-Left Embedding Try treating following text as right-to-left.")
print("PDF U+202C Pop Directional Formatting Terminate nearest LRE, RLE, LRO or RLO.")
print("LRO U+202D Left-to-Right Override Force treating following test as left-to-right.")
print("RLO U+202E Right-to-Left Override Force treating following test as right-to-left.")
print("LRI U+2066 Left-to-Right Isolate Force treating following text as left-to-right")
print(" without affecting adjacent text.")
print("RLI U+2067 Right-to-Left Isolate Force treating following text as right-to-left")
print(" without affecting adjacent text.")
print("FSI U+2068 First Strong Isolate Force treating following text in direction")
print(" indicated by the next character.")
print("PDI U+2069 Pop Directional Isolate Terminate nearest LRI or RLI.")
print("EOL U+000A End Of Line Character used to signify the end")
print(" of a line of text")
print("\nSource: https://www.unicode.org/reports/tr9/tr9-42.html")
print("Paper: https://www.trojansource.codes/trojan-source.pdf, p. 2")
def about():
print("Author: <NAME>")
print("Date: 05.11.2021")
print("Name: codegen.py")
print("Version: v0.0.2")
print("\nDescription")
print("Generate malicious code using bidi-attack (CVE-2021-42574)")
def create_payload(template: bytes) -> bytes:
# replace placeholders with unicode directionality formatting characters
payload = template
for uc in uc_table:
payload = payload.replace(uc, uc_table[uc])
return payload
def unbidi(code: bytes) -> str:
cnt = 0
for char in unbidi_table:
cnt += code.count(char)
code = code.replace(char, unbidi_table[char])
print(f"[i] Replaced {cnt} chars")
return code
def main():
# Parse command line arguments to object `args`
parser = argparse.ArgumentParser(description="Generate malicious code using bidi-attack (CVE-2021-42574)")
parser.add_argument("-m", "--mode", help="Use e|ncode to convert template to malicious code and d|ecode vice versa")
parser.add_argument("-i", "--infile", help="Input file containing unicode placeholders")
parser.add_argument("-o", "--outfile", help="Output file to store the final code")
parser.add_argument("-u", "--uctable", action="store_true", help="Supported bidi-related characters")
parser.add_argument("-a", "--about", action="store_true", help="Print about text")
args = vars(parser.parse_args())
# Print bidi-related unicode chars with description
if args["uctable"]:
table()
exit(0)
# Print about information
if args["about"]:
about()
exit(0)
# Check if required parameters exist
if not args["infile"] and not args["outfile"] and not args["mode"]:
parser.print_usage()
exit(0)
if args["mode"]:
if args["mode"] in ["e", "encode"]:
mode = "encode"
elif args["mode"] in ["d", "decode"]:
mode = "decode"
else:
print("[!] This mode does not exist. Use e|encode or d|decode. See -h|--help for further advice.")
exit(1)
else:
print("[!] Mode is missing.")
exit(1)
if args["infile"]:
infile = args["infile"]
else:
print("[!] Input file is missing")
exit(1)
if args["outfile"]:
outfile = args["outfile"]
else:
print("[!] Output file is missing")
exit(1)
# Check if template exist
if not os.path.exists(infile):
print("[!] Input file does not exist")
exit(1)
# Run method selected by mode arg
if mode == "encode":
code = open(infile, 'rb').read()
data = create_payload(code)
fmode = 'wb'
elif mode == "decode":
code = open(infile, 'r').read()
data = unbidi(code)
fmode = 'w'
# Store payload to output file
with open(outfile, fmode) as f:
f.write(data)
if __name__ == "__main__":
main()
| [
"os.path.exists",
"argparse.ArgumentParser"
] | [((3599, 3701), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Generate malicious code using bidi-attack (CVE-2021-42574)"""'}), "(description=\n 'Generate malicious code using bidi-attack (CVE-2021-42574)')\n", (3622, 3701), False, 'import argparse\n'), ((5267, 5289), 'os.path.exists', 'os.path.exists', (['infile'], {}), '(infile)\n', (5281, 5289), False, 'import os\n')] |
"""
Unit tests for the plugin_support module
This is just a hack to invoke it..not a unit test
Copyright 2022 <NAME>
SPDX-License-Identifier: Apache-2.0
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import os
import unittest
import context # add rvc2mqtt package to the python path using local reference
from rvc2mqtt.plugin_support import PluginSupport
p_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'rvc2mqtt', "entity"))
if __name__ == '__main__':
ps = PluginSupport( p_path, {})
fm = []
ps.register_with_factory_the_entity_plugins(fm) # will be list of tuples (dict of match parameters, class)
print(fm) | [
"os.path.dirname",
"rvc2mqtt.plugin_support.PluginSupport"
] | [((970, 995), 'rvc2mqtt.plugin_support.PluginSupport', 'PluginSupport', (['p_path', '{}'], {}), '(p_path, {})\n', (983, 995), False, 'from rvc2mqtt.plugin_support import PluginSupport\n'), ((877, 902), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (892, 902), False, 'import os\n')] |
from data_types.user import User
class PullRequestReview:
"""
GitHub Pull Request Review
https://developer.github.com/v3/pulls/reviews/
Attributes:
id: Review id
body: Review body text
html_url: Public URL for issue on github.com
state: approved|commented|changes_requested
user: Review author User object
submitted_at: Submitted time
pull_request_url: If issue linked in pull request, stores its public URL
"""
def __init__(self, data):
# Internal GitHub id
self.id = data.get('id', 0)
# Who create
self.user = None
if 'user' in data:
self.user = User(data['user'])
# Body
self.body = data.get('body', '')
# Dates
self.submitted_at = data.get('submitted_at', '')
self.html_url = data.get('html_url', '')
# Review result
self.state = data.get('state', '')
# Linked pull request
self.pull_request_url = ''
if 'pull_request' in data:
self.pull_request_url = data['pull_request'].get('html_url', '')
| [
"data_types.user.User"
] | [((689, 707), 'data_types.user.User', 'User', (["data['user']"], {}), "(data['user'])\n", (693, 707), False, 'from data_types.user import User\n')] |
"""Utilities for tests"""
import copy
import re
BAD_ID = "line %s: id '%s' doesn't match '%s'"
BAD_SEQLEN = "line %s: %s is not the same length as the first read (%s)"
BAD_BASES = "line %s: %s is not in allowed set of bases %s"
BAD_PLUS = "line %s: expected '+', got %s"
BAD_QUALS = "line %s: %s is not the same length as the first read (%s)"
MSG_INCOMPLETE = "incomplete record at end of file %s"
class Fastq:
"""A convenient data structure for handling the fastqs generated by qasim.
NOTES:
* Read id's are the form: @NAME_COORD1_COORD2_ERR1_ERR2_N/[1|2].
* COORD1 and COORD2 are the coordinates of the fragment ends.
* Illumina pair-end reads have read 1 forward and read 2 reverse:
>>>>>>>>>>>>>>
<<<<<<<<<<<<<<
* When run in normal (non-wgsim) mode, for pairs where read 1 is from
the reference strand the coordinates are ordered such that:
COORD1 < COORD2. For for "flipped" reads where read 1 is from the
reverse strand the coordinates are ordered such that:
COORD1 > COORD2.
* When run in legacy (wgsim) mode, coordinates are always ordered:
COORD1 < COORD2 and there's no way to tell by inspection what strand
a read is from."""
allowed_bases = {'A', 'C', 'G', 'T', 'N'}
complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'N': 'N'}
id_regex = re.compile(
r"^@(.+)_(\d+)_(\d+)_e(\d+)_e(\d+)_([a-f0-9]+)\/([12])$")
def __init__(self, filename):
self.records = []
self.read_length = -1
self.forwardized = False
self.minpos = -1
self.maxpos = -1
with open(filename, 'rt') as fh:
read = frag_start = frag_end = lastline = 0
for linenum, line in enumerate(fh.readlines(), 1):
lastline = linenum
if linenum % 4 == 1:
read_id = line.strip()
matches = self.id_regex.match(read_id)
assert matches, BAD_ID % (linenum, read_id, self.id_regex)
frag_start, frag_end = [
int(c) for c in matches.groups()[1:3]]
read = int(matches.groups()[-1])
elif linenum % 4 == 2:
seq = line.strip()
if self.read_length == -1:
self.read_length = len(seq)
else:
assert len(seq) == self.read_length, \
BAD_SEQLEN % (linenum, seq, self.read_length)
disallowed = set(seq) - self.allowed_bases
assert not disallowed, \
BAD_BASES % (linenum, disallowed, self.allowed_bases)
elif linenum % 4 == 3:
plus = line.strip()
assert plus == "+", BAD_PLUS % (linenum, plus)
if linenum % 4 == 0:
quals = line.strip()
assert len(quals) == self.read_length, \
BAD_QUALS % (linenum, quals, self.read_length)
self.records.append({
"id": read_id, "seq": seq, "quals": quals,
"frag_start": frag_start, "frag_end": frag_end,
"read": read})
low = min(frag_start, frag_end)
high = max(frag_start, frag_end)
if self.minpos == -1 or low < self.minpos:
self.minpos = low
if self.maxpos == -1 or high > self.maxpos:
self.maxpos = high
assert lastline % 4 == 0, MSG_INCOMPLETE % (filename)
def coverage(self, pos):
"""Return reads covering pos"""
# simple logic if all reads are forward on the reference strand:
if self.forwardized:
return [r for r in self.records if
r['read_start'] <= pos <=
r['read_start'] + self.read_length - 1]
# more cases to consider if not:
else:
covering = []
for r in self.records:
start = min(r['frag_start'], r['frag_end'])
end = max(r['frag_start'], r['frag_end'])
read = r['read']
flipped = True if r['frag_start'] > r['frag_end'] else False
if (read == 1 and not flipped and
start <= pos <= start + self.read_length - 1 or
read == 2 and not flipped and
end - self.read_length + 1 <= pos <= end or
read == 1 and flipped and
end - self.read_length + 1 <= pos <= end or
read == 2 and flipped and
start <= pos <= start + self.read_length - 1):
covering.append(r)
return covering
def basecounts(self):
"""Return a dict of { base: count } aggregated over all reads"""
counts = {}
for r in self.records:
for base in r['seq']:
counts[base] = counts.setdefault(base, 0) + 1
return counts
@classmethod
def forwardize(cls, original):
"""Return a copy of original with all reads turned into forward reads:
a calculational convenience"""
fwdized = copy.deepcopy(original)
for r in fwdized.records:
frag_start, frag_end = r['frag_start'], r['frag_end']
read = r['read']
if (read == 1 and frag_start < frag_end):
r['read_start'] = frag_start
elif (read == 1 and frag_start > frag_end):
r['seq'] = ''.join(cls.revcomp(r['seq']))
r['quals'] = ''.join(reversed(r['quals']))
r['read_start'] = frag_start - fwdized.read_length + 1
elif (read == 2 and frag_start < frag_end):
r['seq'] = ''.join(cls.revcomp(r['seq']))
r['quals'] = ''.join(reversed(r['quals']))
r['read_start'] = frag_end - fwdized.read_length + 1
elif (read == 2 and frag_start > frag_end):
r['read_start'] = frag_end
else:
raise Exception("Unhandled case:", r)
fwdized.forwardized = True
return fwdized
@classmethod
def revcomp(cls, seq):
return [cls.complement[b] for b in reversed(seq)]
| [
"copy.deepcopy",
"re.compile"
] | [((1426, 1498), 're.compile', 're.compile', (['"""^@(.+)_(\\\\d+)_(\\\\d+)_e(\\\\d+)_e(\\\\d+)_([a-f0-9]+)\\\\/([12])$"""'], {}), "('^@(.+)_(\\\\d+)_(\\\\d+)_e(\\\\d+)_e(\\\\d+)_([a-f0-9]+)\\\\/([12])$')\n", (1436, 1498), False, 'import re\n'), ((5412, 5435), 'copy.deepcopy', 'copy.deepcopy', (['original'], {}), '(original)\n', (5425, 5435), False, 'import copy\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import datetime
import pathlib
import gpxpy
import pandas as pd
import statistics
import seaborn
import matplotlib.pyplot as plt
from activity import Activity, create_activity, parse_activities_csv
def select_activity(activities, iso_date=None):
"""Given a list of activities and selection criteria, return the first activity which matches the criteria.
If no matching activity can be found, or selection criteria was not provided, simply return the most recent
activity.
"""
selected_activity = activities[-1]
if iso_date:
desired_datetime = datetime.datetime.fromisoformat(iso_date)
for activity in activities:
if desired_datetime.year == ride.date.year and \
desired_datetime.month == ride.date.month and \
desired_datetime.day == ride.date.day:
selected_activity = activity
break
print("Selected activity \"{}\" on {}".format(selected_activity.name, selected_activity.date))
return selected_activity
def crunch_total_metrics(rides):
"""Given activities, calculate and return several all time aggregations."""
total_distance = 0
total_elevation = 0
total_time = 0
for ride in rides:
total_distance += ride.distance
total_elevation += ride.elevation_gain
total_time += ride.moving_time
return (len(rides), total_time / 3600, total_distance, total_elevation)
def crunch_year_to_date_metrics(rides):
"""Given activities, calculate and return several year to date aggregations."""
current_datetime = datetime.datetime.now()
ytd_rides = 0
ytd_distance = 0
ytd_elevation = 0
ytd_time = 0
for ride in rides:
if ride.date.year == current_datetime.year:
ytd_rides += 1
ytd_distance += ride.distance
ytd_elevation += ride.elevation_gain
ytd_time += ride.moving_time
return (ytd_rides, ytd_time / 3600, ytd_distance, ytd_elevation)
def crunch_weekly_metrics(rides):
"""Given activities, calculate and return several week-based averages."""
ride_names = [ride.name for ride in rides]
ride_dates = [ride.date for ride in rides]
ride_moving_times = [ride.moving_time for ride in rides]
ride_distances = [ride.distance for ride in rides]
ride_elevations = [ride.elevation_gain for ride in rides]
date_df = pd.DataFrame(data={
"name": ride_names,
"date": ride_dates,
"moving_time": ride_moving_times,
"distance": ride_distances,
"elevation": ride_elevations
})
rides_by_week = date_df.groupby(pd.Grouper(key="date", freq="W"))
average_rides_per_week = statistics.mean([len(weekly_rides[1]) for weekly_rides in rides_by_week])
average_time_per_week = statistics.mean([sum(weekly_rides[1]["moving_time"] / 60) for weekly_rides in rides_by_week])
average_distance_per_week = statistics.mean([sum(weekly_rides[1]["distance"]) for weekly_rides in rides_by_week])
average_elevation_per_week = statistics.mean([sum(weekly_rides[1]["elevation"]) for weekly_rides in rides_by_week])
return (average_rides_per_week, average_time_per_week, average_distance_per_week, average_elevation_per_week)
| [
"pandas.DataFrame",
"datetime.datetime.now",
"pandas.Grouper",
"datetime.datetime.fromisoformat"
] | [((1653, 1676), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (1674, 1676), False, 'import datetime\n'), ((2460, 2619), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': "{'name': ride_names, 'date': ride_dates, 'moving_time': ride_moving_times,\n 'distance': ride_distances, 'elevation': ride_elevations}"}), "(data={'name': ride_names, 'date': ride_dates, 'moving_time':\n ride_moving_times, 'distance': ride_distances, 'elevation':\n ride_elevations})\n", (2472, 2619), True, 'import pandas as pd\n'), ((635, 676), 'datetime.datetime.fromisoformat', 'datetime.datetime.fromisoformat', (['iso_date'], {}), '(iso_date)\n', (666, 676), False, 'import datetime\n'), ((2694, 2726), 'pandas.Grouper', 'pd.Grouper', ([], {'key': '"""date"""', 'freq': '"""W"""'}), "(key='date', freq='W')\n", (2704, 2726), True, 'import pandas as pd\n')] |
from flask import Blueprint
bp_album = Blueprint('album', __name__)
from . import views
| [
"flask.Blueprint"
] | [((40, 68), 'flask.Blueprint', 'Blueprint', (['"""album"""', '__name__'], {}), "('album', __name__)\n", (49, 68), False, 'from flask import Blueprint\n')] |
import json
from base64 import b64encode, b64decode
from flask import abort, request, redirect
from simplecrypt import encrypt, decrypt
from secrets import ENCRYPTION_SECRET
def route_apis(app):
@app.route('/api/encrypt', methods=['GET', 'POST'])
def encrypt_layout():
if request.method == "POST":
try:
data = json.loads(request.data)
cipher = encrypt(ENCRYPTION_SECRET, json.dumps(data['data']))
encoded_cipher = b64encode(cipher).decode('utf-8')
return {
'status': 'ok',
'code': 200,
'payload': encoded_cipher
}
except (KeyError, ValueError, Exception) as e:
abort(400)
else:
return redirect("/")
@app.route('/api/decrypt', methods=['GET', 'POST'])
def decrypt_layout():
if request.method == "POST":
try:
data = json.loads(request.data)
cipher = b64decode(json.dumps(data['data']))
plaintext = decrypt(ENCRYPTION_SECRET, cipher).decode('utf-8')
return {
'status': 'ok',
'code': 200,
'payload': plaintext
}
except (KeyError, ValueError, Exception) as e:
abort(400)
else:
return redirect("/")
| [
"simplecrypt.decrypt",
"json.loads",
"base64.b64encode",
"json.dumps",
"flask.redirect",
"flask.abort"
] | [((805, 818), 'flask.redirect', 'redirect', (['"""/"""'], {}), "('/')\n", (813, 818), False, 'from flask import abort, request, redirect\n'), ((1417, 1430), 'flask.redirect', 'redirect', (['"""/"""'], {}), "('/')\n", (1425, 1430), False, 'from flask import abort, request, redirect\n'), ((358, 382), 'json.loads', 'json.loads', (['request.data'], {}), '(request.data)\n', (368, 382), False, 'import json\n'), ((979, 1003), 'json.loads', 'json.loads', (['request.data'], {}), '(request.data)\n', (989, 1003), False, 'import json\n'), ((435, 459), 'json.dumps', 'json.dumps', (["data['data']"], {}), "(data['data'])\n", (445, 459), False, 'import json\n'), ((761, 771), 'flask.abort', 'abort', (['(400)'], {}), '(400)\n', (766, 771), False, 'from flask import abort, request, redirect\n'), ((1040, 1064), 'json.dumps', 'json.dumps', (["data['data']"], {}), "(data['data'])\n", (1050, 1064), False, 'import json\n'), ((1373, 1383), 'flask.abort', 'abort', (['(400)'], {}), '(400)\n', (1378, 1383), False, 'from flask import abort, request, redirect\n'), ((494, 511), 'base64.b64encode', 'b64encode', (['cipher'], {}), '(cipher)\n', (503, 511), False, 'from base64 import b64encode, b64decode\n'), ((1094, 1128), 'simplecrypt.decrypt', 'decrypt', (['ENCRYPTION_SECRET', 'cipher'], {}), '(ENCRYPTION_SECRET, cipher)\n', (1101, 1128), False, 'from simplecrypt import encrypt, decrypt\n')] |
import re
_ARGS = r"\[[^]]+\]"
_IDENTITIFER = r"[a-zA-Z_][_0-9a-zA-Z]*"
_MODULE_PATH = r"[\.a-zA-Z_][\._0-9a-zA-Z]*"
def _REMEMBER(x, name):
return "(?P<{0}>{1})".format(name, x)
def _OPTIONAL(*x):
return "(?:{0})?".format(''.join(x))
FILTER_STRING_RE = ''.join((
'^',
_REMEMBER(_MODULE_PATH, "module_name"),
_OPTIONAL(
":",
_REMEMBER(_IDENTITIFER, "class_name"),
_OPTIONAL(
_REMEMBER(_ARGS, "setup_call")
),
_OPTIONAL(
".",
_REMEMBER(_IDENTITIFER, "method_name"),
_OPTIONAL(
_REMEMBER(_ARGS, "method_call")
)
)
),
'$'
))
FILTER_STRING_PATTERN = re.compile(FILTER_STRING_RE)
| [
"re.compile"
] | [((725, 753), 're.compile', 're.compile', (['FILTER_STRING_RE'], {}), '(FILTER_STRING_RE)\n', (735, 753), False, 'import re\n')] |
import time
import Ordem
class ContaTempo():
def compara(self, tamanho_da_lista):
'''Compara o tempo exercido para ordenar uma lista com o tamanho passado'''
l = Ordem.Lista()
lista1 = l.crialista(tamanho_da_lista)
lista2 = lista1[:]
o = Ordem.Ordenacao()
antes = time.time()
o.selection_sort(lista1)
time1 = time.time() - antes
antes = time.time()
o.bubble_sort(lista2)
time2 = time.time() - antes
print("Bubble Sort:", time2, "\nSelection Sort:", time1, "\n", time2 / time1)
c = ContaTempo()
c.compara(1000) | [
"Ordem.Ordenacao",
"Ordem.Lista",
"time.time"
] | [((178, 191), 'Ordem.Lista', 'Ordem.Lista', ([], {}), '()\n', (189, 191), False, 'import Ordem\n'), ((279, 296), 'Ordem.Ordenacao', 'Ordem.Ordenacao', ([], {}), '()\n', (294, 296), False, 'import Ordem\n'), ((311, 322), 'time.time', 'time.time', ([], {}), '()\n', (320, 322), False, 'import time\n'), ((409, 420), 'time.time', 'time.time', ([], {}), '()\n', (418, 420), False, 'import time\n'), ((368, 379), 'time.time', 'time.time', ([], {}), '()\n', (377, 379), False, 'import time\n'), ((463, 474), 'time.time', 'time.time', ([], {}), '()\n', (472, 474), False, 'import time\n')] |
#T# the following code shows how to draw the slope of the perpendicular line to a given line
#T# to draw the slope of the perpendicular line to a given line, the pyplot module of the matplotlib package is used
import matplotlib.pyplot as plt
#T# to transform the markers of a plot, import the MarkerStyle constructor
from matplotlib.markers import MarkerStyle
#T# create the figure and axes
fig1, ax1 = plt.subplots(1, 1)
#T# set the aspect of the axes
ax1.set_aspect('equal', adjustable = 'box')
#T# hide the spines and ticks
for it1 in ['top', 'right']:
ax1.spines[it1].set_visible(False)
#T# position the spines and ticks
for it1 in ['bottom', 'left']:
ax1.spines[it1].set_position(('data', 0))
#T# set the axes size
xmin1 = -8
xmax1 = 8
ymin1 = -8
ymax1 = 8
for it1 in fig1.axes:
it1.axis([xmin1, xmax1, ymin1, ymax1])
#T# set the ticks labels
list1_1 = list(range(xmin1, xmax1 + 1, 1))
list2_1 = list(range(ymin1, ymax1 + 1, 1))
list1_2 = ['' if it1 == 0 else str(it1) for it1 in list1_1]
list2_2 = ['' if it1 == 0 else str(it1) for it1 in list2_1]
ax1.set_xticks(list1_1)
ax1.set_yticks(list2_1)
ax1.set_xticklabels(list1_2)
ax1.set_yticklabels(list2_2)
#T# create the variables that define the plot
p1 = (0, 0)
m1 = 3
p2 = (0, 0)
m2 = -1/m1
#T# plot the figure
ax1.axline((p1[0], p1[1]), slope = m1)
ax1.axline((p1[0], p1[1]), slope = -m1, color = 'limegreen')
ax1.axline((p2[0], p2[1]), slope = m2, color = 'crimson')
#T# show the results
plt.show() | [
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
] | [((406, 424), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {}), '(1, 1)\n', (418, 424), True, 'import matplotlib.pyplot as plt\n'), ((1471, 1481), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1479, 1481), True, 'import matplotlib.pyplot as plt\n')] |
"""Test the mulled BioContainers image name generation."""
import pytest
from nf_core.modules import MulledImageNameGenerator
@pytest.mark.parametrize(
"specs, expected",
[
(["foo==0.1.2", "bar==1.1"], [("foo", "0.1.2"), ("bar", "1.1")]),
(["foo=0.1.2", "bar=1.1"], [("foo", "0.1.2"), ("bar", "1.1")]),
],
)
def test_target_parsing(specs, expected):
"""Test that valid specifications are correctly parsed into tool, version pairs."""
assert MulledImageNameGenerator.parse_targets(specs) == expected
@pytest.mark.parametrize(
"specs",
[
["foo<0.1.2", "bar==1.1"],
["foo=0.1.2", "bar>1.1"],
],
)
def test_wrong_specification(specs):
"""Test that unexpected version constraints fail."""
with pytest.raises(ValueError, match="expected format"):
MulledImageNameGenerator.parse_targets(specs)
@pytest.mark.parametrize(
"specs",
[
["foo==0a.1.2", "bar==1.1"],
["foo==0.1.2", "bar==1.b1b"],
],
)
def test_noncompliant_version(specs):
"""Test that version string that do not comply with PEP440 fail."""
with pytest.raises(ValueError, match="PEP440"):
MulledImageNameGenerator.parse_targets(specs)
@pytest.mark.parametrize(
"specs, expected",
[
(
[("chromap", "0.2.1"), ("samtools", "1.15")],
"mulled-v2-1f09f39f20b1c4ee36581dc81cc323c70e661633:bd74d08a359024829a7aec1638a28607bbcd8a58-0",
),
(
[("pysam", "0.16.0.1"), ("biopython", "1.78")],
"mulled-v2-3a59640f3fe1ed11819984087d31d68600200c3f:185a25ca79923df85b58f42deb48f5ac4481e91f-0",
),
(
[("samclip", "0.4.0"), ("samtools", "1.15")],
"mulled-v2-d057255d4027721f3ab57f6a599a2ae81cb3cbe3:13051b049b6ae536d76031ba94a0b8e78e364815-0",
),
],
)
def test_generate_image_name(specs, expected):
"""Test that a known image name is generated from given targets."""
assert MulledImageNameGenerator.generate_image_name(specs) == expected
| [
"nf_core.modules.MulledImageNameGenerator.generate_image_name",
"pytest.mark.parametrize",
"pytest.raises",
"nf_core.modules.MulledImageNameGenerator.parse_targets"
] | [((131, 314), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""specs, expected"""', "[(['foo==0.1.2', 'bar==1.1'], [('foo', '0.1.2'), ('bar', '1.1')]), ([\n 'foo=0.1.2', 'bar=1.1'], [('foo', '0.1.2'), ('bar', '1.1')])]"], {}), "('specs, expected', [(['foo==0.1.2', 'bar==1.1'], [(\n 'foo', '0.1.2'), ('bar', '1.1')]), (['foo=0.1.2', 'bar=1.1'], [('foo',\n '0.1.2'), ('bar', '1.1')])])\n", (154, 314), False, 'import pytest\n'), ((542, 633), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""specs"""', "[['foo<0.1.2', 'bar==1.1'], ['foo=0.1.2', 'bar>1.1']]"], {}), "('specs', [['foo<0.1.2', 'bar==1.1'], ['foo=0.1.2',\n 'bar>1.1']])\n", (565, 633), False, 'import pytest\n'), ((876, 974), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""specs"""', "[['foo==0a.1.2', 'bar==1.1'], ['foo==0.1.2', 'bar==1.b1b']]"], {}), "('specs', [['foo==0a.1.2', 'bar==1.1'], [\n 'foo==0.1.2', 'bar==1.b1b']])\n", (899, 974), False, 'import pytest\n'), ((1223, 1736), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""specs, expected"""', "[([('chromap', '0.2.1'), ('samtools', '1.15')],\n 'mulled-v2-1f09f39f20b1c4ee36581dc81cc323c70e661633:bd74d08a359024829a7aec1638a28607bbcd8a58-0'\n ), ([('pysam', '0.16.0.1'), ('biopython', '1.78')],\n 'mulled-v2-3a59640f3fe1ed11819984087d31d68600200c3f:185a25ca79923df85b58f42deb48f5ac4481e91f-0'\n ), ([('samclip', '0.4.0'), ('samtools', '1.15')],\n 'mulled-v2-d057255d4027721f3ab57f6a599a2ae81cb3cbe3:13051b049b6ae536d76031ba94a0b8e78e364815-0'\n )]"], {}), "('specs, expected', [([('chromap', '0.2.1'), (\n 'samtools', '1.15')],\n 'mulled-v2-1f09f39f20b1c4ee36581dc81cc323c70e661633:bd74d08a359024829a7aec1638a28607bbcd8a58-0'\n ), ([('pysam', '0.16.0.1'), ('biopython', '1.78')],\n 'mulled-v2-3a59640f3fe1ed11819984087d31d68600200c3f:185a25ca79923df85b58f42deb48f5ac4481e91f-0'\n ), ([('samclip', '0.4.0'), ('samtools', '1.15')],\n 'mulled-v2-d057255d4027721f3ab57f6a599a2ae81cb3cbe3:13051b049b6ae536d76031ba94a0b8e78e364815-0'\n )])\n", (1246, 1736), False, 'import pytest\n'), ((481, 526), 'nf_core.modules.MulledImageNameGenerator.parse_targets', 'MulledImageNameGenerator.parse_targets', (['specs'], {}), '(specs)\n', (519, 526), False, 'from nf_core.modules import MulledImageNameGenerator\n'), ((767, 817), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""expected format"""'}), "(ValueError, match='expected format')\n", (780, 817), False, 'import pytest\n'), ((827, 872), 'nf_core.modules.MulledImageNameGenerator.parse_targets', 'MulledImageNameGenerator.parse_targets', (['specs'], {}), '(specs)\n', (865, 872), False, 'from nf_core.modules import MulledImageNameGenerator\n'), ((1123, 1164), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""PEP440"""'}), "(ValueError, match='PEP440')\n", (1136, 1164), False, 'import pytest\n'), ((1174, 1219), 'nf_core.modules.MulledImageNameGenerator.parse_targets', 'MulledImageNameGenerator.parse_targets', (['specs'], {}), '(specs)\n', (1212, 1219), False, 'from nf_core.modules import MulledImageNameGenerator\n'), ((1982, 2033), 'nf_core.modules.MulledImageNameGenerator.generate_image_name', 'MulledImageNameGenerator.generate_image_name', (['specs'], {}), '(specs)\n', (2026, 2033), False, 'from nf_core.modules import MulledImageNameGenerator\n')] |
import astropy.units as u
from astropy.coordinates import Angle, SkyCoord
from astropy import wcs
from regions import CircleSkyRegion
import numpy as np
from scipy.stats import expon
def estimate_exposure_time(timestamps):
'''
Takes numpy datetime64[ns] timestamps and returns an estimates of the exposure time in seconds.
'''
delta_s = np.diff(timestamps).astype(int) * float(1e-9)
# take only events that came within 30 seconds or so
delta_s = delta_s[delta_s < 30]
scale = delta_s.mean()
exposure_time = len(delta_s) * scale
loc = min(delta_s)
# this percentile is somewhat abritrary but seems to work well.
live_time_fraction = 1 - expon.ppf(0.1, loc=loc, scale=scale)
return (exposure_time * live_time_fraction) * u.s
@u.quantity_input(ra=u.hourangle, dec=u.deg, fov=u.deg)
def build_exposure_regions(pointing_coords, fov=4.5 * u.deg):
'''
Takes a list of pointing positions and a field of view and returns
the unique pointing positions and the astropy.regions.
For an observation with N wobble positions this will return N unique
pointing positions and N circular regions.
'''
unique_pointing_positions = SkyCoord(
ra=np.unique(pointing_coords.ra),
dec=np.unique(pointing_coords.dec)
)
regions = [CircleSkyRegion(
center=pointing,
radius=Angle(fov) / 2
) for pointing in unique_pointing_positions]
return unique_pointing_positions, regions
def _build_standard_wcs(image_center, shape, naxis=2, fov=9 * u.deg):
width, height = shape
w = wcs.WCS(naxis=2)
w.wcs.crpix = [width / 2 + 0.5, height / 2 + 0.5]
w.wcs.cdelt = np.array([-fov.value / width, fov.value / height])
w.wcs.crval = [image_center.ra.deg, image_center.dec.deg]
w.wcs.ctype = ["RA---TAN", "DEC--TAN"]
w.wcs.radesys = 'FK5'
w.wcs.equinox = 2000.0
w.wcs.cunit = ['deg', 'deg']
w._naxis = [width, height]
return w
@u.quantity_input(event_ra=u.hourangle, event_dec=u.deg, fov=u.deg)
def build_exposure_map(pointing_coords, event_time, fov=4.5 * u.deg, wcs=None, shape=(1000, 1000)):
'''
Takes pointing coordinates for each event and the corresponding timestamp.
Returns a masked array containing the estimated exposure time in hours
and a WCS object so the mask can be plotted.
'''
if not wcs:
image_center = SkyCoord(ra=pointing_coords.ra.mean(), dec=pointing_coords.dec.mean())
wcs = _build_standard_wcs(image_center, shape, fov=2 * fov)
unique_pointing_positions, regions = build_exposure_regions(pointing_coords)
times = []
for p in unique_pointing_positions:
m = (pointing_coords.ra == p.ra) & (pointing_coords.dec == p.dec)
exposure_time = estimate_exposure_time(event_time[m])
times.append(exposure_time)
masks = [r.to_pixel(wcs).to_mask().to_image(shape) for r in regions]
cutout = sum(masks).astype(bool)
mask = sum([w.to('h').value * m for w, m in zip(times, masks)])
return np.ma.masked_array(mask, mask=~cutout), wcs
| [
"numpy.unique",
"astropy.coordinates.Angle",
"numpy.diff",
"numpy.array",
"numpy.ma.masked_array",
"scipy.stats.expon.ppf",
"astropy.wcs.WCS",
"astropy.units.quantity_input"
] | [((780, 834), 'astropy.units.quantity_input', 'u.quantity_input', ([], {'ra': 'u.hourangle', 'dec': 'u.deg', 'fov': 'u.deg'}), '(ra=u.hourangle, dec=u.deg, fov=u.deg)\n', (796, 834), True, 'import astropy.units as u\n'), ((1966, 2032), 'astropy.units.quantity_input', 'u.quantity_input', ([], {'event_ra': 'u.hourangle', 'event_dec': 'u.deg', 'fov': 'u.deg'}), '(event_ra=u.hourangle, event_dec=u.deg, fov=u.deg)\n', (1982, 2032), True, 'import astropy.units as u\n'), ((1588, 1604), 'astropy.wcs.WCS', 'wcs.WCS', ([], {'naxis': '(2)'}), '(naxis=2)\n', (1595, 1604), False, 'from astropy import wcs\n'), ((1677, 1727), 'numpy.array', 'np.array', (['[-fov.value / width, fov.value / height]'], {}), '([-fov.value / width, fov.value / height])\n', (1685, 1727), True, 'import numpy as np\n'), ((685, 721), 'scipy.stats.expon.ppf', 'expon.ppf', (['(0.1)'], {'loc': 'loc', 'scale': 'scale'}), '(0.1, loc=loc, scale=scale)\n', (694, 721), False, 'from scipy.stats import expon\n'), ((3032, 3070), 'numpy.ma.masked_array', 'np.ma.masked_array', (['mask'], {'mask': '(~cutout)'}), '(mask, mask=~cutout)\n', (3050, 3070), True, 'import numpy as np\n'), ((1217, 1246), 'numpy.unique', 'np.unique', (['pointing_coords.ra'], {}), '(pointing_coords.ra)\n', (1226, 1246), True, 'import numpy as np\n'), ((1260, 1290), 'numpy.unique', 'np.unique', (['pointing_coords.dec'], {}), '(pointing_coords.dec)\n', (1269, 1290), True, 'import numpy as np\n'), ((355, 374), 'numpy.diff', 'np.diff', (['timestamps'], {}), '(timestamps)\n', (362, 374), True, 'import numpy as np\n'), ((1370, 1380), 'astropy.coordinates.Angle', 'Angle', (['fov'], {}), '(fov)\n', (1375, 1380), False, 'from astropy.coordinates import Angle, SkyCoord\n')] |
import numpy as np
a = np.zeros((10,6))
a[1,4:6] = [2,3]
b = a[1,4]
print(b)
check = np.array([2,3])
for i in range(a.shape[0]):
t = int(a[i,4])
idx = int(a[i,5])
if t == 2 and idx == 4:
a = np.delete(a,i,0)
break
else:
continue
print(a.shape)
| [
"numpy.array",
"numpy.zeros",
"numpy.delete"
] | [((24, 41), 'numpy.zeros', 'np.zeros', (['(10, 6)'], {}), '((10, 6))\n', (32, 41), True, 'import numpy as np\n'), ((88, 104), 'numpy.array', 'np.array', (['[2, 3]'], {}), '([2, 3])\n', (96, 104), True, 'import numpy as np\n'), ((216, 234), 'numpy.delete', 'np.delete', (['a', 'i', '(0)'], {}), '(a, i, 0)\n', (225, 234), True, 'import numpy as np\n')] |
# coding: utf-8
import csv # ファイル出力用
import bs4, requests # スクレイピング(html取得・処理)
import re #正規表現
from pathlib import Path
# 指定エンコードのgetメソッド
def get_enc(mode):
enc_dic = dict(r='utf-8', w='sjis', p='cp932')
return enc_dic[mode]
# インラインのfor文リストで除外文字以外を繋ぐ
def remove_str(target, str_list):
return ''.join([c for c in target if c not in str_list])
# 指定エンコードでエラー文字以外を再取得する
def ignore_str(target, enc):
return target.encode(enc, 'ignore').decode(enc)
# ページをパースする
def get_soup(url):
res = requests.get(url)
soup = bs4.BeautifulSoup(res.text)
return soup
# parent,subのフォルダ作成
def get_new_dir(parent_dir, sub_dir):
# フォルダが無ければ作成(あってもエラーなし)
parent_dir.mkdir(exist_ok=True)
sub_dir_path = parent_dir / sub_dir
sub_dir_path.mkdir(exist_ok=True)
return Path(sub_dir_path)
# URLか判定する
def ask_is_url(url):
url = remove_str(url, ['\r', '\n'])
# 正規表現処理
rep = r'^https?://[\w/:%#\$&\?\(\)~\.=\+\-]+$'
return re.match(rep, url) != None
# titleとformatを
# urlからタイトルを取得し、csvファイルに出力する
def read_url(url_list, out_writer):
# urlリストを1行ごとに処理する
for url in url_list:
# urlでなければ次へ
if not ask_is_url(url):
print('{} do not matched url pattern'.format(url))
continue
# ページの取得
soup = get_soup(url)
# タイトルの取得とMarkdown用フォーマット
title = ignore_str(soup.title.string, get_enc('w'))
markup = '[{}]({})'.format(title, url)
# csvファイルへ書き出し
out_writer.writerow([url, title, markup])
# ファイルの読み込み
def read_for(files, out_writer):
# 入力ファイルでfor文を回す
for file_path in files:
with Path(file_path).open('r', encoding=get_enc('r')) as read_file_obj:
# 全行取り込む
url_list = read_file_obj.readlines()
# urlの読み込み
read_url(url_list, out_writer)
def main():
# 各ディレクトリの取得
org_dir = get_new_dir(Path(__file__).parent, 'org')
out_dir = get_new_dir(Path(__file__).parent, 'out')
# 出力ファイルの決定
out_file = out_dir / 'result.csv'
# 入力、出力ファイル・ディレクトリの取得
files = list(org_dir.glob('*.txt'))
with out_file.open('w', encoding=get_enc('w'), newline='') as out_file_obj:
# csvファイルのwriterを取得
out_writer = csv.writer(out_file_obj, dialect="excel")
# ファイルの読み込み
read_for(files, out_writer)
if __name__ == '__main__':
main()
print('finish') | [
"pathlib.Path",
"csv.writer",
"re.match",
"requests.get",
"bs4.BeautifulSoup"
] | [((513, 530), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (525, 530), False, 'import bs4, requests\n'), ((542, 569), 'bs4.BeautifulSoup', 'bs4.BeautifulSoup', (['res.text'], {}), '(res.text)\n', (559, 569), False, 'import bs4, requests\n'), ((799, 817), 'pathlib.Path', 'Path', (['sub_dir_path'], {}), '(sub_dir_path)\n', (803, 817), False, 'from pathlib import Path\n'), ((967, 985), 're.match', 're.match', (['rep', 'url'], {}), '(rep, url)\n', (975, 985), False, 'import re\n'), ((2290, 2331), 'csv.writer', 'csv.writer', (['out_file_obj'], {'dialect': '"""excel"""'}), "(out_file_obj, dialect='excel')\n", (2300, 2331), False, 'import csv\n'), ((1953, 1967), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (1957, 1967), False, 'from pathlib import Path\n'), ((2009, 2023), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (2013, 2023), False, 'from pathlib import Path\n'), ((1693, 1708), 'pathlib.Path', 'Path', (['file_path'], {}), '(file_path)\n', (1697, 1708), False, 'from pathlib import Path\n')] |
# Generated by Django 2.1.4 on 2019-05-29 11:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('daiquiri_metadata', '0024_django2'),
]
operations = [
migrations.AddField(
model_name='schema',
name='published',
field=models.DateField(blank=True, null=True, verbose_name='Published'),
),
migrations.AddField(
model_name='schema',
name='updated',
field=models.DateField(blank=True, null=True, verbose_name='Updated'),
),
migrations.AddField(
model_name='table',
name='published',
field=models.DateField(blank=True, null=True, verbose_name='Published'),
),
migrations.AddField(
model_name='table',
name='updated',
field=models.DateField(blank=True, null=True, verbose_name='Updated'),
),
]
| [
"django.db.models.DateField"
] | [((336, 401), 'django.db.models.DateField', 'models.DateField', ([], {'blank': '(True)', 'null': '(True)', 'verbose_name': '"""Published"""'}), "(blank=True, null=True, verbose_name='Published')\n", (352, 401), False, 'from django.db import migrations, models\n'), ((522, 585), 'django.db.models.DateField', 'models.DateField', ([], {'blank': '(True)', 'null': '(True)', 'verbose_name': '"""Updated"""'}), "(blank=True, null=True, verbose_name='Updated')\n", (538, 585), False, 'from django.db import migrations, models\n'), ((707, 772), 'django.db.models.DateField', 'models.DateField', ([], {'blank': '(True)', 'null': '(True)', 'verbose_name': '"""Published"""'}), "(blank=True, null=True, verbose_name='Published')\n", (723, 772), False, 'from django.db import migrations, models\n'), ((892, 955), 'django.db.models.DateField', 'models.DateField', ([], {'blank': '(True)', 'null': '(True)', 'verbose_name': '"""Updated"""'}), "(blank=True, null=True, verbose_name='Updated')\n", (908, 955), False, 'from django.db import migrations, models\n')] |
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#Created by: <NAME>
#BE department, University of Pennsylvania
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
import numpy as np
import nibabel as nib
import os
from tqdm import tqdm
from functools import partial
import matplotlib.pyplot as plt
from multiprocessing import Pool
from scipy.spatial.distance import directed_hausdorff
import data_utils.surface_distance as surface_distance
def estimate_weights_mfb(labels):
labels = labels.astype(np.float64)
class_weights = np.zeros_like(labels)
unique, counts = np.unique(labels, return_counts=True)
median_freq = np.median(counts)
weights = np.zeros(len(unique))
for i, label in enumerate(unique):
class_weights += (median_freq // counts[i]) * np.array(labels == label)
weights[int(label)] = median_freq // counts[i]
grads = np.gradient(labels)
edge_weights = (grads[0] ** 2 + grads[1] ** 2) > 0
class_weights += 2 * edge_weights
return class_weights, weights
def remaplabels(id, labelfiles, labeldir, savedir):
labelfile = labelfiles[id]
if os.path.exists(os.path.join(savedir,labelfile[:-7]+'.npy')):
return
label = nib.load(os.path.join(labeldir,labelfile))
labelnpy = label.get_fdata()
labelnpy = labelnpy.astype(np.int32)
########################this is for coarse-grained dataset##############################
# labelnpy[(labelnpy >= 100) & (labelnpy % 2 == 0)] = 210
# labelnpy[(labelnpy >= 100) & (labelnpy % 2 == 1)] = 211
# label_list = [45, 211, 44, 210, 52, 41, 39, 60, 37, 58, 56, 4, 11, 35, 48, 32, 62, 51, 40, 38, 59, 36, 57,
# 55, 47, 31, 61]
########################this is for fine-grained dataset##############################
label_list = np.array([4, 11, 23, 30, 31, 32, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 55,
56, 57, 58, 59, 60, 61, 62, 63, 64, 69, 71, 72, 73,
75, 76, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 112,
113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125,
128, 129, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142,
143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155,
156, 157, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170,
171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183,
184, 185, 186, 187, 190, 191, 192, 193, 194, 195, 196, 197, 198,
199, 200, 201, 202, 203, 204, 205, 206, 207])
new_labels = np.zeros_like(labelnpy)
for i, num in enumerate(label_list):
label_present = np.zeros_like(labelnpy)
label_present[labelnpy == num] = 1
new_labels = new_labels + (i + 1) * label_present
if (np.sum(np.unique(new_labels)>139) and np.sum(np.unique(new_labels)<0)) > 0:
print('error')
np.save(os.path.join(savedir,labelfile[:-7]), new_labels)
print('finished converting label: ' + labelfile)
def process_resampled_labels():
labeldir = None #label directory for all nifty images
savedir = None #directory to save numpy images
labelfiles = [f for f in os.listdir(labeldir) if os.path.isfile(os.path.join(labeldir, f))]
labelfiles = [f for f in labelfiles if '_lab.nii.gz' in f]
pool = Pool(processes=20)
partial_mri = partial(remaplabels, labelfiles=labelfiles, labeldir=labeldir, savedir=savedir)
pool.map(partial_mri, range(len(labelfiles)))
pool.close()
pool.join()
print('end preprocessing brain data')
def convertTonpy(datadir, savedir):
if not os.path.exists(savedir):
os.makedirs(savedir)
datafiles = [f for f in os.listdir(datadir) if os.path.isfile(os.path.join(datadir, f))]
datafiles = [f for f in datafiles if '_brainmask.nii.gz' in f]
tbar = tqdm(datafiles)
for datafile in tbar:
data = nib.load(os.path.join(datadir,datafile))
datanpy = data.get_fdata()
datanpy = datanpy.astype(np.int32)
# datanpy = datanpy.astype(np.float32)
datanpy[datanpy>0]=1
np.save(os.path.join(savedir,datafile[:-7]), datanpy)
def convertToNifty(datadir, savedir):
if not os.path.exists(savedir):
os.makedirs(savedir)
datafiles = [f for f in os.listdir(datadir) if os.path.isfile(os.path.join(datadir, f))]
for datafile in datafiles:
datanpy = np.load(os.path.join(datadir,datafile))
datanpy = np.transpose(datanpy, (1,2,0))
datanpy = datanpy.astype(np.uint8)
img = nib.Nifti1Image(datanpy, np.eye(4))
assert(img.get_data_dtype() == np.uint8)
nib.save(img, os.path.join(savedir,datafile[:-4]+'.nii.gz'))
def process_fine_labels(fine_label_dir):
dice_score = np.load(os.path.join(fine_label_dir, 'dice_score.npy'))
iou_score = np.load(os.path.join(fine_label_dir, 'iou_score.npy'))
label_list = np.array([4, 11, 23, 30, 31, 32, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 55,
56, 57, 58, 59, 60, 61, 62, 63, 64, 69, 71, 72, 73,
75, 76, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 112,
113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125,
128, 129, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142,
143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155,
156, 157, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170,
171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183,
184, 185, 186, 187, 190, 191, 192, 193, 194, 195, 196, 197, 198,
199, 200, 201, 202, 203, 204, 205, 206, 207])
total_idx = np.arange(0, len(label_list))
ignore = np.array([42, 43, 64, 69])
valid_idx = [i+1 for i in total_idx if label_list[i] not in ignore]
valid_idx = [0] + valid_idx
dice_score_vali = dice_score[:,valid_idx]
iou_score_vali = iou_score[:,valid_idx]
print(np.mean(dice_score_vali))
print(np.std(dice_score_vali))
print(np.mean(iou_score_vali))
print(np.std(iou_score_vali))
def remap_IXI_images(id, subfodlers, savedir):
subname = subfodlers[id]
orig_dir = subname+'_orig.nii.gz'
aseg_dir = subname+'_aseg.nii.gz'
brain_mask_dir = subname+'_brainmask.nii.gz'
name = subname.split('/')[-1]
orig = nib.load(orig_dir)
orig_npy = orig.get_fdata()
orig_npy = orig_npy.astype(np.int32)
np.save(os.path.join(savedir,'training_images/'+name+'.npy'), orig_npy)
aseg = nib.load(aseg_dir)
aseg_npy = aseg.get_fdata()
aseg_npy = aseg_npy.astype(np.int32)
correspond_labels = [2, 3, 41, 42, 4, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 28, 43, 46, 47,
49, 50, 51, 52, 53, 54, 60]
new_labels = np.zeros_like(aseg_npy)
for i, num in enumerate(correspond_labels):
label_present = np.zeros_like(aseg_npy)
label_present[aseg_npy == num] = 1
new_labels = new_labels + (i + 1) * label_present
np.save(os.path.join(savedir,'training_labels/'+name+'.npy'), new_labels)
brain_mask = nib.load(brain_mask_dir)
brain_mask_npy = brain_mask.get_fdata()
brain_mask_npy = brain_mask_npy.astype(np.int32)
brain_mask_npy[brain_mask_npy>0]=1
np.save(os.path.join(savedir,'training_skulls/'+name+'.npy'), brain_mask_npy)
print('finished processing image '+name)
def process_IXI_images():
datadir = '/IXI_T1_surf/'
nii_path = '/IXI_T1_surf_nii/'
savedir = '/IXI_T1_surf/'
subfodlers = [os.path.join(nii_path, name) for name in os.listdir(datadir) if os.path.isdir(os.path.join(datadir, name)) and 'IXI' in name]
pool = Pool(processes=20)
partial_mri = partial(remap_IXI_images, subfodlers=subfodlers, savedir=savedir)
pool.map(partial_mri, range(len(subfodlers)))
pool.close()
pool.join()
print('end preprocessing IXI data')
def compute_Hausdorff_distance(id, subfiles, gt_dir, pred_dir, baseline_dir):
file_name = subfiles[id]
# subfiles = [name for name in os.listdir(gt_dir)]
dist_pred_lists = []
dist_quick_lists = []
# label_list = np.array([4, 11, 23, 30, 31, 32, 35, 36, 37, 38, 39, 40,
# 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 55,
# 56, 57, 58, 59, 60, 61, 62, 63, 64, 69, 71, 72, 73,
# 75, 76, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 112,
# 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125,
# 128, 129, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142,
# 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155,
# 156, 157, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170,
# 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183,
# 184, 185, 186, 187, 190, 191, 192, 193, 194, 195, 196, 197, 198,
# 199, 200, 201, 202, 203, 204, 205, 206, 207])
# total_idx = np.arange(0, len(label_list))
#
# ignore = np.array([42,43,64, 69])
#
# non_valid_idx = [i+1 for i in total_idx if label_list[i] in ignore]
# non_valid_idx = non_valid_idx
#this is originally a for loop
file_gt = nib.load(os.path.join(gt_dir,file_name))
file_gt_npy = file_gt.get_fdata().astype(np.int32)
file_pred = nib.load(os.path.join(pred_dir,file_name))
file_pred_npy = file_pred.get_fdata().astype(np.int32)
file_quick = nib.load(os.path.join(baseline_dir,file_name))
file_quick_npy = file_quick.get_fdata().astype(np.int32)
# for idx in non_valid_idx:
# file_pred_npy[file_pred_npy==idx] = 0
# file_quick_npy[file_quick_npy==idx] = 0
# file_gt_npy[file_gt_npy==idx] = 0
for idx in np.unique(file_gt_npy):
temp_gt = np.zeros_like(file_gt_npy)
temp_pred = np.zeros_like(file_gt_npy)
temp_quick = np.zeros_like(file_gt_npy)
temp_gt[file_gt_npy==idx] = 1
temp_pred[file_pred_npy==idx] = 1
temp_quick[file_quick_npy==idx] = 1
surface_distances_pred = surface_distance.compute_surface_distances(temp_gt, temp_pred, spacing_mm=(1, 1, 1))
dist_pred = surface_distance.compute_robust_hausdorff(surface_distances_pred, 100)
dist_pred_lists.append(dist_pred)
surface_distances_quick = surface_distance.compute_surface_distances(temp_gt, temp_quick, spacing_mm=(1, 1, 1))
dist_quick = surface_distance.compute_robust_hausdorff(surface_distances_quick, 100)
dist_quick_lists.append(dist_quick)
np.save(os.path.join(pred_dir,file_name+'_pred.npy'), dist_pred_lists)
np.save(os.path.join(pred_dir,file_name+'_quick.npy'), dist_quick_lists)
def process_Hausdorff_distance():
baseline_dir = '/MRI_model/quicknat/pred' #this is our baseline
pred_dir = '/MRI_model/coarse_dir/pred'
gt_dir = None #gt label directory, double check the rotation matches with pred
subfiles = [name for name in os.listdir(gt_dir)]
pool = Pool(processes=16)
partial_mri = partial(compute_Hausdorff_distance, subfiles=subfiles, gt_dir=gt_dir, pred_dir=pred_dir, baseline_dir=baseline_dir)
pool.map(partial_mri, range(len(subfiles)))
pool.close()
pool.join()
print('end preprocessing IXI data')
def process_Hausdorff_npy():
#this is for MALC27
gt_dir = '/label/' #gt label directory, double check the rotation matches with pred
pred_dir = '/MRI_model/coarse_dir/pred'
subfiles = [name for name in os.listdir(gt_dir)]
dist_pred_lists = []
dist_quick_lists = []
for file_name in subfiles:
pred_dist = np.load(os.path.join(pred_dir,file_name+'_pred.npy'))
quick_dist = np.load(os.path.join(pred_dir,file_name+'_quick.npy'))
quick_dist[quick_dist==np.inf]=150
dist_pred_lists.append(np.mean(pred_dist[1:,0].astype(np.float32)))
dist_quick_lists.append(np.mean(quick_dist[1:,0].astype(np.float32)))
dist_pred_lists = np.asarray(dist_pred_lists)
dist_quick_lists = np.asarray(dist_quick_lists)
print(np.mean(dist_pred_lists))
print(np.mean(dist_quick_lists))
if __name__ == '__main__':
process_resampled_labels()
| [
"nibabel.load",
"numpy.array",
"numpy.gradient",
"os.path.exists",
"numpy.mean",
"os.listdir",
"numpy.asarray",
"numpy.eye",
"numpy.std",
"numpy.transpose",
"numpy.median",
"data_utils.surface_distance.compute_robust_hausdorff",
"numpy.unique",
"os.makedirs",
"tqdm.tqdm",
"os.path.join... | [((588, 609), 'numpy.zeros_like', 'np.zeros_like', (['labels'], {}), '(labels)\n', (601, 609), True, 'import numpy as np\n'), ((631, 668), 'numpy.unique', 'np.unique', (['labels'], {'return_counts': '(True)'}), '(labels, return_counts=True)\n', (640, 668), True, 'import numpy as np\n'), ((687, 704), 'numpy.median', 'np.median', (['counts'], {}), '(counts)\n', (696, 704), True, 'import numpy as np\n'), ((928, 947), 'numpy.gradient', 'np.gradient', (['labels'], {}), '(labels)\n', (939, 947), True, 'import numpy as np\n'), ((1887, 2589), 'numpy.array', 'np.array', (['[4, 11, 23, 30, 31, 32, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,\n 48, 49, 50, 51, 52, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 69, 71, 72,\n 73, 75, 76, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 112, 113,\n 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 128, 129, \n 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, \n 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 160, 161, \n 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, \n 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 190, 191, \n 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, \n 206, 207]'], {}), '([4, 11, 23, 30, 31, 32, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45,\n 46, 47, 48, 49, 50, 51, 52, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 69,\n 71, 72, 73, 75, 76, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, \n 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, \n 128, 129, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, \n 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, \n 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, \n 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, \n 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, \n 204, 205, 206, 207])\n', (1895, 2589), True, 'import numpy as np\n'), ((2794, 2817), 'numpy.zeros_like', 'np.zeros_like', (['labelnpy'], {}), '(labelnpy)\n', (2807, 2817), True, 'import numpy as np\n'), ((3568, 3586), 'multiprocessing.Pool', 'Pool', ([], {'processes': '(20)'}), '(processes=20)\n', (3572, 3586), False, 'from multiprocessing import Pool\n'), ((3605, 3684), 'functools.partial', 'partial', (['remaplabels'], {'labelfiles': 'labelfiles', 'labeldir': 'labeldir', 'savedir': 'savedir'}), '(remaplabels, labelfiles=labelfiles, labeldir=labeldir, savedir=savedir)\n', (3612, 3684), False, 'from functools import partial\n'), ((4107, 4122), 'tqdm.tqdm', 'tqdm', (['datafiles'], {}), '(datafiles)\n', (4111, 4122), False, 'from tqdm import tqdm\n'), ((5195, 5897), 'numpy.array', 'np.array', (['[4, 11, 23, 30, 31, 32, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,\n 48, 49, 50, 51, 52, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 69, 71, 72,\n 73, 75, 76, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 112, 113,\n 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 128, 129, \n 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, \n 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 160, 161, \n 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, \n 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 190, 191, \n 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, \n 206, 207]'], {}), '([4, 11, 23, 30, 31, 32, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45,\n 46, 47, 48, 49, 50, 51, 52, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 69,\n 71, 72, 73, 75, 76, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, \n 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, \n 128, 129, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, \n 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, \n 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, \n 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, \n 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, \n 204, 205, 206, 207])\n', (5203, 5897), True, 'import numpy as np\n'), ((6173, 6199), 'numpy.array', 'np.array', (['[42, 43, 64, 69]'], {}), '([42, 43, 64, 69])\n', (6181, 6199), True, 'import numpy as np\n'), ((6826, 6844), 'nibabel.load', 'nib.load', (['orig_dir'], {}), '(orig_dir)\n', (6834, 6844), True, 'import nibabel as nib\n'), ((7010, 7028), 'nibabel.load', 'nib.load', (['aseg_dir'], {}), '(aseg_dir)\n', (7018, 7028), True, 'import nibabel as nib\n'), ((7278, 7301), 'numpy.zeros_like', 'np.zeros_like', (['aseg_npy'], {}), '(aseg_npy)\n', (7291, 7301), True, 'import numpy as np\n'), ((7600, 7624), 'nibabel.load', 'nib.load', (['brain_mask_dir'], {}), '(brain_mask_dir)\n', (7608, 7624), True, 'import nibabel as nib\n'), ((8188, 8206), 'multiprocessing.Pool', 'Pool', ([], {'processes': '(20)'}), '(processes=20)\n', (8192, 8206), False, 'from multiprocessing import Pool\n'), ((8225, 8290), 'functools.partial', 'partial', (['remap_IXI_images'], {'subfodlers': 'subfodlers', 'savedir': 'savedir'}), '(remap_IXI_images, subfodlers=subfodlers, savedir=savedir)\n', (8232, 8290), False, 'from functools import partial\n'), ((10407, 10429), 'numpy.unique', 'np.unique', (['file_gt_npy'], {}), '(file_gt_npy)\n', (10416, 10429), True, 'import numpy as np\n'), ((11705, 11723), 'multiprocessing.Pool', 'Pool', ([], {'processes': '(16)'}), '(processes=16)\n', (11709, 11723), False, 'from multiprocessing import Pool\n'), ((11742, 11861), 'functools.partial', 'partial', (['compute_Hausdorff_distance'], {'subfiles': 'subfiles', 'gt_dir': 'gt_dir', 'pred_dir': 'pred_dir', 'baseline_dir': 'baseline_dir'}), '(compute_Hausdorff_distance, subfiles=subfiles, gt_dir=gt_dir,\n pred_dir=pred_dir, baseline_dir=baseline_dir)\n', (11749, 11861), False, 'from functools import partial\n'), ((12689, 12716), 'numpy.asarray', 'np.asarray', (['dist_pred_lists'], {}), '(dist_pred_lists)\n', (12699, 12716), True, 'import numpy as np\n'), ((12740, 12768), 'numpy.asarray', 'np.asarray', (['dist_quick_lists'], {}), '(dist_quick_lists)\n', (12750, 12768), True, 'import numpy as np\n'), ((1191, 1237), 'os.path.join', 'os.path.join', (['savedir', "(labelfile[:-7] + '.npy')"], {}), "(savedir, labelfile[:-7] + '.npy')\n", (1203, 1237), False, 'import os\n'), ((1282, 1315), 'os.path.join', 'os.path.join', (['labeldir', 'labelfile'], {}), '(labeldir, labelfile)\n', (1294, 1315), False, 'import os\n'), ((2884, 2907), 'numpy.zeros_like', 'np.zeros_like', (['labelnpy'], {}), '(labelnpy)\n', (2897, 2907), True, 'import numpy as np\n'), ((3138, 3175), 'os.path.join', 'os.path.join', (['savedir', 'labelfile[:-7]'], {}), '(savedir, labelfile[:-7])\n', (3150, 3175), False, 'import os\n'), ((3872, 3895), 'os.path.exists', 'os.path.exists', (['savedir'], {}), '(savedir)\n', (3886, 3895), False, 'import os\n'), ((3905, 3925), 'os.makedirs', 'os.makedirs', (['savedir'], {}), '(savedir)\n', (3916, 3925), False, 'import os\n'), ((4476, 4499), 'os.path.exists', 'os.path.exists', (['savedir'], {}), '(savedir)\n', (4490, 4499), False, 'import os\n'), ((4509, 4529), 'os.makedirs', 'os.makedirs', (['savedir'], {}), '(savedir)\n', (4520, 4529), False, 'import os\n'), ((4744, 4776), 'numpy.transpose', 'np.transpose', (['datanpy', '(1, 2, 0)'], {}), '(datanpy, (1, 2, 0))\n', (4756, 4776), True, 'import numpy as np\n'), ((5054, 5100), 'os.path.join', 'os.path.join', (['fine_label_dir', '"""dice_score.npy"""'], {}), "(fine_label_dir, 'dice_score.npy')\n", (5066, 5100), False, 'import os\n'), ((5126, 5171), 'os.path.join', 'os.path.join', (['fine_label_dir', '"""iou_score.npy"""'], {}), "(fine_label_dir, 'iou_score.npy')\n", (5138, 5171), False, 'import os\n'), ((6419, 6443), 'numpy.mean', 'np.mean', (['dice_score_vali'], {}), '(dice_score_vali)\n', (6426, 6443), True, 'import numpy as np\n'), ((6455, 6478), 'numpy.std', 'np.std', (['dice_score_vali'], {}), '(dice_score_vali)\n', (6461, 6478), True, 'import numpy as np\n'), ((6495, 6518), 'numpy.mean', 'np.mean', (['iou_score_vali'], {}), '(iou_score_vali)\n', (6502, 6518), True, 'import numpy as np\n'), ((6530, 6552), 'numpy.std', 'np.std', (['iou_score_vali'], {}), '(iou_score_vali)\n', (6536, 6552), True, 'import numpy as np\n'), ((6930, 6987), 'os.path.join', 'os.path.join', (['savedir', "('training_images/' + name + '.npy')"], {}), "(savedir, 'training_images/' + name + '.npy')\n", (6942, 6987), False, 'import os\n'), ((7375, 7398), 'numpy.zeros_like', 'np.zeros_like', (['aseg_npy'], {}), '(aseg_npy)\n', (7388, 7398), True, 'import numpy as np\n'), ((7512, 7569), 'os.path.join', 'os.path.join', (['savedir', "('training_labels/' + name + '.npy')"], {}), "(savedir, 'training_labels/' + name + '.npy')\n", (7524, 7569), False, 'import os\n'), ((7773, 7830), 'os.path.join', 'os.path.join', (['savedir', "('training_skulls/' + name + '.npy')"], {}), "(savedir, 'training_skulls/' + name + '.npy')\n", (7785, 7830), False, 'import os\n'), ((8050, 8078), 'os.path.join', 'os.path.join', (['nii_path', 'name'], {}), '(nii_path, name)\n', (8062, 8078), False, 'import os\n'), ((9872, 9903), 'os.path.join', 'os.path.join', (['gt_dir', 'file_name'], {}), '(gt_dir, file_name)\n', (9884, 9903), False, 'import os\n'), ((9989, 10022), 'os.path.join', 'os.path.join', (['pred_dir', 'file_name'], {}), '(pred_dir, file_name)\n', (10001, 10022), False, 'import os\n'), ((10113, 10150), 'os.path.join', 'os.path.join', (['baseline_dir', 'file_name'], {}), '(baseline_dir, file_name)\n', (10125, 10150), False, 'import os\n'), ((10449, 10475), 'numpy.zeros_like', 'np.zeros_like', (['file_gt_npy'], {}), '(file_gt_npy)\n', (10462, 10475), True, 'import numpy as np\n'), ((10496, 10522), 'numpy.zeros_like', 'np.zeros_like', (['file_gt_npy'], {}), '(file_gt_npy)\n', (10509, 10522), True, 'import numpy as np\n'), ((10544, 10570), 'numpy.zeros_like', 'np.zeros_like', (['file_gt_npy'], {}), '(file_gt_npy)\n', (10557, 10570), True, 'import numpy as np\n'), ((10746, 10835), 'data_utils.surface_distance.compute_surface_distances', 'surface_distance.compute_surface_distances', (['temp_gt', 'temp_pred'], {'spacing_mm': '(1, 1, 1)'}), '(temp_gt, temp_pred, spacing_mm=(\n 1, 1, 1))\n', (10788, 10835), True, 'import data_utils.surface_distance as surface_distance\n'), ((10851, 10921), 'data_utils.surface_distance.compute_robust_hausdorff', 'surface_distance.compute_robust_hausdorff', (['surface_distances_pred', '(100)'], {}), '(surface_distances_pred, 100)\n', (10892, 10921), True, 'import data_utils.surface_distance as surface_distance\n'), ((11007, 11097), 'data_utils.surface_distance.compute_surface_distances', 'surface_distance.compute_surface_distances', (['temp_gt', 'temp_quick'], {'spacing_mm': '(1, 1, 1)'}), '(temp_gt, temp_quick, spacing_mm=\n (1, 1, 1))\n', (11049, 11097), True, 'import data_utils.surface_distance as surface_distance\n'), ((11114, 11185), 'data_utils.surface_distance.compute_robust_hausdorff', 'surface_distance.compute_robust_hausdorff', (['surface_distances_quick', '(100)'], {}), '(surface_distances_quick, 100)\n', (11155, 11185), True, 'import data_utils.surface_distance as surface_distance\n'), ((11251, 11298), 'os.path.join', 'os.path.join', (['pred_dir', "(file_name + '_pred.npy')"], {}), "(pred_dir, file_name + '_pred.npy')\n", (11263, 11298), False, 'import os\n'), ((11326, 11374), 'os.path.join', 'os.path.join', (['pred_dir', "(file_name + '_quick.npy')"], {}), "(pred_dir, file_name + '_quick.npy')\n", (11338, 11374), False, 'import os\n'), ((12779, 12803), 'numpy.mean', 'np.mean', (['dist_pred_lists'], {}), '(dist_pred_lists)\n', (12786, 12803), True, 'import numpy as np\n'), ((12815, 12840), 'numpy.mean', 'np.mean', (['dist_quick_lists'], {}), '(dist_quick_lists)\n', (12822, 12840), True, 'import numpy as np\n'), ((834, 859), 'numpy.array', 'np.array', (['(labels == label)'], {}), '(labels == label)\n', (842, 859), True, 'import numpy as np\n'), ((3426, 3446), 'os.listdir', 'os.listdir', (['labeldir'], {}), '(labeldir)\n', (3436, 3446), False, 'import os\n'), ((3959, 3978), 'os.listdir', 'os.listdir', (['datadir'], {}), '(datadir)\n', (3969, 3978), False, 'import os\n'), ((4178, 4209), 'os.path.join', 'os.path.join', (['datadir', 'datafile'], {}), '(datadir, datafile)\n', (4190, 4209), False, 'import os\n'), ((4379, 4415), 'os.path.join', 'os.path.join', (['savedir', 'datafile[:-7]'], {}), '(savedir, datafile[:-7])\n', (4391, 4415), False, 'import os\n'), ((4567, 4586), 'os.listdir', 'os.listdir', (['datadir'], {}), '(datadir)\n', (4577, 4586), False, 'import os\n'), ((4694, 4725), 'os.path.join', 'os.path.join', (['datadir', 'datafile'], {}), '(datadir, datafile)\n', (4706, 4725), False, 'import os\n'), ((4857, 4866), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (4863, 4866), True, 'import numpy as np\n'), ((4939, 4987), 'os.path.join', 'os.path.join', (['savedir', "(datafile[:-4] + '.nii.gz')"], {}), "(savedir, datafile[:-4] + '.nii.gz')\n", (4951, 4987), False, 'import os\n'), ((8091, 8110), 'os.listdir', 'os.listdir', (['datadir'], {}), '(datadir)\n', (8101, 8110), False, 'import os\n'), ((11673, 11691), 'os.listdir', 'os.listdir', (['gt_dir'], {}), '(gt_dir)\n', (11683, 11691), False, 'import os\n'), ((12213, 12231), 'os.listdir', 'os.listdir', (['gt_dir'], {}), '(gt_dir)\n', (12223, 12231), False, 'import os\n'), ((12348, 12395), 'os.path.join', 'os.path.join', (['pred_dir', "(file_name + '_pred.npy')"], {}), "(pred_dir, file_name + '_pred.npy')\n", (12360, 12395), False, 'import os\n'), ((12423, 12471), 'os.path.join', 'os.path.join', (['pred_dir', "(file_name + '_quick.npy')"], {}), "(pred_dir, file_name + '_quick.npy')\n", (12435, 12471), False, 'import os\n'), ((3465, 3490), 'os.path.join', 'os.path.join', (['labeldir', 'f'], {}), '(labeldir, f)\n', (3477, 3490), False, 'import os\n'), ((3997, 4021), 'os.path.join', 'os.path.join', (['datadir', 'f'], {}), '(datadir, f)\n', (4009, 4021), False, 'import os\n'), ((4605, 4629), 'os.path.join', 'os.path.join', (['datadir', 'f'], {}), '(datadir, f)\n', (4617, 4629), False, 'import os\n'), ((3029, 3050), 'numpy.unique', 'np.unique', (['new_labels'], {}), '(new_labels)\n', (3038, 3050), True, 'import numpy as np\n'), ((3067, 3088), 'numpy.unique', 'np.unique', (['new_labels'], {}), '(new_labels)\n', (3076, 3088), True, 'import numpy as np\n'), ((8128, 8155), 'os.path.join', 'os.path.join', (['datadir', 'name'], {}), '(datadir, name)\n', (8140, 8155), False, 'import os\n')] |
from django.contrib.auth import get_user_model
from django.test import TestCase
from posts.models import Group, Post
User = get_user_model()
class PostModelTest(TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.user = User.objects.create_user(username='auth')
cls.post = Post.objects.create(
author=cls.user,
text='Тестовый текст больше',
)
def test_models_have_correct_object_names_post(self):
"""Проверяем, что у моделей корректно работает __str__."""
post = PostModelTest.post
text = post.text[:15]
self.assertEqual(text, str(self.post))
class GroupModelTest(TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.group = Group.objects.create(
title='Тестовая группа',
slug='Тестовый слаг',
description='Тестовое описание',
)
def test_models_have_correct_object_names_group(self):
"""Проверяем, что у моделей корректно работает __str__."""
group = GroupModelTest.group
title = group.title
self.assertEqual(title, str(self.group.title))
| [
"django.contrib.auth.get_user_model",
"posts.models.Group.objects.create",
"posts.models.Post.objects.create"
] | [((126, 142), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (140, 142), False, 'from django.contrib.auth import get_user_model\n'), ((327, 393), 'posts.models.Post.objects.create', 'Post.objects.create', ([], {'author': 'cls.user', 'text': '"""Тестовый текст больше"""'}), "(author=cls.user, text='Тестовый текст больше')\n", (346, 393), False, 'from posts.models import Group, Post\n'), ((791, 895), 'posts.models.Group.objects.create', 'Group.objects.create', ([], {'title': '"""Тестовая группа"""', 'slug': '"""Тестовый слаг"""', 'description': '"""Тестовое описание"""'}), "(title='Тестовая группа', slug='Тестовый слаг',\n description='Тестовое описание')\n", (811, 895), False, 'from posts.models import Group, Post\n')] |
import logging
import uuid
from assistant.orders.models import LineItem
from .models import Stock
from .exceptions import InsufficientStock
logger = logging.getLogger(__name__)
def process_simple_stock_allocation(**data):
stocks = Stock.objects.filter(product_variant=data.get("variant"))
line_items = data.get("orders", None)
assigned_to = []
for line_item in line_items:
quantity_required = line_item.quantity_unfulfilled
for stock in stocks:
try:
done = stock.allocate_to_order_line_item(
line_item=line_item, quantity=quantity_required
)
if done:
assigned_to.append(line_item)
except InsufficientStock as ins:
logger.info(
"Allocating to order %s but ran out of stock %s continue the loop. %s",
line_item,
stock,
ins
)
continue
return assigned_to
def allocate_stock(guid: uuid.UUID) -> Stock:
stocks = Stock.objects.filter(product_variant__guid=guid)
lines_items = LineItem.objects.filter(variant__guid=guid)
for item in lines_items:
for stock in stocks:
try:
stock.allocate_to_order_line_item(
line_item=item,
)
except InsufficientStock as ins:
logger.info(
"Allocating to order %s but ran out of stock %s continue the loop. %s",
item,
stock,
ins
)
return stocks
| [
"logging.getLogger",
"assistant.orders.models.LineItem.objects.filter"
] | [((152, 179), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (169, 179), False, 'import logging\n'), ((1160, 1203), 'assistant.orders.models.LineItem.objects.filter', 'LineItem.objects.filter', ([], {'variant__guid': 'guid'}), '(variant__guid=guid)\n', (1183, 1203), False, 'from assistant.orders.models import LineItem\n')] |
import tempfile
import unittest
from pathlib import Path
from typing import Iterable
import numpy as np
from tests.fixtures.algorithms import SupervisedDeviatingFromMean
from timeeval import (
TimeEval,
Algorithm,
Datasets,
TrainingType,
InputDimensionality,
Status,
Metric,
ResourceConstraints,
DatasetManager
)
from timeeval.datasets import Dataset, DatasetRecord
from timeeval.experiments import Experiment, Experiments
from timeeval.utils.hash_dict import hash_dict
class TestDatasetAndAlgorithmMatch(unittest.TestCase):
def setUp(self) -> None:
self.dmgr = DatasetManager("./tests/example_data")
self.algorithms = [
Algorithm(
name="supervised_deviating_from_mean",
main=SupervisedDeviatingFromMean(),
training_type=TrainingType.SUPERVISED,
input_dimensionality=InputDimensionality.UNIVARIATE,
data_as_file=False
)
]
def _prepare_dmgr(self, path: Path,
training_type: Iterable[str] = ("unsupervised",),
dimensionality: Iterable[str] = ("univariate",)) -> Datasets:
dmgr = DatasetManager(path / "data")
for t, d in zip(training_type, dimensionality):
dmgr.add_dataset(DatasetRecord(
collection_name="test",
dataset_name=f"dataset-{t}-{d}",
train_path="train.csv",
test_path="test.csv",
dataset_type="synthetic",
datetime_index=False,
split_at=-1,
train_type=t,
train_is_normal=True if t == "semi-supervised" else False,
input_type=d,
length=10000,
dimensions=5 if d == "multivariate" else 1,
contamination=0.1,
num_anomalies=1,
min_anomaly_length=100,
median_anomaly_length=100,
max_anomaly_length=100,
mean=0.0,
stddev=1.0,
trend="no-trend",
stationarity="stationary",
period_size=50
))
return dmgr
def test_supervised_algorithm(self):
with tempfile.TemporaryDirectory() as tmp_path:
timeeval = TimeEval(self.dmgr, [("test", "dataset-datetime")], self.algorithms,
repetitions=1,
results_path=Path(tmp_path))
timeeval.run()
results = timeeval.get_results(aggregated=False)
np.testing.assert_array_almost_equal(results["ROC_AUC"].values, [0.810225])
def test_mismatched_training_type(self):
algo = Algorithm(
name="supervised_deviating_from_mean",
main=SupervisedDeviatingFromMean(),
training_type=TrainingType.SEMI_SUPERVISED,
data_as_file=False
)
with tempfile.TemporaryDirectory() as tmp_path:
timeeval = TimeEval(self.dmgr, [("test", "dataset-datetime")], [algo],
repetitions=1,
results_path=Path(tmp_path),
skip_invalid_combinations=False)
timeeval.run()
results = timeeval.get_results(aggregated=False)
self.assertEqual(results.loc[0, "status"], Status.ERROR)
self.assertIn("training type", results.loc[0, "error_message"])
self.assertIn("incompatible", results.loc[0, "error_message"])
def test_mismatched_input_dimensionality(self):
algo = Algorithm(
name="supervised_deviating_from_mean",
main=SupervisedDeviatingFromMean(),
input_dimensionality=InputDimensionality.UNIVARIATE,
data_as_file=False
)
with tempfile.TemporaryDirectory() as tmp_path:
tmp_path = Path(tmp_path)
dmgr = self._prepare_dmgr(tmp_path, training_type=["supervised"], dimensionality=["multivariate"])
timeeval = TimeEval(dmgr, [("test", "dataset-supervised-multivariate")], [algo],
repetitions=1,
results_path=tmp_path,
skip_invalid_combinations=False)
timeeval.run()
results = timeeval.get_results(aggregated=False)
self.assertEqual(results.loc[0, "status"], Status.ERROR)
self.assertIn("input dimensionality", results.loc[0, "error_message"])
self.assertIn("incompatible", results.loc[0, "error_message"])
def test_missing_training_dataset_timeeval(self):
with tempfile.TemporaryDirectory() as tmp_path:
timeeval = TimeEval(self.dmgr, [("test", "dataset-int")], self.algorithms,
repetitions=1,
results_path=Path(tmp_path),
skip_invalid_combinations=False)
timeeval.run()
results = timeeval.get_results(aggregated=False)
self.assertEqual(results.loc[0, "status"], Status.ERROR)
self.assertIn("training dataset", results.loc[0, "error_message"])
self.assertIn("not found", results.loc[0, "error_message"])
def test_missing_training_dataset_experiment(self):
exp = Experiment(
dataset=Dataset(
datasetId=("test", "dataset-datetime"),
dataset_type="synthetic",
training_type=TrainingType.SUPERVISED,
num_anomalies=1,
dimensions=1,
length=3000,
contamination=0.0002777777777777778,
min_anomaly_length=1,
median_anomaly_length=1,
max_anomaly_length=1,
period_size=None
),
algorithm=self.algorithms[0],
params={},
params_id=hash_dict({}),
repetition=0,
base_results_dir=Path("tmp_path"),
resource_constraints=ResourceConstraints(),
metrics=Metric.default_list(),
resolved_test_dataset_path=self.dmgr.get_dataset_path(("test", "dataset-datetime")),
resolved_train_dataset_path=None
)
with self.assertRaises(ValueError) as e:
exp._perform_training()
self.assertIn("No training dataset", str(e.exception))
def test_dont_skip_invalid_combinations(self):
datasets = [self.dmgr.get(d) for d in self.dmgr.select()]
exps = Experiments(
dmgr=self.dmgr,
datasets=datasets,
algorithms=self.algorithms,
metrics=Metric.default_list(),
base_result_path=Path("tmp_path"),
skip_invalid_combinations=False
)
self.assertEqual(len(exps), len(datasets) * len(self.algorithms))
def test_skip_invalid_combinations(self):
datasets = [self.dmgr.get(d) for d in self.dmgr.select()]
exps = Experiments(
dmgr=self.dmgr,
datasets=datasets,
algorithms=self.algorithms,
metrics=Metric.default_list(),
base_result_path=Path("tmp_path"),
skip_invalid_combinations=True
)
self.assertEqual(len(exps), 1)
exp = list(exps)[0]
self.assertEqual(exp.dataset.training_type, exp.algorithm.training_type)
self.assertEqual(exp.dataset.input_dimensionality, exp.algorithm.input_dimensionality)
def test_force_training_type_match(self):
algo = Algorithm(
name="supervised_deviating_from_mean2",
main=SupervisedDeviatingFromMean(),
training_type=TrainingType.SUPERVISED,
input_dimensionality=InputDimensionality.MULTIVARIATE,
data_as_file=False
)
with tempfile.TemporaryDirectory() as tmp_path:
tmp_path = Path(tmp_path)
dmgr = self._prepare_dmgr(tmp_path,
training_type=["unsupervised", "semi-supervised", "supervised", "supervised"],
dimensionality=["univariate", "univariate", "univariate", "multivariate"])
datasets = [dmgr.get(d) for d in dmgr.select()]
exps = Experiments(
dmgr=dmgr,
datasets=datasets,
algorithms=self.algorithms + [algo],
metrics=Metric.default_list(),
base_result_path=tmp_path,
force_training_type_match=True
)
self.assertEqual(len(exps), 3)
exps = list(exps)
# algo1 and dataset 3
exp = exps[0]
self.assertEqual(exp.algorithm.training_type, TrainingType.SUPERVISED)
self.assertEqual(exp.dataset.training_type, TrainingType.SUPERVISED)
self.assertEqual(exp.algorithm.input_dimensionality, InputDimensionality.UNIVARIATE)
self.assertEqual(exp.dataset.input_dimensionality, InputDimensionality.UNIVARIATE)
# algo2 and dataset 4
exp = exps[1]
self.assertEqual(exp.algorithm.training_type, TrainingType.SUPERVISED)
self.assertEqual(exp.dataset.training_type, TrainingType.SUPERVISED)
self.assertEqual(exp.algorithm.input_dimensionality, InputDimensionality.MULTIVARIATE)
self.assertEqual(exp.dataset.input_dimensionality, InputDimensionality.MULTIVARIATE)
# algo1 and dataset 3
exp = exps[2]
self.assertEqual(exp.algorithm.training_type, TrainingType.SUPERVISED)
self.assertEqual(exp.dataset.training_type, TrainingType.SUPERVISED)
self.assertEqual(exp.algorithm.input_dimensionality, InputDimensionality.MULTIVARIATE)
self.assertEqual(exp.dataset.input_dimensionality, InputDimensionality.UNIVARIATE)
def test_force_dimensionality_match(self):
algo = Algorithm(
name="supervised_deviating_from_mean2",
main=SupervisedDeviatingFromMean(),
training_type=TrainingType.UNSUPERVISED,
input_dimensionality=InputDimensionality.MULTIVARIATE,
data_as_file=False
)
with tempfile.TemporaryDirectory() as tmp_path:
tmp_path = Path(tmp_path)
dmgr = self._prepare_dmgr(tmp_path,
training_type=["unsupervised", "supervised", "supervised", "unsupervised"],
dimensionality=["univariate", "multivariate", "univariate", "multivariate"])
datasets = [dmgr.get(d) for d in dmgr.select()]
exps = Experiments(
dmgr=dmgr,
datasets=datasets,
algorithms=self.algorithms + [algo],
metrics=Metric.default_list(),
base_result_path=tmp_path,
force_dimensionality_match=True
)
self.assertEqual(len(exps), 3)
exps = list(exps)
# algo1 and dataset 2
exp = exps[0]
self.assertEqual(exp.algorithm.training_type, TrainingType.SUPERVISED)
self.assertEqual(exp.dataset.training_type, TrainingType.SUPERVISED)
self.assertEqual(exp.algorithm.input_dimensionality, InputDimensionality.UNIVARIATE)
self.assertEqual(exp.dataset.input_dimensionality, InputDimensionality.UNIVARIATE)
# algo2 and dataset 2
exp = exps[1]
self.assertEqual(exp.algorithm.training_type, TrainingType.UNSUPERVISED)
self.assertEqual(exp.dataset.training_type, TrainingType.SUPERVISED)
self.assertEqual(exp.algorithm.input_dimensionality, InputDimensionality.MULTIVARIATE)
self.assertEqual(exp.dataset.input_dimensionality, InputDimensionality.MULTIVARIATE)
# algo2 and dataset 4
exp = exps[2]
self.assertEqual(exp.algorithm.training_type, TrainingType.UNSUPERVISED)
self.assertEqual(exp.dataset.training_type, TrainingType.UNSUPERVISED)
self.assertEqual(exp.algorithm.input_dimensionality, InputDimensionality.MULTIVARIATE)
self.assertEqual(exp.dataset.input_dimensionality, InputDimensionality.MULTIVARIATE)
| [
"tempfile.TemporaryDirectory",
"timeeval.utils.hash_dict.hash_dict",
"numpy.testing.assert_array_almost_equal",
"pathlib.Path",
"timeeval.TimeEval",
"timeeval.datasets.Dataset",
"tests.fixtures.algorithms.SupervisedDeviatingFromMean",
"timeeval.DatasetManager",
"timeeval.ResourceConstraints",
"tim... | [((615, 653), 'timeeval.DatasetManager', 'DatasetManager', (['"""./tests/example_data"""'], {}), "('./tests/example_data')\n", (629, 653), False, 'from timeeval import TimeEval, Algorithm, Datasets, TrainingType, InputDimensionality, Status, Metric, ResourceConstraints, DatasetManager\n'), ((1207, 1236), 'timeeval.DatasetManager', 'DatasetManager', (["(path / 'data')"], {}), "(path / 'data')\n", (1221, 1236), False, 'from timeeval import TimeEval, Algorithm, Datasets, TrainingType, InputDimensionality, Status, Metric, ResourceConstraints, DatasetManager\n'), ((2617, 2692), 'numpy.testing.assert_array_almost_equal', 'np.testing.assert_array_almost_equal', (["results['ROC_AUC'].values", '[0.810225]'], {}), "(results['ROC_AUC'].values, [0.810225])\n", (2653, 2692), True, 'import numpy as np\n'), ((2281, 2310), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (2308, 2310), False, 'import tempfile\n'), ((2974, 3003), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (3001, 3003), False, 'import tempfile\n'), ((3863, 3892), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (3890, 3892), False, 'import tempfile\n'), ((3929, 3943), 'pathlib.Path', 'Path', (['tmp_path'], {}), '(tmp_path)\n', (3933, 3943), False, 'from pathlib import Path\n'), ((4078, 4222), 'timeeval.TimeEval', 'TimeEval', (['dmgr', "[('test', 'dataset-supervised-multivariate')]", '[algo]'], {'repetitions': '(1)', 'results_path': 'tmp_path', 'skip_invalid_combinations': '(False)'}), "(dmgr, [('test', 'dataset-supervised-multivariate')], [algo],\n repetitions=1, results_path=tmp_path, skip_invalid_combinations=False)\n", (4086, 4222), False, 'from timeeval import TimeEval, Algorithm, Datasets, TrainingType, InputDimensionality, Status, Metric, ResourceConstraints, DatasetManager\n'), ((4683, 4712), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (4710, 4712), False, 'import tempfile\n'), ((7862, 7891), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (7889, 7891), False, 'import tempfile\n'), ((7928, 7942), 'pathlib.Path', 'Path', (['tmp_path'], {}), '(tmp_path)\n', (7932, 7942), False, 'from pathlib import Path\n'), ((10174, 10203), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (10201, 10203), False, 'import tempfile\n'), ((10240, 10254), 'pathlib.Path', 'Path', (['tmp_path'], {}), '(tmp_path)\n', (10244, 10254), False, 'from pathlib import Path\n'), ((1322, 1866), 'timeeval.datasets.DatasetRecord', 'DatasetRecord', ([], {'collection_name': '"""test"""', 'dataset_name': 'f"""dataset-{t}-{d}"""', 'train_path': '"""train.csv"""', 'test_path': '"""test.csv"""', 'dataset_type': '"""synthetic"""', 'datetime_index': '(False)', 'split_at': '(-1)', 'train_type': 't', 'train_is_normal': "(True if t == 'semi-supervised' else False)", 'input_type': 'd', 'length': '(10000)', 'dimensions': "(5 if d == 'multivariate' else 1)", 'contamination': '(0.1)', 'num_anomalies': '(1)', 'min_anomaly_length': '(100)', 'median_anomaly_length': '(100)', 'max_anomaly_length': '(100)', 'mean': '(0.0)', 'stddev': '(1.0)', 'trend': '"""no-trend"""', 'stationarity': '"""stationary"""', 'period_size': '(50)'}), "(collection_name='test', dataset_name=f'dataset-{t}-{d}',\n train_path='train.csv', test_path='test.csv', dataset_type='synthetic',\n datetime_index=False, split_at=-1, train_type=t, train_is_normal=True if\n t == 'semi-supervised' else False, input_type=d, length=10000,\n dimensions=5 if d == 'multivariate' else 1, contamination=0.1,\n num_anomalies=1, min_anomaly_length=100, median_anomaly_length=100,\n max_anomaly_length=100, mean=0.0, stddev=1.0, trend='no-trend',\n stationarity='stationary', period_size=50)\n", (1335, 1866), False, 'from timeeval.datasets import Dataset, DatasetRecord\n'), ((2833, 2862), 'tests.fixtures.algorithms.SupervisedDeviatingFromMean', 'SupervisedDeviatingFromMean', ([], {}), '()\n', (2860, 2862), False, 'from tests.fixtures.algorithms import SupervisedDeviatingFromMean\n'), ((3713, 3742), 'tests.fixtures.algorithms.SupervisedDeviatingFromMean', 'SupervisedDeviatingFromMean', ([], {}), '()\n', (3740, 3742), False, 'from tests.fixtures.algorithms import SupervisedDeviatingFromMean\n'), ((5382, 5674), 'timeeval.datasets.Dataset', 'Dataset', ([], {'datasetId': "('test', 'dataset-datetime')", 'dataset_type': '"""synthetic"""', 'training_type': 'TrainingType.SUPERVISED', 'num_anomalies': '(1)', 'dimensions': '(1)', 'length': '(3000)', 'contamination': '(0.0002777777777777778)', 'min_anomaly_length': '(1)', 'median_anomaly_length': '(1)', 'max_anomaly_length': '(1)', 'period_size': 'None'}), "(datasetId=('test', 'dataset-datetime'), dataset_type='synthetic',\n training_type=TrainingType.SUPERVISED, num_anomalies=1, dimensions=1,\n length=3000, contamination=0.0002777777777777778, min_anomaly_length=1,\n median_anomaly_length=1, max_anomaly_length=1, period_size=None)\n", (5389, 5674), False, 'from timeeval.datasets import Dataset, DatasetRecord\n'), ((5941, 5954), 'timeeval.utils.hash_dict.hash_dict', 'hash_dict', (['{}'], {}), '({})\n', (5950, 5954), False, 'from timeeval.utils.hash_dict import hash_dict\n'), ((6011, 6027), 'pathlib.Path', 'Path', (['"""tmp_path"""'], {}), "('tmp_path')\n", (6015, 6027), False, 'from pathlib import Path\n'), ((6062, 6083), 'timeeval.ResourceConstraints', 'ResourceConstraints', ([], {}), '()\n', (6081, 6083), False, 'from timeeval import TimeEval, Algorithm, Datasets, TrainingType, InputDimensionality, Status, Metric, ResourceConstraints, DatasetManager\n'), ((6105, 6126), 'timeeval.Metric.default_list', 'Metric.default_list', ([], {}), '()\n', (6124, 6126), False, 'from timeeval import TimeEval, Algorithm, Datasets, TrainingType, InputDimensionality, Status, Metric, ResourceConstraints, DatasetManager\n'), ((6693, 6714), 'timeeval.Metric.default_list', 'Metric.default_list', ([], {}), '()\n', (6712, 6714), False, 'from timeeval import TimeEval, Algorithm, Datasets, TrainingType, InputDimensionality, Status, Metric, ResourceConstraints, DatasetManager\n'), ((6745, 6761), 'pathlib.Path', 'Path', (['"""tmp_path"""'], {}), "('tmp_path')\n", (6749, 6761), False, 'from pathlib import Path\n'), ((7151, 7172), 'timeeval.Metric.default_list', 'Metric.default_list', ([], {}), '()\n', (7170, 7172), False, 'from timeeval import TimeEval, Algorithm, Datasets, TrainingType, InputDimensionality, Status, Metric, ResourceConstraints, DatasetManager\n'), ((7203, 7219), 'pathlib.Path', 'Path', (['"""tmp_path"""'], {}), "('tmp_path')\n", (7207, 7219), False, 'from pathlib import Path\n'), ((7659, 7688), 'tests.fixtures.algorithms.SupervisedDeviatingFromMean', 'SupervisedDeviatingFromMean', ([], {}), '()\n', (7686, 7688), False, 'from tests.fixtures.algorithms import SupervisedDeviatingFromMean\n'), ((9969, 9998), 'tests.fixtures.algorithms.SupervisedDeviatingFromMean', 'SupervisedDeviatingFromMean', ([], {}), '()\n', (9996, 9998), False, 'from tests.fixtures.algorithms import SupervisedDeviatingFromMean\n'), ((781, 810), 'tests.fixtures.algorithms.SupervisedDeviatingFromMean', 'SupervisedDeviatingFromMean', ([], {}), '()\n', (808, 810), False, 'from tests.fixtures.algorithms import SupervisedDeviatingFromMean\n'), ((2508, 2522), 'pathlib.Path', 'Path', (['tmp_path'], {}), '(tmp_path)\n', (2512, 2522), False, 'from pathlib import Path\n'), ((3192, 3206), 'pathlib.Path', 'Path', (['tmp_path'], {}), '(tmp_path)\n', (3196, 3206), False, 'from pathlib import Path\n'), ((4905, 4919), 'pathlib.Path', 'Path', (['tmp_path'], {}), '(tmp_path)\n', (4909, 4919), False, 'from pathlib import Path\n'), ((8452, 8473), 'timeeval.Metric.default_list', 'Metric.default_list', ([], {}), '()\n', (8471, 8473), False, 'from timeeval import TimeEval, Algorithm, Datasets, TrainingType, InputDimensionality, Status, Metric, ResourceConstraints, DatasetManager\n'), ((10763, 10784), 'timeeval.Metric.default_list', 'Metric.default_list', ([], {}), '()\n', (10782, 10784), False, 'from timeeval import TimeEval, Algorithm, Datasets, TrainingType, InputDimensionality, Status, Metric, ResourceConstraints, DatasetManager\n')] |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 兼容python2和python3
from __future__ import print_function
from __future__ import unicode_literals
from concurrent.futures import TimeoutError
from subprocess import Popen
from os import path, system, mknod
import json
import time
import timeout_decorator
import sys
from getopt import getopt, GetoptError
# 镜像列表
mirrors = {
"docker": "", # 使用官方默认
"docker-cn": "https://registry.docker-cn.com", # docker官方中国镜像
"azure": "https://dockerhub.azk8s.cn",
"tencentyun": "https://mirror.ccs.tencentyun.com", # 腾讯云
"daocloud": "https://f1361db2.m.daocloud.io", # 道客
"netease": "https://hub-mirror.c.163.com", # 网易
"ustc": "https://docker.mirrors.ustc.edu.cn", # 中科大
"aliyun": "https://tzqukqlm.mirror.aliyuncs.com", # 阿里云 请替换为自己的阿里云镜像加速地址
"qiniu": "https://reg-mirror.qiniu.com" # 七牛云
}
class DockerClient:
def __init__(self, image, timeout):
self.image = image # 测试用镜像
self.timeout = timeout
self.config_file = "/etc/docker/daemon.json" # docker配置文件路径
self.result_list = [] # 用于存储测试结果
# 配置docker
def set_docker_config(self, mirror_url):
config_dict = {}
if not path.exists(self.config_file):
# 如果不存在则创建配置文件
mknod(self.config_file, 0o644)
pass
else:
# 如果存在则读取参数
with open(self.config_file, "r") as file:
config_dict = json.load(file)
config_dict["registry-mirrors"] = mirror_url
with open(self.config_file, "w") as file:
json.dump(config_dict, file)
@staticmethod
def docker_reload_config():
# 热加载docker配置
# os.system默认使用sh,不支持kill -SIGHUP,使用kill -1代替,或者使用sudo切换到bash,或者使用/bin/bash -c "kill -SIGHUP"
system("sudo kill -SIGHUP $(pidof dockerd)")
# 拉取镜像,超时取消
def pull_image(self, mirror):
@timeout_decorator.timeout(self.timeout, timeout_exception=TimeoutError)
def pull_start():
pull = ""
try:
print("pulling {} from {}".format(self.image, mirror))
begin_time = time.time()
pull = Popen("docker pull {}".format(self.image), shell=True)
exit_code = pull.wait()
if exit_code == 0:
end_time = time.time()
cost_time = end_time - begin_time
print("mirror {} cost time \033[32m{}\033[0m seconds".format(mirror, cost_time))
return cost_time
else:
# 退出码为1
# net/http: TLS handshake timeout
# image not found
return 1000000000
except TimeoutError:
pull.kill()
self.clean_image()
print("\033[31mTime out {} seconds, skip!\033[0m".format(self.timeout))
return 666666666
cost_time = pull_start()
print("--------------------------------------------")
return cost_time
def speed_test(self, mirror):
self.clean_image()
return self.pull_image(mirror)
# 对测试结果排序
def mirror_sort(self):
self.result_list.sort(key=lambda cost_time: cost_time[2])
def clean_image(self):
# 强制删除镜像
system("docker rmi {} -f > /dev/null 2>&1".format(self.image))
if __name__ == '__main__':
image = "busybox:1.34.1" # 默认拉取的镜像
timeout = 60 # 默认超过60秒取消
version = "0.1.1" # 版本号
# 获取参数
try:
options_list = getopt(sys.argv[1:], "i:t:vh", ["image=", "timeout=", "version", "help"])[0]
for option, option_value in options_list:
if option in ("-i", "--image"):
image = option_value # 设置要拉取的镜像
elif option in ("-t", "--timeout"):
timeout = float(option_value) # 设置超时时间,并转换为float型数据
if timeout < 10: # 超时时间必须大于10秒
print("\033[31mError, timeout value must be greater than 10.\033[0m")
exit()
elif option in ("-v", "--version"):
print("docker-mirror version \033[32m{}\033[0m".format(version)) # 当前版本号
exit()
elif option in ("-h", "--help"):
print("Usage: docker-mirror [OPTIONS]")
print("Options:")
print(" -h, --help".ljust(25), "Print usage")
print(
" -i, --image string".ljust(25),
"Docker image for testing speed, use the default busybox:1.34.1 (e.g., busybox:1.34.1)")
print(" -t, --timeout float".ljust(25),
"Docker pull timeout threshold, must be greater than 10, use the default 60, (e.g., 88.88)")
print(" -v, --version".ljust(25), "Print version information and quit")
exit()
# 创建类
docker_client = DockerClient(image, timeout)
# 读取镜像列表,依次测试速度
for mirror, mirror_url in mirrors.items():
docker_client.set_docker_config([mirror_url]) # 设置docker仓库镜像源
docker_client.docker_reload_config() # 重载配置
cost_time = docker_client.speed_test(mirror) # 测试该镜像源拉取镜像花费时间
docker_client.result_list.append((mirror, mirror_url, cost_time)) # 保存测试结果
docker_client.mirror_sort() # 对测试结果进行排序
# 输出测试结果
for mirror in docker_client.result_list:
if mirror[2] == 666666666:
print("mirror {}: \033[31mtime out\033[0m".format(mirror[0]))
elif mirror[2] == 1000000000:
print("mirror {}: \033[31mpull error\033[0m".format(mirror[0]))
else:
print("mirror {}: \033[32m{:.3f}\033[0m seconds".format(mirror[0], mirror[2]))
if docker_client.result_list[0][2] == 666666666: # 全部超时
print("\033[31moh, your internet is terrible, all mirror time out!\033[0m")
print("Restore the default configuration.")
docker_client.set_docker_config(mirrors["docker"])
docker_client.docker_reload_config()
else:
print(
"\033[32mnow, set top three mirrors {}, {}, {} for you.\033[0m".format(docker_client.result_list[0][0],
docker_client.result_list[1][0],
docker_client.result_list[2][0]))
excellent_mirror_url = [docker_client.result_list[0][1], docker_client.result_list[1][1],
docker_client.result_list[2][1]]
docker_client.set_docker_config(excellent_mirror_url)
docker_client.docker_reload_config()
# 清理镜像
docker_client.clean_image()
# 错误的参数输入导致解析错误
except GetoptError:
print("Your command is error.")
print('You can use the "docker-mirror -h" command to get help.')
exit()
# timeout的值不为float
except ValueError:
print("\033[31mError, timeout value must a number.\033[0m")
exit()
# 用户使用ctrl+c取消
except KeyboardInterrupt:
print("\033[31m\nUser manual cancel, restore the default configuration.\033[0m")
docker_client.set_docker_config(mirrors["docker"])
docker_client.docker_reload_config()
exit()
| [
"os.path.exists",
"getopt.getopt",
"timeout_decorator.timeout",
"json.load",
"os.system",
"os.mknod",
"time.time",
"json.dump"
] | [((1791, 1835), 'os.system', 'system', (['"""sudo kill -SIGHUP $(pidof dockerd)"""'], {}), "('sudo kill -SIGHUP $(pidof dockerd)')\n", (1797, 1835), False, 'from os import path, system, mknod\n'), ((1896, 1967), 'timeout_decorator.timeout', 'timeout_decorator.timeout', (['self.timeout'], {'timeout_exception': 'TimeoutError'}), '(self.timeout, timeout_exception=TimeoutError)\n', (1921, 1967), False, 'import timeout_decorator\n'), ((1206, 1235), 'os.path.exists', 'path.exists', (['self.config_file'], {}), '(self.config_file)\n', (1217, 1235), False, 'from os import path, system, mknod\n'), ((1276, 1304), 'os.mknod', 'mknod', (['self.config_file', '(420)'], {}), '(self.config_file, 420)\n', (1281, 1304), False, 'from os import path, system, mknod\n'), ((1579, 1607), 'json.dump', 'json.dump', (['config_dict', 'file'], {}), '(config_dict, file)\n', (1588, 1607), False, 'import json\n'), ((3549, 3622), 'getopt.getopt', 'getopt', (['sys.argv[1:]', '"""i:t:vh"""', "['image=', 'timeout=', 'version', 'help']"], {}), "(sys.argv[1:], 'i:t:vh', ['image=', 'timeout=', 'version', 'help'])\n", (3555, 3622), False, 'from getopt import getopt, GetoptError\n'), ((1446, 1461), 'json.load', 'json.load', (['file'], {}), '(file)\n', (1455, 1461), False, 'import json\n'), ((2133, 2144), 'time.time', 'time.time', ([], {}), '()\n', (2142, 2144), False, 'import time\n'), ((2329, 2340), 'time.time', 'time.time', ([], {}), '()\n', (2338, 2340), False, 'import time\n')] |
"""SQLAlchemy models and utility functions for Sprint."""
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Record(db.Model):
id = db.Column(db.Integer, primary_key=True)
datetime = db.Column(db.String(25))
value = db.Column(db.Float, nullable=False)
def __repr__(self):
return f'Record[id:{self.id},datetime{self.datetime},value{self.value}]'
| [
"flask_sqlalchemy.SQLAlchemy"
] | [((105, 117), 'flask_sqlalchemy.SQLAlchemy', 'SQLAlchemy', ([], {}), '()\n', (115, 117), False, 'from flask_sqlalchemy import SQLAlchemy\n')] |
#!/usr/bin/env python3
import os
import sys
import argparse
import logging
from io import IOBase
from sys import stdout
from select import select
from threading import Thread
from time import sleep
from io import StringIO
import shutil
from datetime import datetime
import numpy as np
logging.basicConfig(filename=datetime.now().strftime('run_%Y%m%d_%H_%M.log'), level=logging.DEBUG)
# handler = logging.root.handlers.pop()
# assert logging.root.handlers == [], "root logging handlers aren't empty"
# handler.stream.close()
# handler.stream = stdout
# logging.root.addHandler(handler)
mpl_logger = logging.getLogger('matplotlib')
mpl_logger.setLevel(logging.WARNING)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# Log to screen
console_logger = logging.StreamHandler(sys.stdout)
logger.addHandler(console_logger)
# -------------------------------
class StreamLogger(IOBase, logging.Handler):
_run = None
def __init__(self, logger_obj, level):
super(StreamLogger, self).__init__()
self.logger_obj = logger_obj
self.level = level
self.pipe = os.pipe()
self.thread = Thread(target=self._flusher)
self.thread.start()
def __call__(self):
return self
def _flusher(self):
self._run = True
buf = b''
while self._run:
for fh in select([self.pipe[0]], [], [], 1)[0]:
buf += os.read(fh, 1024)
while b'\n' in buf:
data, buf = buf.split(b'\n', 1)
self.write(data.decode())
self._run = None
def write(self, data):
return self.logger_obj.log(self.level, data)
emit = write
def fileno(self):
return self.pipe[1]
def close(self):
if self._run:
self._run = False
while self._run is not None:
sleep(1)
for pipe in self.pipe:
os.close(pipe)
self.thread.join(1)
class LevelRangeFilter(logging.Filter):
def __init__(self, min_level, max_level, name=''):
super(LevelRangeFilter, self).__init__(name)
self._min_level = min_level
self._max_level = max_level
def filter(self, record):
return super(LevelRangeFilter, self).filter(record) and (
self._min_level is None or self._min_level <= record.levelno) and (
self._max_level is None or record.levelno < self._max_level)
class Runner(object):
def __init__(self, config):
self._config = config
@property
def Cfg(self):
return self._config
@staticmethod
def add_line(fname, mname, nline=2, pattern=None, is_demo=False):
"""
Add a control line to the file named fname.
:param is_demo:
:param fname: file with type *.1
:param mname: model name
:param nline: position new line. Default: 2
:param pattern: string to set the place to rename, as "111001", if it's None [default] rename all substrings.
:return:
"""
if nline < 1:
raise ValueError('nline should be more 0: {}'.format(nline))
nline -= 1 # shift to zero as array indexes
# read the file
with open(fname, "r") as f:
lines = f.readlines()
# take pattern as nline
subs = lines[nline].split()
if pattern is None:
pattern = np.ones(len(subs))
else:
pattern = pattern.replace(' ', '')
pattern = [int(p) for p in pattern]
for i, p in enumerate(pattern):
if bool(p):
filename = subs[i]
if '.' in filename:
(prefix, sep1, suffix) = filename.rpartition('.')
else:
(prefix, sep1, suffix) = filename, '', ''
(predir, sep2, nm) = prefix.rpartition('/')
subs[i] = '{}{}{}{}{}'.format(predir, sep2, mname, sep1, suffix)
newline = ' '.join(subs)
# add new line at nline position
lines.insert(nline, newline + "\n")
# write to the file
if not is_demo:
with open(fname, "w") as fout:
for l in lines:
fout.write(l)
else:
logger.info('Demo: to {} add line \n {} '.format(fname, newline))
@staticmethod
def cp_sample(fin, fout, mode=1, is_demo=False):
if os.path.exists(fout):
if mode == 2:
raise ValueError('The target file: {} is exist.'.format(fout))
if mode == 1:
logger.warning('The target file: {} was exist and left unchanged.'.format(fout))
return
logger.warning('The target file: {} was rewritten.'.format(fout))
logger.info(' Copy {} to {}'.format(fin, fout))
try:
if not is_demo:
shutil.copy2(fin, fout)
else:
logger.info('Demo: copy {} to {}'.format(fin, fout))
except shutil.SameFileError:
logger.info(' {} and {} are the same file'.format(fin, fout))
pass
@staticmethod
def eval_cmd_log2(cmd, path, is_demo=False, **kwargs):
import subprocess
# # subprocess.check_output(['ls','-l']) #all that is technically needed...
# print subprocess.check_output(['ls', '-l'])
logger.info(' Run cmd: {} in {}'.format(cmd, path))
stdin = kwargs.get('stdin', None)
stdin_flag = None
if not is_demo:
if not stdin is None:
stdin_flag = subprocess.PIPE
try:
stderr_stream = logging.StreamHandler(StringIO())
stderr_stream.addFilter(LevelRangeFilter(logging.ERROR, None))
logger.addHandler(stderr_stream)
logger.setLevel(logging.ERROR)
stdout_stream = logging.StreamHandler(StringIO())
logger.addFilter(LevelRangeFilter(logging.INFO, logging.ERROR))
logger.addHandler(stdout_stream)
logger.setLevel(logging.INFO)
with StreamLogger(logger, logging.INFO) as out, StreamLogger(logger, logging.ERROR) as err:
proc = subprocess.Popen(cmd, cwd=path, shell=True, stdout=out, stderr=err)
# print
# 'stderr_tee =', stderr_tee.stream.getvalue()
# print
# 'stdout_tee =', stdout_tee.stream.getvalue()
finally:
for handler in logger.handlers:
logger.removeHandler(handler)
handler.stream.close()
handler.close()
# stderr_tee.stream.close()
# stdout_tee.stream.close()
return proc.returncode, False, False #, stdout, stderr
else:
returncode, stdout, stderr = 0, False, False
logger.info('Demo: system cmd: {} : '.format(cmd))
return returncode, stdout, stderr
@staticmethod
def eval_cmd_log(cmd, path, is_demo=False, **kwargs):
import subprocess
# # subprocess.check_output(['ls','-l']) #all that is technically needed...
# print subprocess.check_output(['ls', '-l'])
# logger.info(' Run cmd: {} in {}'.format(cmd, path))
stdin = kwargs.get('stdin', None)
stdin_flag = None
if not is_demo:
logger.info(' Run cmd: {} in {}'.format(cmd, path))
# External script output
logger.info(
subprocess.check_output(cmd, cwd=path, shell=True)
)
return 0, False, False
else:
returncode, stdout, stderr = 0, '', ''
logger.info('Demo: system cmd: {} : '.format(cmd))
return returncode, stdout, stderr
@staticmethod
def eval_cmd(cmd, path, is_demo=False, **kwargs):
import subprocess
# # subprocess.check_output(['ls','-l']) #all that is technically needed...
# print subprocess.check_output(['ls', '-l'])
logger.info(' Run cmd: {} in {}'.format(cmd, path))
stdin = kwargs.get('stdin', None)
stdin_flag = None
if not is_demo:
if not stdin is None:
stdin_flag = subprocess.PIPE
proc = subprocess.Popen(
cmd, cwd=path, shell=True,
stdin=stdin_flag,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = proc.communicate(stdin)
return proc.returncode, stdout, stderr
else:
returncode, stdout, stderr = 0, '', ''
logger.info('Demo: system cmd: {} : '.format(cmd))
return returncode, stdout, stderr
def run(self, mname, is_sys=False, is_demo=False):
mode_sample = 1
# create first line in stella files
for sec in self.Cfg.Sections:
opts = self.Cfg.Options(sec)
pattern = None
if 'mode_sample' in opts:
mode_sample = int(self.Cfg.get(sec, 'mode_sample'))
if 'dir' in opts:
path = os.path.join(self.Cfg.Root, self.Cfg.get(sec, 'dir'))
else:
path = self.Cfg.Root
path = os.path.realpath(path)
# print("{}: mode_sample= {}".format(sec, mode_sample));
if 'pattern' in opts:
pattern = self.Cfg.get(sec, 'pattern')
if 'file_add_line' in opts:
fname = os.path.join(self.Cfg.Root, self.Cfg.get(sec, 'file_add_line'))
self.add_line(fname, mname, pattern=pattern, is_demo=is_demo)
logger.info(' {}: Added new line to {} with pattern= {}'.format(sec, fname, pattern))
if 'sample' in opts:
fname = os.path.join(self.Cfg.Root, self.Cfg.get(sec, 'sample'))
extension = os.path.splitext(fname)[1]
fout = os.path.join(os.path.dirname(fname), '{}{}'.format(mname, extension))
self.cp_sample(fname, fout, mode=mode_sample, is_demo=is_demo)
if mode_sample == -1:
cmd = './delstel.pl {};'.format(mname)
return_code, stdout, stderr = self.eval_cmd(cmd, path, is_demo=is_demo)
if is_sys and 'cmd' in opts:
cmd = self.Cfg.get(sec, 'cmd')
return_code, stdout, stderr = self.eval_cmd(cmd, path, is_demo=is_demo)
# return_code, stdout, stderr = self.eval_cmd_log(cmd, path, is_demo=is_demo)
if stdout:
for line in stdout.decode('utf8').strip().split("\n"):
logger.info('stdout: {}'.format(line))
if stderr:
for line in stderr.decode('utf8').strip().split("\n"):
logger.error('stderr: {}'.format(line))
# logger.error(line)
class Config(object):
def __init__(self, fname, isload=True):
self._fconfig = fname
self._parser = None
if isload:
self.load()
def load(self):
from configparser import ConfigParser
# parser = ConfigParser()
# parser.optionxform = str
# parser.read(self.ConfigFile)
# with open(self.ConfigFile) as f:
# sample_config = f.read()
# self._config = ConfigParser(allow_no_value=True)
# print('Load {}'.format(self.ConfigFile))
# self._config.read_file(self.ConfigFile)
parser = ConfigParser()
parser.optionxform = str
l = parser.read(self.ConfigFile)
if len(l) > 0:
self._parser = parser
return True
else:
raise ValueError('Problem with reading the config file {}'.format(self.ConfigFile))
@property
def ConfigFile(self):
return self._fconfig
@property
def Parser(self):
return self._parser
@property
def Sections(self):
return self._parser.sections()
def Options(self, sec):
# a = self.Config.items(sec)
# if len(a)
return self.Parser.options(sec)
def get(self, sec, name):
return self.Parser.get(sec, name)
@property
def Root(self):
d = os.path.dirname(self._fconfig)
if len(d) == 0:
d = './'
return d
# return self.Config.get('DEFAULT', 'root')
# return self.Config.get('DEFAULT', 'root')
# @property
# def Model(self):
# return self.Parser.get('DEFAULT', 'mname')
@property
def Eve(self):
return os.path.join(self.Root, 'eve')
@property
def Eve1(self):
fname = self.Parser.get('EVE', 'file')
return os.path.join(self.Eve, fname)
@property
def EvePattern(self):
return self.Parser.get('EVE', 'pattern')
@property
def Strad(self):
return os.path.join(self.Root, 'strad')
@property
def Strad1(self):
fname = self.Parser.get('STRAD', 'file')
return os.path.join(self.Strad, fname)
@property
def StradPattern(self):
return self.Parser.get('STRAD', 'pattern')
@property
def Vladsf(self):
return os.path.join(self.Root, 'vladsf')
@property
def Vladsf1(self):
fname = self.Parser.get('VLADSF', 'file')
return os.path.join(self.Vladsf, fname)
@property
def VladsfPattern(self):
return self.Parser.get('VLADSF', 'pattern')
@property
def as_dict(self):
return {section: dict(self._parser[section]) for section in self._parser.sections()}
def print(self):
print(self.as_dict)
def get_parser():
parser = argparse.ArgumentParser(description='Run STELLA modelling.')
# print(" Observational data could be loaded with plugin, ex: -c lcobs:filedata:tshift:mshift")
parser.add_argument('-i', '--input',
nargs='+',
required=True,
dest="input",
help="Model name, example: cat_R450_M15_Ni007 OR set of names: model1 model2")
parser.add_argument('-r', '--run_config',
required=True,
dest="run_config",
help="config file, example: run.config")
parser.add_argument('-so', '--show-only',
action='store_const',
default=False,
const=True,
dest="is_show_only",
help="Just show config, nothing will be done.")
parser.add_argument('--run',
action='store_const',
default=False,
const=True,
dest="is_sys",
help="Run with system commands.")
return parser
def main():
import sys
parser = get_parser()
args, unknownargs = parser.parse_known_args()
if args.is_show_only:
print(">>>>> JUST SHOW! <<<<<<")
if len(unknownargs) > 0:
logger.error(' Undefined strings in the command line')
parser.print_help()
sys.exit(2)
else:
if args.run_config:
fconfig = os.path.expanduser(args.run_config)
else:
logger.error(' No any config data.')
parser.print_help()
sys.exit(2)
models = args.input
logger.info(' Run {} for config: {}'.format(models, fconfig))
cfg = Config(fconfig)
# cfg.print()
runner = Runner(cfg)
for mname in models:
logger.info(' Start runner for the model: {} in {} '.format(mname, cfg.Root))
runner.run(mname, is_sys=args.is_sys, is_demo=args.is_show_only)
if __name__ == '__main__':
main()
| [
"logging.getLogger",
"logging.StreamHandler",
"configparser.ConfigParser",
"sys.stdout.decode",
"time.sleep",
"sys.exit",
"os.read",
"os.path.exists",
"argparse.ArgumentParser",
"shutil.copy2",
"subprocess.Popen",
"io.StringIO",
"os.path.expanduser",
"subprocess.check_output",
"select.se... | [((604, 635), 'logging.getLogger', 'logging.getLogger', (['"""matplotlib"""'], {}), "('matplotlib')\n", (621, 635), False, 'import logging\n'), ((683, 710), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (700, 710), False, 'import logging\n'), ((774, 807), 'logging.StreamHandler', 'logging.StreamHandler', (['sys.stdout'], {}), '(sys.stdout)\n', (795, 807), False, 'import logging\n'), ((13828, 13888), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Run STELLA modelling."""'}), "(description='Run STELLA modelling.')\n", (13851, 13888), False, 'import argparse\n'), ((1112, 1121), 'os.pipe', 'os.pipe', ([], {}), '()\n', (1119, 1121), False, 'import os\n'), ((1144, 1172), 'threading.Thread', 'Thread', ([], {'target': 'self._flusher'}), '(target=self._flusher)\n', (1150, 1172), False, 'from threading import Thread\n'), ((4446, 4466), 'os.path.exists', 'os.path.exists', (['fout'], {}), '(fout)\n', (4460, 4466), False, 'import os\n'), ((11659, 11673), 'configparser.ConfigParser', 'ConfigParser', ([], {}), '()\n', (11671, 11673), False, 'from configparser import ConfigParser\n'), ((12398, 12428), 'os.path.dirname', 'os.path.dirname', (['self._fconfig'], {}), '(self._fconfig)\n', (12413, 12428), False, 'import os\n'), ((12737, 12767), 'os.path.join', 'os.path.join', (['self.Root', '"""eve"""'], {}), "(self.Root, 'eve')\n", (12749, 12767), False, 'import os\n'), ((12865, 12894), 'os.path.join', 'os.path.join', (['self.Eve', 'fname'], {}), '(self.Eve, fname)\n', (12877, 12894), False, 'import os\n'), ((13036, 13068), 'os.path.join', 'os.path.join', (['self.Root', '"""strad"""'], {}), "(self.Root, 'strad')\n", (13048, 13068), False, 'import os\n'), ((13170, 13201), 'os.path.join', 'os.path.join', (['self.Strad', 'fname'], {}), '(self.Strad, fname)\n', (13182, 13201), False, 'import os\n'), ((13348, 13381), 'os.path.join', 'os.path.join', (['self.Root', '"""vladsf"""'], {}), "(self.Root, 'vladsf')\n", (13360, 13381), False, 'import os\n'), ((13485, 13517), 'os.path.join', 'os.path.join', (['self.Vladsf', 'fname'], {}), '(self.Vladsf, fname)\n', (13497, 13517), False, 'import os\n'), ((15302, 15313), 'sys.exit', 'sys.exit', (['(2)'], {}), '(2)\n', (15310, 15313), False, 'import sys\n'), ((8376, 8490), 'subprocess.Popen', 'subprocess.Popen', (['cmd'], {'cwd': 'path', 'shell': '(True)', 'stdin': 'stdin_flag', 'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.PIPE'}), '(cmd, cwd=path, shell=True, stdin=stdin_flag, stdout=\n subprocess.PIPE, stderr=subprocess.PIPE)\n', (8392, 8490), False, 'import subprocess\n'), ((9360, 9382), 'os.path.realpath', 'os.path.realpath', (['path'], {}), '(path)\n', (9376, 9382), False, 'import os\n'), ((15374, 15409), 'os.path.expanduser', 'os.path.expanduser', (['args.run_config'], {}), '(args.run_config)\n', (15392, 15409), False, 'import os\n'), ((15518, 15529), 'sys.exit', 'sys.exit', (['(2)'], {}), '(2)\n', (15526, 15529), False, 'import sys\n'), ((319, 333), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (331, 333), False, 'from datetime import datetime\n'), ((1361, 1394), 'select.select', 'select', (['[self.pipe[0]]', '[]', '[]', '(1)'], {}), '([self.pipe[0]], [], [], 1)\n', (1367, 1394), False, 'from select import select\n'), ((1422, 1439), 'os.read', 'os.read', (['fh', '(1024)'], {}), '(fh, 1024)\n', (1429, 1439), False, 'import os\n'), ((1880, 1888), 'time.sleep', 'sleep', (['(1)'], {}), '(1)\n', (1885, 1888), False, 'from time import sleep\n'), ((1940, 1954), 'os.close', 'os.close', (['pipe'], {}), '(pipe)\n', (1948, 1954), False, 'import os\n'), ((4915, 4938), 'shutil.copy2', 'shutil.copy2', (['fin', 'fout'], {}), '(fin, fout)\n', (4927, 4938), False, 'import shutil\n'), ((7605, 7655), 'subprocess.check_output', 'subprocess.check_output', (['cmd'], {'cwd': 'path', 'shell': '(True)'}), '(cmd, cwd=path, shell=True)\n', (7628, 7655), False, 'import subprocess\n'), ((5713, 5723), 'io.StringIO', 'StringIO', ([], {}), '()\n', (5721, 5723), False, 'from io import StringIO\n'), ((5955, 5965), 'io.StringIO', 'StringIO', ([], {}), '()\n', (5963, 5965), False, 'from io import StringIO\n'), ((6278, 6345), 'subprocess.Popen', 'subprocess.Popen', (['cmd'], {'cwd': 'path', 'shell': '(True)', 'stdout': 'out', 'stderr': 'err'}), '(cmd, cwd=path, shell=True, stdout=out, stderr=err)\n', (6294, 6345), False, 'import subprocess\n'), ((10012, 10035), 'os.path.splitext', 'os.path.splitext', (['fname'], {}), '(fname)\n', (10028, 10035), False, 'import os\n'), ((10075, 10097), 'os.path.dirname', 'os.path.dirname', (['fname'], {}), '(fname)\n', (10090, 10097), False, 'import os\n'), ((10738, 10759), 'sys.stdout.decode', 'stdout.decode', (['"""utf8"""'], {}), "('utf8')\n", (10751, 10759), False, 'from sys import stdout\n')] |
from django.contrib import admin
from .models.customer import Customer
from .models.purchase import Purchase
from .models.purchase import PurchaseItem
@admin.register(Customer)
class CustomerAdmin(admin.ModelAdmin):
pass
@admin.register(Purchase)
class PurchaseAdmin(admin.ModelAdmin):
pass
@admin.register(PurchaseItem)
class PurchaseItemAdmin(admin.ModelAdmin):
pass
| [
"django.contrib.admin.register"
] | [((155, 179), 'django.contrib.admin.register', 'admin.register', (['Customer'], {}), '(Customer)\n', (169, 179), False, 'from django.contrib import admin\n'), ((231, 255), 'django.contrib.admin.register', 'admin.register', (['Purchase'], {}), '(Purchase)\n', (245, 255), False, 'from django.contrib import admin\n'), ((307, 335), 'django.contrib.admin.register', 'admin.register', (['PurchaseItem'], {}), '(PurchaseItem)\n', (321, 335), False, 'from django.contrib import admin\n')] |
import os
import tqdm
import argparse
import subprocess
from shutil import copyfile
def dump_files(src_dir, out_dir, data):
with open(f"{out_dir}/wav.scp", "w") as file:
for key in sorted(data):
file.write(f"{key} {data[key]}\n")
copyfile(f"data/{src_dir}/utt2spk", f"{out_dir}/utt2spk")
copyfile(f"data/{src_dir}/spk2utt", f"{out_dir}/spk2utt")
copyfile(f"data/{src_dir}/segments", f"{out_dir}/segments")
def prepare_train(kind):
data_dir = f"data/train_worn_simu_u400k_cleaned_{kind}_sp_hires"
os.makedirs(f"{data_dir}/wav", exist_ok=True)
os.makedirs(f"{data_dir}/log", exist_ok=True)
clean_set = "train_worn_simu_u400k_cleaned_dae_sp_hires"
multi_set = "train_worn_simu_u400k_cleaned_sp_hires"
data = dict()
with open(f"data/{multi_set}/wav.scp") as multi_file, open(f"data/{clean_set}/wav.scp") as clean_file,\
open(f"data/train_worn_simu_u400k_cleaned_{kind}_sp_hires/log/mix_wav.log", "w") as log_file:
for multi_line, clean_line in tqdm.tqdm(zip(multi_file, clean_file)):
multi_key, multi_cmd = multi_line.strip().split(" ", 1)
clean_key, clean_cmd = clean_line.strip().split(" ", 1)
multi_cmd = multi_cmd[:-3] # [:-2]
clean_cmd = clean_cmd[:-2]
# create physical multi wav
multi_wav_path = f"{data_dir}/wav/multi/{multi_key}.wav"
if not os.path.exists(multi_wav_path):
cmd = f"{multi_cmd} {multi_wav_path}"
p = subprocess.Popen(cmd, shell=True)
p.communicate()
# compute the difference between 2 wav files and output a new wav
noise_wav_path = f"{data_dir}/wav/{multi_key}.wav"
if not os.path.exists(noise_wav_path):
cmd = f"sox -m -v 1 '{multi_wav_path}' -v -1 '|{clean_cmd}' {noise_wav_path}"
p = subprocess.Popen(cmd, shell=True)
p.communicate()
data[multi_key] = noise_wav_path
log_file.write(f"{multi_key} {noise_wav_path}\n")
# Dump wav.scp, utt2spk, spk2utt
dump_files(multi_set, data_dir, data)
def main(kind):
prepare_train(kind)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("kind", default="noise_mismatch", nargs="?",
help="'noise_mismatch' might contain channel distortion, "\
"'pure_noise' only extract added noise (TODO)")
args = parser.parse_args()
main(kind=args.kind) | [
"os.path.exists",
"argparse.ArgumentParser",
"os.makedirs",
"subprocess.Popen",
"shutil.copyfile"
] | [((260, 317), 'shutil.copyfile', 'copyfile', (['f"""data/{src_dir}/utt2spk"""', 'f"""{out_dir}/utt2spk"""'], {}), "(f'data/{src_dir}/utt2spk', f'{out_dir}/utt2spk')\n", (268, 317), False, 'from shutil import copyfile\n'), ((322, 379), 'shutil.copyfile', 'copyfile', (['f"""data/{src_dir}/spk2utt"""', 'f"""{out_dir}/spk2utt"""'], {}), "(f'data/{src_dir}/spk2utt', f'{out_dir}/spk2utt')\n", (330, 379), False, 'from shutil import copyfile\n'), ((384, 443), 'shutil.copyfile', 'copyfile', (['f"""data/{src_dir}/segments"""', 'f"""{out_dir}/segments"""'], {}), "(f'data/{src_dir}/segments', f'{out_dir}/segments')\n", (392, 443), False, 'from shutil import copyfile\n'), ((544, 589), 'os.makedirs', 'os.makedirs', (['f"""{data_dir}/wav"""'], {'exist_ok': '(True)'}), "(f'{data_dir}/wav', exist_ok=True)\n", (555, 589), False, 'import os\n'), ((594, 639), 'os.makedirs', 'os.makedirs', (['f"""{data_dir}/log"""'], {'exist_ok': '(True)'}), "(f'{data_dir}/log', exist_ok=True)\n", (605, 639), False, 'import os\n'), ((2247, 2272), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2270, 2272), False, 'import argparse\n'), ((1418, 1448), 'os.path.exists', 'os.path.exists', (['multi_wav_path'], {}), '(multi_wav_path)\n', (1432, 1448), False, 'import os\n'), ((1524, 1557), 'subprocess.Popen', 'subprocess.Popen', (['cmd'], {'shell': '(True)'}), '(cmd, shell=True)\n', (1540, 1557), False, 'import subprocess\n'), ((1763, 1793), 'os.path.exists', 'os.path.exists', (['noise_wav_path'], {}), '(noise_wav_path)\n', (1777, 1793), False, 'import os\n'), ((1909, 1942), 'subprocess.Popen', 'subprocess.Popen', (['cmd'], {'shell': '(True)'}), '(cmd, shell=True)\n', (1925, 1942), False, 'import subprocess\n')] |
from opendatatools.common import RestAgent, md5
from progressbar import ProgressBar
import json
import pandas as pd
import io
import hashlib
import time
index_map = {
'Barclay_Hedge_Fund_Index' : 'ghsndx',
'Convertible_Arbitrage_Index' : 'ghsca',
'Distressed_Securities_Index' : 'ghsds',
'Emerging_Markets_Index' : 'ghsem',
'Equity_Long_Bias_Index' : 'ghselb',
'Equity_Long_Short_Index' : 'ghsels',
'Equity_Market_Neutral_Index' : 'ghsemn',
'European_Equities_Index' : 'ghsee',
'Event_Driven_Index' : 'ghsed',
'Fixed_Income_Arbitrage_Index' : 'ghsfia',
'Fund_of_Funds_Index' : 'ghsfof',
'Global_Macro_Index' : 'ghsmc',
'Healthcare_&_Biotechnology_Index': 'ghsbio',
'Merger_Arbitrage_Index' : 'ghsma',
'Multi_Strategy_Index' : 'ghsms',
'Pacific_Rim_Equities_Index' : 'ghspre',
'Technology_Index' : 'ghstec',
}
class SimuAgent(RestAgent):
def __init__(self):
RestAgent.__init__(self)
self.user_info = None
self.df_fundlist = None
self.cookies = None
def login(self, username, password):
url = 'https://passport.simuwang.com/index.php?m=Passport&c=auth&a=login&type=login&name=%s&pass=%s&reme=1&rn=1' % (username, password)
self.add_headers({'Referer': 'https://dc.simuwang.com/'})
response = self.do_request(url)
if response is None:
return None, '登录失败'
jsonobj = json.loads(response)
suc = jsonobj['suc']
msg = jsonobj['msg']
if suc != 1:
return None, msg
self.cookies = self.get_cookies()
self.user_info = jsonobj['data']
return self.user_info, msg
def prepare_cookies(self, url):
response = self.do_request(url, None)
if response is not None:
cookies = self.get_cookies()
return cookies
else:
return None
def _get_rz_token(self, time):
mk = time * 158995555893
mtoken = md5(md5(str(mk))) + '.' + str(time)
return mtoken
def _get_fund_list_page(self, page_no):
url = 'https://dc.simuwang.com/ranking/get?page=%s&condition=fund_type:1,6,4,3,8,2;ret:9;rating_year:1;istiered:0;company_type:1;sort_name:profit_col2;sort_asc:desc;keyword:' % page_no
response = self.do_request(url)
if response is None:
return None, '获取数据失败', None
jsonobj = json.loads(response)
code = jsonobj['code']
msg = jsonobj['msg']
if code != 1000:
return None, msg, None
df = pd.DataFrame(jsonobj['data'])
pageinfo = jsonobj['pager']
return df, '', pageinfo
def load_data(self):
page_no = 1
df_list = []
df, msg, pageinfo = self._get_fund_list_page(page_no)
if df is None:
return None, msg
df_list.append(df)
page_count = pageinfo['pagecount']
process_bar = ProgressBar().start(max_value=page_count)
page_no = page_no + 1
while page_no <= page_count:
df, msg, pageinfo = self._get_fund_list_page(page_no)
if df is None:
return None, msg
df_list.append(df)
process_bar.update(page_no)
page_no = page_no + 1
self.df_fundlist = pd.concat(df_list)
return self.df_fundlist, ''
def get_fund_list(self):
if self.df_fundlist is None:
return None, '请先加载数据 load_data'
return self.df_fundlist, ''
def _get_sign(self, url, params):
str = url
for k,v in params.items():
str = str + k + params[k]
sha1 = hashlib.sha1()
sha1.update(str.encode('utf8'))
sign = sha1.hexdigest()
return sign
def _get_token(self, fund_id):
sign = self._get_sign('https://dc.simuwang.com/Api/getToken', {'id' : fund_id})
url = 'https://dc.simuwang.com/Api/getToken?id=%s&sign=%s' % (fund_id, sign)
self.add_headers({'Referer': 'https://dc.simuwang.com/'})
response = self.do_request(url)
if response is None:
return None, '获取数据失败'
jsonobj = json.loads(response)
code = jsonobj['code']
msg = jsonobj['message']
if code != 1000 :
return code, msg
self.cookies.update(self.get_cookies())
salt = jsonobj['data']
muid = self.user_info['userid']
#str = 'id%smuid%spage%s%s' % (fund_id, muid, page_no, salt)
str = '%s%s' % (fund_id, salt)
sha1 = hashlib.sha1()
sha1.update(str.encode('utf8'))
token = sha1.hexdigest()
return token, ''
def _get_fund_nav_page(self, fund_id, page_no):
muid = self.user_info['userid']
token, msg = self._get_token(fund_id)
if token is None:
return None, '获取token失败: ' + msg, ''
url = 'https://dc.simuwang.com/fund/getNavList.html'
self.add_headers({'Referer': 'https://dc.simuwang.com/product/%s.html' % fund_id})
data = {
'id' : fund_id,
'muid' : muid,
'page' : str(page_no),
'token': token,
}
response = self.do_request(url, param=data, cookies=self.cookies, encoding="utf8")
if response is None:
return None, '获取数据失败', ''
jsonobj = json.loads(response)
code = jsonobj['code']
msg = jsonobj['msg']
if code != 1000 :
return code, msg, ''
df = pd.DataFrame(jsonobj['data'])
pageinfo = jsonobj['pager']
return df, '', pageinfo
def _bit_encrypt(self, str, key):
cryText = ''
keyLen = len(key)
strLen = len(str)
for i in range(strLen):
k = i % keyLen
cryText = cryText + chr(ord(str[i]) - k)
return cryText
def _bit_encrypt2(self, str, key):
cryText = ''
keyLen = len(key)
strLen = len(str)
for i in range(strLen):
k = i % keyLen
cryText = cryText + chr(ord(str[i]) ^ ord(key[k]))
return cryText
def _decrypt_data(self, str, func, key):
# return self._bit_encrypt(str, 'cd0a8bee4c6b2f8a91ad5538dde2eb34')
# return self._bit_encrypt(str, '937ab03370497f2b4e8d0599ad25c44c')
# return self._bit_encrypt(str, '083975ce19392492bbccff21a52f1ace')
return func(str, key)
def _get_decrypt_info(self, fund_id):
url = 'https://dc.simuwang.com/product/%s.html' % fund_id
response = self.do_request(url, param=None, cookies=self.cookies, encoding="utf8")
if response is None:
return None, '获取数据失败', ''
if "String.fromCharCode(str.charCodeAt(i) - k)" in response:
decrypt_func = self._bit_encrypt
else:
decrypt_func = self._bit_encrypt2
if response.find("return xOrEncrypt(str, ")> 0:
tag = "return xOrEncrypt(str, "
else:
tag = "return bitEncrypt(str, "
pos = response.index(tag) + len(tag) + 1
key = response[pos:pos+32]
return decrypt_func, key
def get_fund_nav(self, fund_id, time_elapse = 0):
if self.user_info is None:
return None, '请先登录'
page_no = 1
df_list = []
df, msg, pageinfo = self._get_fund_nav_page(fund_id, page_no)
if df is None:
return None, msg
df_list.append(df)
page_count = pageinfo['pagecount']
page_no = page_no + 1
while page_no <= page_count:
try_times = 1
while try_times <= 3:
df, msg, pageinfo = self._get_fund_nav_page(fund_id, page_no)
if df is None:
if try_times > 3:
return None, msg
else:
try_times = try_times + 1
continue
else:
df_list.append(df)
break
page_no = page_no + 1
if time_elapse > 0:
time.sleep(time_elapse)
df_nav = pd.concat(df_list)
df_nav.drop('c', axis=1, inplace=True)
df_nav.rename(columns={'d': 'date', 'n': 'nav', 'cn' : 'accu_nav', 'cnw' : 'accu_nav_w'}, inplace=True)
# 这个网站搞了太多的小坑
func, key = self._get_decrypt_info(fund_id)
df_nav['nav'] = df_nav['nav'].apply(lambda x : self._decrypt_data(x, func, key))
df_nav['accu_nav'] = df_nav['accu_nav'].apply(lambda x : self._decrypt_data(x, func, key))
df_nav['accu_nav_w'] = df_nav['accu_nav_w'].apply(lambda x : self._decrypt_data(x, func, key))
#df_nav['nav'] = df_nav['nav'] - df_nav.index * 0.01 - 0.01
#df_nav['accu_nav'] = df_nav['accu_nav'].apply(lambda x: float(x) - 0.01)
#df_nav['accu_nav_w'] = df_nav['accu_nav_w'].apply(lambda x: float(x) - 0.02)
return df_nav, ''
class BarclayAgent(RestAgent):
def __init__(self):
RestAgent.__init__(self)
self.add_headers({'Referer': 'https://www.barclayhedge.com/research/indices/ghs/Equity_Long_Short_Index.html'})
self.add_headers({'Content - Type': 'application / x - www - form - urlencoded'})
def get_data(self, index):
prog_cod = index_map[index]
url = "https://www.barclayhedge.com/cgi-bin/barclay_stats/ghsndx.cgi"
param = {
'dump': 'excel',
'prog_cod': prog_cod,
}
response = self.do_request(url, param=param, method='POST', type='binary')
if response is not None:
excel = pd.ExcelFile(io.BytesIO(response))
df = excel.parse('Sheet1').dropna(how='all').copy().reset_index().drop(0)
df.columns = ['year', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'YTD']
df = df.set_index('year')
return df, ''
return None, "获取数据失败" | [
"json.loads",
"opendatatools.common.RestAgent.__init__",
"io.BytesIO",
"time.sleep",
"pandas.DataFrame",
"hashlib.sha1",
"pandas.concat",
"progressbar.ProgressBar"
] | [((1042, 1066), 'opendatatools.common.RestAgent.__init__', 'RestAgent.__init__', (['self'], {}), '(self)\n', (1060, 1066), False, 'from opendatatools.common import RestAgent, md5\n'), ((1529, 1549), 'json.loads', 'json.loads', (['response'], {}), '(response)\n', (1539, 1549), False, 'import json\n'), ((2512, 2532), 'json.loads', 'json.loads', (['response'], {}), '(response)\n', (2522, 2532), False, 'import json\n'), ((2670, 2699), 'pandas.DataFrame', 'pd.DataFrame', (["jsonobj['data']"], {}), "(jsonobj['data'])\n", (2682, 2699), True, 'import pandas as pd\n'), ((3411, 3429), 'pandas.concat', 'pd.concat', (['df_list'], {}), '(df_list)\n', (3420, 3429), True, 'import pandas as pd\n'), ((3760, 3774), 'hashlib.sha1', 'hashlib.sha1', ([], {}), '()\n', (3772, 3774), False, 'import hashlib\n'), ((4265, 4285), 'json.loads', 'json.loads', (['response'], {}), '(response)\n', (4275, 4285), False, 'import json\n'), ((4652, 4666), 'hashlib.sha1', 'hashlib.sha1', ([], {}), '()\n', (4664, 4666), False, 'import hashlib\n'), ((5457, 5477), 'json.loads', 'json.loads', (['response'], {}), '(response)\n', (5467, 5477), False, 'import json\n'), ((5613, 5642), 'pandas.DataFrame', 'pd.DataFrame', (["jsonobj['data']"], {}), "(jsonobj['data'])\n", (5625, 5642), True, 'import pandas as pd\n'), ((8235, 8253), 'pandas.concat', 'pd.concat', (['df_list'], {}), '(df_list)\n', (8244, 8253), True, 'import pandas as pd\n'), ((9116, 9140), 'opendatatools.common.RestAgent.__init__', 'RestAgent.__init__', (['self'], {}), '(self)\n', (9134, 9140), False, 'from opendatatools.common import RestAgent, md5\n'), ((3042, 3055), 'progressbar.ProgressBar', 'ProgressBar', ([], {}), '()\n', (3053, 3055), False, 'from progressbar import ProgressBar\n'), ((8193, 8216), 'time.sleep', 'time.sleep', (['time_elapse'], {}), '(time_elapse)\n', (8203, 8216), False, 'import time\n'), ((9741, 9761), 'io.BytesIO', 'io.BytesIO', (['response'], {}), '(response)\n', (9751, 9761), False, 'import io\n')] |
#==========================================================================================
# A very clumsy attemp to read and write data stored in csv files
# because I have tried hard to write cutomized data file in .npz and .pt but both gave trouble
# so I gave up and now use the old good csv--->but everything is a string so I need to convert everyhing
# resources from https://docs.python.org/3.6/library/csv.html#module-contents
# https://code.tutsplus.com/tutorials/how-to-read-and-write-csv-files-in-python--cms-29907
# and https://github.com/utkuozbulak/pytorch-custom-dataset-examples
#==========================================================================================
import random, string, copy, math, os, sys, csv
import numpy as np
import pandas as pd
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import torch
#importing pyTorch's neural network object + optimizer
from torch import nn, optim
#import functions like ReLU and log softmax
import torch.nn.functional as F
from torchvision import datasets, transforms
# everything must be float/long data type
# IMPORTANT NOTEs: pytorch only takes 0-based labels, so last col is just
# 0=256, 1=512, 2=1024, 3=2048, 4=4096, 5=8192
data = [
[1000., 100., 50., 50., 2, '1024'],
[1000., 100., 50., 50., 2, '1024'],
[1000., 100., 50., 50., 0, '256'],
[1000., 100., 50., 50., 1, '512'],
[1000., 100., 50., 50., 2, '1024'],
[1000., 100., 50., 50., 0, '256'],
[1000., 100., 50., 50., 2, '1024'],
[1000., 100., 50., 50., 2, '1024'],
[1000., 100., 50., 50., 1, '512'],
[1000., 100., 50., 50., 2, '1024'],
[1000., 100., 50., 50., 1, '512'],
[1000., 100., 50., 50., 0, '256'],
[1000., 100., 50., 50., 0, '256'],
[1000., 100., 50., 50., 1, '512'],
# first 14
[100., 100., 50., 50., 2, '1024'],
[100., 100., 50., 50., 1, '512'],
[100., 100., 50., 50., 2, '1024'],
[100., 100., 50., 50., 0, '256'],
[100., 100., 50., 50., 1, '512'],
[100., 100., 50., 50., 2, '1024'],
[100., 100., 50., 50., 1, '512'],
[100., 100., 50., 50., 1, '512']
]
def writeCSV():
with open('data/data.csv', 'w', newline='') as dataFile:
writer = csv.writer(dataFile)
writer.writerows(data)
print("Writing complete")
# need to rewrite the csv file everytime we add new data
writeCSV()
def readCSV():
with open('data/data.csv', newline='') as dataFile:
reader = csv.reader(dataFile)
for row in reader:
print(row)
def customCSV(csvPath):
dataset = pd.read_csv(csvPath, header=None)
xLocation = np.asarray(dataset.iloc[:, 0])
xEmptySquare = np.asarray(dataset.iloc[:, 1])
xMono = np.asarray(dataset.iloc[:, 2])
xSmooth = np.asarray(dataset.iloc[:, 3])
parameters = []
for row in range(len(xLocation)):
parameters.append([xLocation[row], xEmptySquare[row], xMono[row], xSmooth[row] ])
parameters = np.array(parameters)
# Second column is the labels, datatype: numpy array, float
labels = np.asarray(dataset.iloc[:, 4])
#print(labels)
return dataset, parameters, labels
#dataset, parameters, labels = customCSV('data/data.csv')
| [
"pandas.read_csv",
"csv.writer",
"numpy.asarray",
"numpy.array",
"csv.reader"
] | [((2653, 2686), 'pandas.read_csv', 'pd.read_csv', (['csvPath'], {'header': 'None'}), '(csvPath, header=None)\n', (2664, 2686), True, 'import pandas as pd\n'), ((2708, 2738), 'numpy.asarray', 'np.asarray', (['dataset.iloc[:, 0]'], {}), '(dataset.iloc[:, 0])\n', (2718, 2738), True, 'import numpy as np\n'), ((2762, 2792), 'numpy.asarray', 'np.asarray', (['dataset.iloc[:, 1]'], {}), '(dataset.iloc[:, 1])\n', (2772, 2792), True, 'import numpy as np\n'), ((2809, 2839), 'numpy.asarray', 'np.asarray', (['dataset.iloc[:, 2]'], {}), '(dataset.iloc[:, 2])\n', (2819, 2839), True, 'import numpy as np\n'), ((2858, 2888), 'numpy.asarray', 'np.asarray', (['dataset.iloc[:, 3]'], {}), '(dataset.iloc[:, 3])\n', (2868, 2888), True, 'import numpy as np\n'), ((3071, 3091), 'numpy.array', 'np.array', (['parameters'], {}), '(parameters)\n', (3079, 3091), True, 'import numpy as np\n'), ((3178, 3208), 'numpy.asarray', 'np.asarray', (['dataset.iloc[:, 4]'], {}), '(dataset.iloc[:, 4])\n', (3188, 3208), True, 'import numpy as np\n'), ((2298, 2318), 'csv.writer', 'csv.writer', (['dataFile'], {}), '(dataFile)\n', (2308, 2318), False, 'import random, string, copy, math, os, sys, csv\n'), ((2539, 2559), 'csv.reader', 'csv.reader', (['dataFile'], {}), '(dataFile)\n', (2549, 2559), False, 'import random, string, copy, math, os, sys, csv\n')] |
import os
import numpy as np
# import jax.numpy as jnp
from sklearn.decomposition import TruncatedSVD
def Temporal_basis_POD(K, SAVE_T_POD=False, FOLDER_OUT='./',n_Modes=10):
"""
This method computes the POD basis. For some theoretical insights, you can find
the theoretical background of the proper orthogonal decomposition in a nutshell here:
https://youtu.be/8fhupzhAR_M
--------------------------------------------------------------------------------------------------------------------
Parameters:
----------
:param FOLDER_OUT: str
Folder in which the results will be saved (if SAVE_T_POD=True)
:param K: np.array
Temporal correlation matrix
:param SAVE_T_POD: bool
A flag deciding whether the results are saved on disk or not. If the MEMORY_SAVING feature is active, it is
switched True by default.
:param n_Modes: int
number of modes that will be computed
--------------------------------------------------------------------------------------------------------------------
Returns:
--------
:return: Psi_P: np.array
POD Psis
:return: Sigma_P: np.array
POD Sigmas
"""
# Solver 1: Use the standard SVD
# Psi_P, Lambda_P, _ = np.linalg.svd(K)
# Sigma_P = np.sqrt(Lambda_P)
# Solver 2: Use randomized SVD ############## WARNING #################
svd = TruncatedSVD(n_Modes)
svd.fit_transform(K)
Psi_P = svd.components_.T
Lambda_P=svd.singular_values_
Sigma_P=np.sqrt(Lambda_P)
if SAVE_T_POD:
os.makedirs(FOLDER_OUT + "/POD/", exist_ok=True)
print("Saving POD temporal basis")
np.savez(FOLDER_OUT + '/POD/temporal_basis', Psis=Psi_P, Lambdas=Lambda_P, Sigmas=Sigma_P)
return Psi_P, Sigma_P
| [
"os.makedirs",
"numpy.savez",
"numpy.sqrt",
"sklearn.decomposition.TruncatedSVD"
] | [((1438, 1459), 'sklearn.decomposition.TruncatedSVD', 'TruncatedSVD', (['n_Modes'], {}), '(n_Modes)\n', (1450, 1459), False, 'from sklearn.decomposition import TruncatedSVD\n'), ((1561, 1578), 'numpy.sqrt', 'np.sqrt', (['Lambda_P'], {}), '(Lambda_P)\n', (1568, 1578), True, 'import numpy as np\n'), ((1611, 1659), 'os.makedirs', 'os.makedirs', (["(FOLDER_OUT + '/POD/')"], {'exist_ok': '(True)'}), "(FOLDER_OUT + '/POD/', exist_ok=True)\n", (1622, 1659), False, 'import os\n'), ((1711, 1805), 'numpy.savez', 'np.savez', (["(FOLDER_OUT + '/POD/temporal_basis')"], {'Psis': 'Psi_P', 'Lambdas': 'Lambda_P', 'Sigmas': 'Sigma_P'}), "(FOLDER_OUT + '/POD/temporal_basis', Psis=Psi_P, Lambdas=Lambda_P,\n Sigmas=Sigma_P)\n", (1719, 1805), True, 'import numpy as np\n')] |
import networkx as nx
import matplotlib.pyplot as plt
from nxviz import GeoPlot
G = nx.read_gpickle("divvy.pkl")
print(list(G.nodes(data=True))[0])
G_new = G.copy()
for n1, n2, d in G.edges(data=True):
if d["count"] < 200:
G_new.remove_edge(n1, n2)
g = GeoPlot(
G_new,
node_lat="latitude",
node_lon="longitude",
node_color="dpcapacity",
node_size=0.005,
)
g.draw()
plt.show()
| [
"networkx.read_gpickle",
"nxviz.GeoPlot",
"matplotlib.pyplot.show"
] | [((86, 114), 'networkx.read_gpickle', 'nx.read_gpickle', (['"""divvy.pkl"""'], {}), "('divvy.pkl')\n", (101, 114), True, 'import networkx as nx\n'), ((268, 372), 'nxviz.GeoPlot', 'GeoPlot', (['G_new'], {'node_lat': '"""latitude"""', 'node_lon': '"""longitude"""', 'node_color': '"""dpcapacity"""', 'node_size': '(0.005)'}), "(G_new, node_lat='latitude', node_lon='longitude', node_color=\n 'dpcapacity', node_size=0.005)\n", (275, 372), False, 'from nxviz import GeoPlot\n'), ((402, 412), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (410, 412), True, 'import matplotlib.pyplot as plt\n')] |
# -*- coding: utf-8 -*-
import re
import fnmatch
import itertools
import six
from .util import matcher
class TaskContainer(list):
"""Contains tasks. Tasks can be accessed by task_no or by name"""
def __init__(self, *args, **kwargs):
self.by_name = dict()
return super(TaskContainer, self).__init__(*args, **kwargs)
def _update(self, task):
self.by_name[task.name] = task
def _get_or_search(self, key):
if '*' in key:
hits = list(self.search(fnmatch.translate(key)))
if not hits:
raise KeyError
return hits
return self.by_name[key]
def search(self, q):
return iter(val for val in self if re.search(q, val.name))
def append(self, task):
self._update(task)
return super(TaskContainer, self).append(task)
def extend(self, iterable):
a, b = itertools.tee(iterable)
for task in a:
self._update(task)
return super(TaskContainer, self).extend(b)
def __setitem__(self, key, task):
self._update(task)
return super(TaskContainer, self).__setitem__(key, task)
def __getitem__(self, key):
try:
if isinstance(key, six.string_types):
return self._get_or_search(key)
return super(TaskContainer, self).__getitem__(key)
except KeyError:
msg = "Unable to find task with `{}'. Perhaps you meant `{}'?"
m = matcher.closest(key, iter(t.name for t in self))[0][1]
raise KeyError(msg.format(key, m))
except IndexError:
msg = "No task with number {}. There are only {} tasks."
raise IndexError(msg.format(key, len(self)))
def __contains__(self, item):
if isinstance(item, six.string_types):
if '*' in item:
try:
next(self.search(fnmatch.translate(item)))
return True
except StopIteration:
return False
else:
return item in self.by_name
return super(TaskContainer, self).__contains__(item)
| [
"re.search",
"fnmatch.translate",
"itertools.tee"
] | [((911, 934), 'itertools.tee', 'itertools.tee', (['iterable'], {}), '(iterable)\n', (924, 934), False, 'import itertools\n'), ((518, 540), 'fnmatch.translate', 'fnmatch.translate', (['key'], {}), '(key)\n', (535, 540), False, 'import fnmatch\n'), ((726, 748), 're.search', 're.search', (['q', 'val.name'], {}), '(q, val.name)\n', (735, 748), False, 'import re\n'), ((1922, 1945), 'fnmatch.translate', 'fnmatch.translate', (['item'], {}), '(item)\n', (1939, 1945), False, 'import fnmatch\n')] |
from core.framework.module import BaseModule
import ast
import time
import difflib
class Module(BaseModule):
meta = {
'name': 'Jailbreak Detection',
'author': '@LanciniMarco (@MWRLabs)',
'description': 'Verify that the app cannot be run on a jailbroken device. Currently detects if the app applies jailbreak detection at startup.',
'options': (
),
}
PID = None
WATCH_TIME = 10
EXIT = False
# ==================================================================================================================
# UTILS
# ==================================================================================================================
def _monitor_fs_start(self):
# Remote output file
self.fsmon_out = self.device.remote_op.build_temp_path_for_file("fsmon")
# Run command in a thread
cmd = '{app} -j -a {watchtime} -P "ReportCrash" {flt} &> {fname} & echo $!'.format(app=self.device.DEVICE_TOOLS['FSMON'],
watchtime=self.WATCH_TIME,
flt='/',
fname=self.fsmon_out)
self.device.remote_op.command_background_start(self, cmd)
def _parse_changed_files(self):
# Read output of file monitoring
file_list_str = self.device.remote_op.read_file(self.fsmon_out)
if not file_list_str:
self.printer.warning('No crashes identified. It is possible that jailbreak detection might be applied at a later stage in the app.')
self.EXIT = True
return
# Intepret string to list
file_list = ast.literal_eval(file_list_str[0])
# Eliminate duplicates and filter log files
fnames = list(set([el['filename'] for el in file_list]))
self.crashes = filter(lambda x: x.endswith('.log'), fnames)
# Print identified files
if self.crashes:
self.printer.notify('The following crash files has been identified')
map(self.printer.notify, self.crashes)
else:
self.printer.warning('No crashes identified. It is possible that jailbreak detection might be applied at a later stage in the app.')
self.EXIT = True
def detect_crash_files(self):
# Monitor filesystem for a crash
self.printer.info("Monitoring the filesystem for a crash...")
self._monitor_fs_start()
# Launch the app
self.printer.info("Launching the app multiple times to trigger a crash...")
self.device.app.open(self.APP_METADATA['bundle_id'])
self.device.app.open(self.APP_METADATA['bundle_id'])
self.device.app.open(self.APP_METADATA['bundle_id'])
time.sleep(self.WATCH_TIME)
# Parse changed files
self.printer.info("Looking for crash files...")
self._parse_changed_files()
def parse_crash_files(self):
self.printer.info("Parsing current status of crash files...")
self.crash_details = []
for fp in self.crashes:
content = self.device.remote_op.read_file(fp)
self.crash_details.append({'file': fp, 'content': content})
def diff_crash_files(self):
arxan = False
for el in self.crash_details:
# Prepare orig and new
fname, content_orig = el['file'], el['content']
self.printer.info('Analyzing: %s' % fname)
content_new = self.device.remote_op.read_file(fname)
# Diff
diff = difflib.unified_diff(content_orig, content_new)
# Extract new lines
if diff:
self.printer.notify('New crashes identified (probable indicator of jailbreak detection):')
for dd in diff:
dline = dd.strip()
if dline.startswith('+') and not dline.endswith('+'):
self.printer.notify(dline)
if 'KERN_INVALID_ADDRESS' in dline:
arxan = True
if arxan:
self.printer.notify('Arxan Detected!')
# ==================================================================================================================
# RUN
# ==================================================================================================================
def module_run(self):
# Detect crash files
self.detect_crash_files()
if not self.EXIT:
# Parse crash files
self.parse_crash_files()
# Launch the app
self.printer.info("Launching the app again...")
self.device.app.open(self.APP_METADATA['bundle_id'])
self.device.app.open(self.APP_METADATA['bundle_id'])
self.device.app.open(self.APP_METADATA['bundle_id'])
# Diff crash files
self.diff_crash_files()
| [
"ast.literal_eval",
"time.sleep",
"difflib.unified_diff"
] | [((1877, 1911), 'ast.literal_eval', 'ast.literal_eval', (['file_list_str[0]'], {}), '(file_list_str[0])\n', (1893, 1911), False, 'import ast\n'), ((2975, 3002), 'time.sleep', 'time.sleep', (['self.WATCH_TIME'], {}), '(self.WATCH_TIME)\n', (2985, 3002), False, 'import time\n'), ((3789, 3836), 'difflib.unified_diff', 'difflib.unified_diff', (['content_orig', 'content_new'], {}), '(content_orig, content_new)\n', (3809, 3836), False, 'import difflib\n')] |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# By: <NAME> (Tedezed)
# Source: https://github.com/Tedezed
# Mail: <EMAIL>
from sys import argv
from copy import deepcopy
from chronos import *
from module_control import *
debug = True
def argument_to_dic(list):
dic = {}
for z in list:
dic[z[0]] = z[1]
return dic
def main():
list_argv = []
argv_ext = deepcopy(argv)
argv_ext.remove(argv_ext[0])
for elements in argv_ext:
var_input = elements.split("=")
if len(var_input) == 1 or var_input[1] == '':
raise NameError('[ERROR] (main) Invalid Arguments [python example.py var="text"]')
list_argv.append(var_input)
dic_argv = argument_to_dic(list_argv)
chronos_backup = chronos(dic_argv, debug)
chronos_backup.check_disk("/chronos/backups")
try:
chronos_backup.start_chronos()
except Exception as error:
print("[ERROR] (main) %s" % str(error))
logging.error(error)
send_mail("[ERROR] Mode %s" \
% ("(main)"), str(error).replace("<","").replace(">",""), debug)
else:
print("[ERROR] (main) Mode not found")
if __name__ == '__main__':
# Start
main()
| [
"copy.deepcopy"
] | [((381, 395), 'copy.deepcopy', 'deepcopy', (['argv'], {}), '(argv)\n', (389, 395), False, 'from copy import deepcopy\n')] |
import numpy as np
import pandas as pd
import torch
import src.configuration as C
import src.dataset as dataset
import src.models as models
import src.utils as utils
from pathlib import Path
from fastprogress import progress_bar
if __name__ == "__main__":
args = utils.get_sed_parser().parse_args()
config = utils.load_config(args.config)
global_params = config["globals"]
output_dir = Path(global_params["output_dir"])
output_dir.mkdir(exist_ok=True, parents=True)
utils.set_seed(global_params["seed"])
device = C.get_device(global_params["device"])
df, datadir = C.get_metadata(config)
splitter = C.get_split(config)
for i, (_, val_idx) in enumerate(splitter.split(df, y=df["ebird_code"])):
if i not in global_params["folds"]:
continue
val_df = df.loc[val_idx, :].reset_index(drop=True)
loader = C.get_sed_inference_loader(val_df, datadir, config)
model = models.get_model_for_inference(config,
global_params["weights"][i])
if not torch.cuda.is_available():
device = torch.device("cpu")
else:
device = torch.device("cuda")
model.to(device)
model.eval()
estimated_event_list = []
for batch in progress_bar(loader):
waveform = batch["waveform"]
ebird_code = batch["ebird_code"][0]
wav_name = batch["wav_name"][0]
target = batch["targets"].detach().cpu().numpy()[0]
global_time = 0.0
if waveform.ndim == 3:
waveform = waveform.squeeze(0)
batch_size = 32
whole_size = waveform.size(0)
if whole_size % batch_size == 0:
n_iter = whole_size // batch_size
else:
n_iter = whole_size // batch_size + 1
for index in range(n_iter):
iter_batch = waveform[index * batch_size:(index + 1) * batch_size]
if iter_batch.ndim == 1:
iter_batch = iter_batch.unsqueeze(0)
iter_batch = iter_batch.to(device)
with torch.no_grad():
prediction = model(iter_batch)
framewise_output = prediction["framewise_output"].detach(
).cpu().numpy()
thresholded = framewise_output >= args.threshold
target_indices = np.argwhere(target).reshape(-1)
for short_clip in thresholded:
for target_idx in target_indices:
if short_clip[:, target_idx].mean() == 0:
pass
else:
detected = np.argwhere(
short_clip[:, target_idx]).reshape(-1)
head_idx = 0
tail_idx = 0
while True:
if (tail_idx + 1 == len(detected)) or (
detected[tail_idx + 1] -
detected[tail_idx] != 1):
onset = 0.01 * detected[head_idx] + global_time
offset = 0.01 * detected[tail_idx] + global_time
estimated_event = {
"filename": wav_name,
"ebird_code": dataset.INV_BIRD_CODE[target_idx],
"onset": onset,
"offset": offset
}
estimated_event_list.append(estimated_event)
head_idx = tail_idx + 1
tail_idx = tail_idx + 1
if head_idx > len(detected):
break
else:
tail_idx = tail_idx + 1
global_time += 5.0
estimated_event_df = pd.DataFrame(estimated_event_list)
save_filename = global_params["save_path"].replace(".csv", "")
save_filename += f"_th{args.threshold}" + ".csv"
save_path = output_dir / save_filename
if save_path.exists():
event_level_labels = pd.read_csv(save_path)
estimated_event_df = pd.concat(
[event_level_labels, estimated_event_df], axis=0,
sort=False).reset_index(drop=True)
estimated_event_df.to_csv(save_path, index=False)
else:
estimated_event_df.to_csv(save_path, index=False)
| [
"src.utils.get_sed_parser",
"src.configuration.get_metadata",
"src.models.get_model_for_inference",
"pathlib.Path",
"fastprogress.progress_bar",
"src.configuration.get_device",
"src.configuration.get_split",
"pandas.read_csv",
"src.configuration.get_sed_inference_loader",
"torch.cuda.is_available"... | [((321, 351), 'src.utils.load_config', 'utils.load_config', (['args.config'], {}), '(args.config)\n', (338, 351), True, 'import src.utils as utils\n'), ((409, 442), 'pathlib.Path', 'Path', (["global_params['output_dir']"], {}), "(global_params['output_dir'])\n", (413, 442), False, 'from pathlib import Path\n'), ((498, 535), 'src.utils.set_seed', 'utils.set_seed', (["global_params['seed']"], {}), "(global_params['seed'])\n", (512, 535), True, 'import src.utils as utils\n'), ((549, 586), 'src.configuration.get_device', 'C.get_device', (["global_params['device']"], {}), "(global_params['device'])\n", (561, 586), True, 'import src.configuration as C\n'), ((606, 628), 'src.configuration.get_metadata', 'C.get_metadata', (['config'], {}), '(config)\n', (620, 628), True, 'import src.configuration as C\n'), ((644, 663), 'src.configuration.get_split', 'C.get_split', (['config'], {}), '(config)\n', (655, 663), True, 'import src.configuration as C\n'), ((885, 936), 'src.configuration.get_sed_inference_loader', 'C.get_sed_inference_loader', (['val_df', 'datadir', 'config'], {}), '(val_df, datadir, config)\n', (911, 936), True, 'import src.configuration as C\n'), ((953, 1020), 'src.models.get_model_for_inference', 'models.get_model_for_inference', (['config', "global_params['weights'][i]"], {}), "(config, global_params['weights'][i])\n", (983, 1020), True, 'import src.models as models\n'), ((1314, 1334), 'fastprogress.progress_bar', 'progress_bar', (['loader'], {}), '(loader)\n', (1326, 1334), False, 'from fastprogress import progress_bar\n'), ((4174, 4208), 'pandas.DataFrame', 'pd.DataFrame', (['estimated_event_list'], {}), '(estimated_event_list)\n', (4186, 4208), True, 'import pandas as pd\n'), ((272, 294), 'src.utils.get_sed_parser', 'utils.get_sed_parser', ([], {}), '()\n', (292, 294), True, 'import src.utils as utils\n'), ((1084, 1109), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1107, 1109), False, 'import torch\n'), ((1132, 1151), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (1144, 1151), False, 'import torch\n'), ((1187, 1207), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (1199, 1207), False, 'import torch\n'), ((4448, 4470), 'pandas.read_csv', 'pd.read_csv', (['save_path'], {}), '(save_path)\n', (4459, 4470), True, 'import pandas as pd\n'), ((2177, 2192), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2190, 2192), False, 'import torch\n'), ((4504, 4575), 'pandas.concat', 'pd.concat', (['[event_level_labels, estimated_event_df]'], {'axis': '(0)', 'sort': '(False)'}), '([event_level_labels, estimated_event_df], axis=0, sort=False)\n', (4513, 4575), True, 'import pandas as pd\n'), ((2458, 2477), 'numpy.argwhere', 'np.argwhere', (['target'], {}), '(target)\n', (2469, 2477), True, 'import numpy as np\n'), ((2759, 2797), 'numpy.argwhere', 'np.argwhere', (['short_clip[:, target_idx]'], {}), '(short_clip[:, target_idx])\n', (2770, 2797), True, 'import numpy as np\n')] |
import requests
import json
from bs4 import BeautifulSoup
BASE_URL = 'https://cobalt.qas.im/documentation/%s/filter'
def scrape(api_endpoint):
"""Scrape filter keys from the Cobalt documentation of api_endpoint."""
host = BASE_URL % api_endpoint
resp = requests.get(host)
soup = BeautifulSoup(resp.text, 'html.parser')
filters = []
if not soup.find('table'):
return filters
for tr in soup.find('table').find_all('tr'):
if tr.find('th') or not tr.find('td'):
continue
filters.append(tr.find('td').text)
return filters
def main(active_apis):
"""Scrape and return filter keys for active_apis."""
filters = {}
for api in active_apis:
filters[api] = scrape(api)
return filters
if __name__ == '__main__':
main()
| [
"bs4.BeautifulSoup",
"requests.get"
] | [((270, 288), 'requests.get', 'requests.get', (['host'], {}), '(host)\n', (282, 288), False, 'import requests\n'), ((300, 339), 'bs4.BeautifulSoup', 'BeautifulSoup', (['resp.text', '"""html.parser"""'], {}), "(resp.text, 'html.parser')\n", (313, 339), False, 'from bs4 import BeautifulSoup\n')] |
from flask import Blueprint, render_template, request, redirect, url_for, Response
from flask.views import MethodView
from flask.ext.login import login_required, current_user
from lablog import config
from lablog.models.client import SocialAccount, FacebookPage, PageCategory
from flask_oauth import OAuth
import logging
from urlparse import parse_qs, urlparse
import json
oauth = OAuth()
facebook = Blueprint(
"facebook",
__name__,
template_folder=config.TEMPLATES,
url_prefix="/auth/facebook",
)
fb_app = oauth.remote_app(
'facebook',
base_url='https://graph.facebook.com/',
request_token_url=None,
access_token_url='/oauth/access_token',
authorize_url='https://www.facebook.com/dialog/oauth',
consumer_key=config.FACEBOOK_APP_ID,
consumer_secret=config.FACEBOOK_APP_SECRET,
request_token_params={'scope': 'manage_pages,read_insights,ads_management'}
)
@fb_app.tokengetter
def get_facebook_token(token=None):
sa = current_user.social_account(SocialAccount.FACEBOOK)
return (sa.token, config.FACEBOOK_APP_SECRET)
@facebook.route("/login", methods=['GET', 'POST'])
@login_required
def login():
return fb_app.authorize(
callback=url_for('.authorized',
next=request.args.get('next'), _external=True)
)
@facebook.route("/authorized", methods=['GET', 'POST'])
@fb_app.authorized_handler
@login_required
def authorized(resp):
if resp is None:
flash("You denied the request", "danger")
return redirect(url_for(".index"))
try:
append = True
sa = current_user.social_account(account_type=SocialAccount.FACEBOOK)
if sa.token: append = False
sa.token = resp.get('access_token')
if append: current_user.social_accounts.append(sa)
current_user.save()
except Exception as e:
logging.exception(e)
return redirect(url_for(".verify"))
def get_pages(user_id):
pages = []
res = fb_app.get("/{}/accounts".format(user_id))
pages = [p for p in res.data.get("data")]
while res.data.get("paging", {}).get("next"):
res = fb_app.get(
"/{}/accounts".format(user_id),
data={
"after":res.data.get("paging", {}).get("cursor").get("after")
}
)
pages+= [p for p in res.data.get("data")]
return pages
def get_long_token(token):
long_token = fb_app.get(
"/oauth/access_token",
data={
'grant_type':'fb_exchange_token',
'fb_exchange_token':token,
'client_id':config.FACEBOOK_APP_ID,
'client_secret':config.FACEBOOK_APP_SECRET,
}
)
token = parse_qs(long_token.data, keep_blank_values=True)
return {'token':token.get('access_token', [""])[0], 'expires':token.get('expires', [""])[0]}
class Index(MethodView):
decorators = [ login_required, ]
def get(self):
return render_template("auth/facebook/index.html")
class Verify(MethodView):
decorators = [ login_required, ]
def get(self):
return render_template("auth/facebook/load_pages.html")
class LoadPages(MethodView):
decorators = [ login_required, ]
def get(self):
sa = current_user.social_account(SocialAccount.FACEBOOK)
res = fb_app.get(
"/debug_token",
data={
'input_token':sa.token
}
)
if res:
data = res.data.get('data')
sa.id = data.get("user_id")
sa.app_id = data.get("app_id")
[sa.permissions.append(p) for p in data.get("scopes") if p not in sa.permissions]
current_user.save()
token = get_long_token(sa.token)
sa.token = token['token']
sa.expires = token['expires']
current_user.save()
pages = get_pages(sa.id)
logging.info(pages)
for page in pages:
for p in current_user.facebook_pages:
if page.get("id") == p.id:
break
else:
fp = FacebookPage()
fp.name = page.get("name")
fp.token = page.get("access_token")
fp.id = page.get("id")
[fp.permissions.append(perm) for perm in page.get("perms")]
for pc in page.get("category_list", []):
pca = PageCategory()
pca.id = pc.get("id")
pca.name = pc.get("name")
fp.categories.append(pca)
current_user.facebook_pages.append(fp)
current_user.save()
return render_template("auth/facebook/pages.html")
class SavePage(MethodView):
decorators = [login_required,]
def post(self):
id = request.form["id"]
logging.info(id);
cfp = current_user.client.facebook_page
for p in current_user.facebook_pages:
if p.id == id:
res = current_user.client.update({"$set":{"facebook_page":p._json()}})
logging.info(res)
break
return Response(json.dumps({'id':id}), mimetype='application/json')
facebook.add_url_rule("/", view_func=Index.as_view('index'))
facebook.add_url_rule("/verify", view_func=Verify.as_view('verify'))
facebook.add_url_rule("/loadpages", view_func=LoadPages.as_view('load_pages'))
facebook.add_url_rule("/save_page", view_func=SavePage.as_view('save_page'))
| [
"flask.render_template",
"flask.ext.login.current_user.social_accounts.append",
"flask.request.args.get",
"urlparse.parse_qs",
"flask.ext.login.current_user.social_account",
"flask.ext.login.current_user.facebook_pages.append",
"json.dumps",
"flask.url_for",
"logging.exception",
"flask_oauth.OAuth... | [((382, 389), 'flask_oauth.OAuth', 'OAuth', ([], {}), '()\n', (387, 389), False, 'from flask_oauth import OAuth\n'), ((402, 500), 'flask.Blueprint', 'Blueprint', (['"""facebook"""', '__name__'], {'template_folder': 'config.TEMPLATES', 'url_prefix': '"""/auth/facebook"""'}), "('facebook', __name__, template_folder=config.TEMPLATES,\n url_prefix='/auth/facebook')\n", (411, 500), False, 'from flask import Blueprint, render_template, request, redirect, url_for, Response\n'), ((972, 1023), 'flask.ext.login.current_user.social_account', 'current_user.social_account', (['SocialAccount.FACEBOOK'], {}), '(SocialAccount.FACEBOOK)\n', (999, 1023), False, 'from flask.ext.login import login_required, current_user\n'), ((2667, 2716), 'urlparse.parse_qs', 'parse_qs', (['long_token.data'], {'keep_blank_values': '(True)'}), '(long_token.data, keep_blank_values=True)\n', (2675, 2716), False, 'from urlparse import parse_qs, urlparse\n'), ((1570, 1634), 'flask.ext.login.current_user.social_account', 'current_user.social_account', ([], {'account_type': 'SocialAccount.FACEBOOK'}), '(account_type=SocialAccount.FACEBOOK)\n', (1597, 1634), False, 'from flask.ext.login import login_required, current_user\n'), ((1782, 1801), 'flask.ext.login.current_user.save', 'current_user.save', ([], {}), '()\n', (1799, 1801), False, 'from flask.ext.login import login_required, current_user\n'), ((1879, 1897), 'flask.url_for', 'url_for', (['""".verify"""'], {}), "('.verify')\n", (1886, 1897), False, 'from flask import Blueprint, render_template, request, redirect, url_for, Response\n'), ((2912, 2955), 'flask.render_template', 'render_template', (['"""auth/facebook/index.html"""'], {}), "('auth/facebook/index.html')\n", (2927, 2955), False, 'from flask import Blueprint, render_template, request, redirect, url_for, Response\n'), ((3054, 3102), 'flask.render_template', 'render_template', (['"""auth/facebook/load_pages.html"""'], {}), "('auth/facebook/load_pages.html')\n", (3069, 3102), False, 'from flask import Blueprint, render_template, request, redirect, url_for, Response\n'), ((3202, 3253), 'flask.ext.login.current_user.social_account', 'current_user.social_account', (['SocialAccount.FACEBOOK'], {}), '(SocialAccount.FACEBOOK)\n', (3229, 3253), False, 'from flask.ext.login import login_required, current_user\n'), ((4689, 4732), 'flask.render_template', 'render_template', (['"""auth/facebook/pages.html"""'], {}), "('auth/facebook/pages.html')\n", (4704, 4732), False, 'from flask import Blueprint, render_template, request, redirect, url_for, Response\n'), ((4858, 4874), 'logging.info', 'logging.info', (['id'], {}), '(id)\n', (4870, 4874), False, 'import logging\n'), ((1506, 1523), 'flask.url_for', 'url_for', (['""".index"""'], {}), "('.index')\n", (1513, 1523), False, 'from flask import Blueprint, render_template, request, redirect, url_for, Response\n'), ((1734, 1773), 'flask.ext.login.current_user.social_accounts.append', 'current_user.social_accounts.append', (['sa'], {}), '(sa)\n', (1769, 1773), False, 'from flask.ext.login import login_required, current_user\n'), ((1837, 1857), 'logging.exception', 'logging.exception', (['e'], {}), '(e)\n', (1854, 1857), False, 'import logging\n'), ((3635, 3654), 'flask.ext.login.current_user.save', 'current_user.save', ([], {}), '()\n', (3652, 3654), False, 'from flask.ext.login import login_required, current_user\n'), ((3792, 3811), 'flask.ext.login.current_user.save', 'current_user.save', ([], {}), '()\n', (3809, 3811), False, 'from flask.ext.login import login_required, current_user\n'), ((3861, 3880), 'logging.info', 'logging.info', (['pages'], {}), '(pages)\n', (3873, 3880), False, 'import logging\n'), ((4654, 4673), 'flask.ext.login.current_user.save', 'current_user.save', ([], {}), '()\n', (4671, 4673), False, 'from flask.ext.login import login_required, current_user\n'), ((5165, 5187), 'json.dumps', 'json.dumps', (["{'id': id}"], {}), "({'id': id})\n", (5175, 5187), False, 'import json\n'), ((5100, 5117), 'logging.info', 'logging.info', (['res'], {}), '(res)\n', (5112, 5117), False, 'import logging\n'), ((1241, 1265), 'flask.request.args.get', 'request.args.get', (['"""next"""'], {}), "('next')\n", (1257, 1265), False, 'from flask import Blueprint, render_template, request, redirect, url_for, Response\n'), ((4090, 4104), 'lablog.models.client.FacebookPage', 'FacebookPage', ([], {}), '()\n', (4102, 4104), False, 'from lablog.models.client import SocialAccount, FacebookPage, PageCategory\n'), ((4603, 4641), 'flask.ext.login.current_user.facebook_pages.append', 'current_user.facebook_pages.append', (['fp'], {}), '(fp)\n', (4637, 4641), False, 'from flask.ext.login import login_required, current_user\n'), ((4422, 4436), 'lablog.models.client.PageCategory', 'PageCategory', ([], {}), '()\n', (4434, 4436), False, 'from lablog.models.client import SocialAccount, FacebookPage, PageCategory\n')] |
import cv2
'''
gets a video file and dumps each frame as a jpg picture in an output dir
'''
# Opens the Video file
cap = cv2.VideoCapture('./Subt_2.mp4')
i = 0
while(cap.isOpened()):
ret, frame = cap.read()
if i%(round(25*0.3)) == 0:
print(i)
if ret == False:
break
cv2.imwrite('./output/cave2-'+str(i)+'.jpg',frame)
i+=1
cap.release()
cv2.destroyAllWindows()
| [
"cv2.destroyAllWindows",
"cv2.VideoCapture"
] | [((131, 163), 'cv2.VideoCapture', 'cv2.VideoCapture', (['"""./Subt_2.mp4"""'], {}), "('./Subt_2.mp4')\n", (147, 163), False, 'import cv2\n'), ((411, 434), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (432, 434), False, 'import cv2\n')] |
import normalize
norm = normalize.normalize("heightdata.png", 6, 6)
class TestNormArray:
"""test_norm_array references requirement 3.0 because it shows 2x2 block area of (0,0),
(0,1), (1,0), (1,1), this area will for sure be a 2x2 block area"""
# \brief Ref : Req 3.0 One pixel in topographic image shall correspond to a 2x2 block area
def test_norm_array(self):
assert norm.getval(0, 0) == 66
assert norm.getval(0, 1) == 66
assert norm.getval(1, 0) == 66
assert norm.getval(1, 1) == 66
"""test_array_dimensions reference requirement 3.0 because if each pixel corresponds
to a 2x2 area, then the height and width will be doubled from 6x6 to 12x12 as an example"""
# \brief Ref : Req 3.0 One pixel in topographic image shall correspond to a 2x2 block area
def test_array_dimensions(self):
assert norm.height == 12
assert norm.width == 12
# \brief Ref : Req 1.2 Pixel values shall be normalized to represent a realistic range of block heights
# \brief Ref : Req 1.3 The realistic range of block heights shall be a minimum of 20 blocks and a maximum of 100 blocks
def test_max(self):
assert norm.get_max() == [100, 8, 8]
# \brief Ref : Req 1.2 Pixel values shall be normalized to represent a realistic range of block heights
# \brief Ref : Req 1.3 The realistic range of block heights shall be a minimum of 20 blocks and a maximum of 100 blocks
def test_min(self):
assert norm.get_min() == [20, 2, 0]
class TestProcessImage:
# \brief Ref : Req Req 1.1 Topographic image shall be a .png image
def test_file_ending(self):
## test file not ending in .png
assert normalize.process_image("heightdata.jpg", 10, 10) == 'File must be a .png \n'
def test_file_not_found(self):
## test file that doesn't exist
assert normalize.process_image("heightfile.png", 10, 10) == None
| [
"normalize.process_image",
"normalize.normalize"
] | [((25, 68), 'normalize.normalize', 'normalize.normalize', (['"""heightdata.png"""', '(6)', '(6)'], {}), "('heightdata.png', 6, 6)\n", (44, 68), False, 'import normalize\n'), ((1710, 1759), 'normalize.process_image', 'normalize.process_image', (['"""heightdata.jpg"""', '(10)', '(10)'], {}), "('heightdata.jpg', 10, 10)\n", (1733, 1759), False, 'import normalize\n'), ((1879, 1928), 'normalize.process_image', 'normalize.process_image', (['"""heightfile.png"""', '(10)', '(10)'], {}), "('heightfile.png', 10, 10)\n", (1902, 1928), False, 'import normalize\n')] |
# imports
import json
import argparse
import torch
from torch import nn
from torch import optim
from torch.optim import lr_scheduler
import torch.nn.functional as F
from torchvision import models
from collections import OrderedDict
from data_utils import load_data
from model_utils import define_model, train_model
# parse args from command line
def parse_arguments():
parser = argparse.ArgumentParser(
description='Parser command line arguments for Flower Image Classifier',
)
parser.add_argument('--data_dir', type=str , default='flowers', help='location of datasets')
parser.add_argument('--save_dir', type=str , default='saved_models/checkpoint.pth', help='location to save checkpoint')
parser.add_argument('--arch', type=str, default='vgg16', choices=['vgg16', 'vgg13'], help='Pretrained model architecture. vgg16 or vgg13')
parser.add_argument('--learning_rate', type=float , default=0.001, help='learning rate')
parser.add_argument('--hidden_units', type=int , default=512, help='hidden units')
parser.add_argument('--epochs', type=int , default=3, help='number of training epochs')
parser.add_argument('--gpu', type=bool , default=False, help='use a GPU')
return parser.parse_args()
def main():
# load data
image_datasets, dataloaders = load_data(args.data_dir)
# label mapping
with open('cat_to_name.json', 'r') as f:
cat_to_name = json.load(f)
categories_num = len(cat_to_name)
# load pretrained model(s)
model = define_model(args.arch, args.hidden_units, categories_num)
# Define loss Function
criterion = nn.NLLLoss()
# Define optimizer
optimizer = optim.Adam(model.classifier.parameters(), lr=args.learning_rate)
scheduler = lr_scheduler.StepLR(optimizer, step_size=5, gamma=0.1)
# Use GPU if available
device = torch.device("cuda" if args.gpu else "cpu")
model.to(device)
# train model
print("Start training model using: {}".format(device))
train_model(model, image_datasets, dataloaders, criterion, optimizer, scheduler, args.epochs, device)
print("Model training completed!")
# save checkpoint
if args.save_dir:
model.class_to_idx = image_datasets['train'].class_to_idx
checkpoint = {'arch': args.arch,
'state_dict': model.state_dict(),
'optimizer': optimizer.state_dict(),
'classifier': model.classifier,
'epochs': args.epochs,
'class_to_idx': model.class_to_idx}
torch.save(checkpoint, args.save_dir)
# Example command: python train.py --gpu true --arch vgg16 --learning_rate 0.003 --hidden_units 256 --epochs 5
if __name__ == "__main__":
args = parse_arguments()
main()
| [
"model_utils.define_model",
"data_utils.load_data",
"argparse.ArgumentParser",
"model_utils.train_model",
"torch.optim.lr_scheduler.StepLR",
"torch.nn.NLLLoss",
"torch.save",
"json.load",
"torch.device"
] | [((383, 484), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Parser command line arguments for Flower Image Classifier"""'}), "(description=\n 'Parser command line arguments for Flower Image Classifier')\n", (406, 484), False, 'import argparse\n'), ((1306, 1330), 'data_utils.load_data', 'load_data', (['args.data_dir'], {}), '(args.data_dir)\n', (1315, 1330), False, 'from data_utils import load_data\n'), ((1519, 1577), 'model_utils.define_model', 'define_model', (['args.arch', 'args.hidden_units', 'categories_num'], {}), '(args.arch, args.hidden_units, categories_num)\n', (1531, 1577), False, 'from model_utils import define_model, train_model\n'), ((1626, 1638), 'torch.nn.NLLLoss', 'nn.NLLLoss', ([], {}), '()\n', (1636, 1638), False, 'from torch import nn\n'), ((1760, 1814), 'torch.optim.lr_scheduler.StepLR', 'lr_scheduler.StepLR', (['optimizer'], {'step_size': '(5)', 'gamma': '(0.1)'}), '(optimizer, step_size=5, gamma=0.1)\n', (1779, 1814), False, 'from torch.optim import lr_scheduler\n'), ((1856, 1899), 'torch.device', 'torch.device', (["('cuda' if args.gpu else 'cpu')"], {}), "('cuda' if args.gpu else 'cpu')\n", (1868, 1899), False, 'import torch\n'), ((2007, 2112), 'model_utils.train_model', 'train_model', (['model', 'image_datasets', 'dataloaders', 'criterion', 'optimizer', 'scheduler', 'args.epochs', 'device'], {}), '(model, image_datasets, dataloaders, criterion, optimizer,\n scheduler, args.epochs, device)\n', (2018, 2112), False, 'from model_utils import define_model, train_model\n'), ((1423, 1435), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1432, 1435), False, 'import json\n'), ((2584, 2621), 'torch.save', 'torch.save', (['checkpoint', 'args.save_dir'], {}), '(checkpoint, args.save_dir)\n', (2594, 2621), False, 'import torch\n')] |
from django.contrib import admin
from .models import Patient,Ipd,Rooms,TreatmentAdviced,TreatmentGiven,Discharge,Procedure,Investigation,DailyRound,Opd
admin.site.register(Opd)# Register your models here.
admin.site.register(Patient)
admin.site.register(Ipd)
admin.site.register(Rooms)
admin.site.register(TreatmentAdviced)
admin.site.register(TreatmentGiven)
admin.site.register(Investigation)
admin.site.register(DailyRound)
admin.site.register(Discharge)
admin.site.register(Procedure)
| [
"django.contrib.admin.site.register"
] | [((153, 177), 'django.contrib.admin.site.register', 'admin.site.register', (['Opd'], {}), '(Opd)\n', (172, 177), False, 'from django.contrib import admin\n'), ((207, 235), 'django.contrib.admin.site.register', 'admin.site.register', (['Patient'], {}), '(Patient)\n', (226, 235), False, 'from django.contrib import admin\n'), ((236, 260), 'django.contrib.admin.site.register', 'admin.site.register', (['Ipd'], {}), '(Ipd)\n', (255, 260), False, 'from django.contrib import admin\n'), ((261, 287), 'django.contrib.admin.site.register', 'admin.site.register', (['Rooms'], {}), '(Rooms)\n', (280, 287), False, 'from django.contrib import admin\n'), ((288, 325), 'django.contrib.admin.site.register', 'admin.site.register', (['TreatmentAdviced'], {}), '(TreatmentAdviced)\n', (307, 325), False, 'from django.contrib import admin\n'), ((326, 361), 'django.contrib.admin.site.register', 'admin.site.register', (['TreatmentGiven'], {}), '(TreatmentGiven)\n', (345, 361), False, 'from django.contrib import admin\n'), ((362, 396), 'django.contrib.admin.site.register', 'admin.site.register', (['Investigation'], {}), '(Investigation)\n', (381, 396), False, 'from django.contrib import admin\n'), ((397, 428), 'django.contrib.admin.site.register', 'admin.site.register', (['DailyRound'], {}), '(DailyRound)\n', (416, 428), False, 'from django.contrib import admin\n'), ((429, 459), 'django.contrib.admin.site.register', 'admin.site.register', (['Discharge'], {}), '(Discharge)\n', (448, 459), False, 'from django.contrib import admin\n'), ((460, 490), 'django.contrib.admin.site.register', 'admin.site.register', (['Procedure'], {}), '(Procedure)\n', (479, 490), False, 'from django.contrib import admin\n')] |
"""
Copyright (c) 2015 <NAME>
license http://opensource.org/licenses/MIT
lib/ui/handlers.py
Handlers for find menu
"""
from functools import partial
import sys
import traceback
import pynance as pn
from ..dbtools import find_job
from ..dbwrapper import job
from ..spreads.dgb_finder import DgbFinder
from ..stockopt import StockOptFactory
from .. import strikes
SEP_LEN = 48
MAX_FAILURES = 4
class DataUnavailable(Exception):
pass
class FindHandlers(object):
def __init__(self, logger):
self.logger = logger
self.opt_factory = StockOptFactory()
def get_dgbs(self):
"""
Scan a list of equities for potential diagonal butterfly spreads.
For the type of equity to examine cf. McMillan, p. 344:
'one would like the underlying stock to be somewhat volatile,
since there is the possibility that long-term options will
be owned for free'.
The selection logic can be found in lib.spreads.diagonal_butterfly.DgbFinder
"""
cursor = job(self.logger, partial(find_job, 'find', {'spread': 'dgb'}))
equities = sorted([item['eq'] for item in cursor])
dgbs = self._find_dgbs(equities)
_show_dgbs(dgbs)
return True
def _find_dgbs(self, equities):
print('scanning {} equities for diagonal butterfly spreads'.format(len(equities)))
dgbs = []
n_failures = 0
for equity in equities:
if n_failures >= MAX_FAILURES and not dgbs:
raise DataUnavailable
print('{}'.format(equity), end='')
msg = '?'
try:
dgbs_foreq = self._find_dgbs_foreq(equity)
dgbs.extend(dgbs_foreq)
msg = len(dgbs_foreq)
except AttributeError:
n_failures += 1
self.logger.exception('error retrieving options data')
except Exception:
n_failures += 1
traceback.print_exc()
self.logger.exception('error retrieving options data')
finally:
print('({}).'.format(msg), end='')
sys.stdout.flush()
return dgbs
def _find_dgbs_foreq(self, equity):
opts = pn.opt.get(equity)
return DgbFinder(opts, self.opt_factory).run()
def _show_dgbs(dgbs):
if len(dgbs) > 0:
print('')
for dgb in dgbs:
print('-' * SEP_LEN)
dgb.show()
print('=' * SEP_LEN)
else:
print('\nNo spreads meeting the requirements were found.')
| [
"sys.stdout.flush",
"traceback.print_exc",
"functools.partial",
"pynance.opt.get"
] | [((2252, 2270), 'pynance.opt.get', 'pn.opt.get', (['equity'], {}), '(equity)\n', (2262, 2270), True, 'import pynance as pn\n'), ((1051, 1095), 'functools.partial', 'partial', (['find_job', '"""find"""', "{'spread': 'dgb'}"], {}), "(find_job, 'find', {'spread': 'dgb'})\n", (1058, 1095), False, 'from functools import partial\n'), ((2157, 2175), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (2173, 2175), False, 'import sys\n'), ((1976, 1997), 'traceback.print_exc', 'traceback.print_exc', ([], {}), '()\n', (1995, 1997), False, 'import traceback\n')] |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
__author__ = 'andyguo'
from functools import wraps
class DayuDatabaseStatusNotConnect(object):
pass
class DayuDatabaseStatusConnected(object):
pass
def validate_status(status):
def outter_wrapper(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
current_status = getattr(self, 'status', None)
if current_status is None:
from dayu_database.error import DayuStatusNotSetError
raise DayuStatusNotSetError('{} status not set or without status'.format(self))
if not isinstance(current_status, status):
from dayu_database.error import DayuStatusInvalidateError
raise DayuStatusInvalidateError('{} not match {}'.format(current_status, status))
return func(self, *args, **kwargs)
return wrapper
return outter_wrapper | [
"functools.wraps"
] | [((280, 291), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (285, 291), False, 'from functools import wraps\n')] |
from dataclasses import dataclass, field
from typing import Optional
from pytest import raises
from apischema import ValidationError, deserialize
from apischema.metadata import required
@dataclass
class Foo:
bar: Optional[int] = field(default=None, metadata=required)
with raises(ValidationError) as err:
deserialize(Foo, {})
assert err.value.errors == [{"loc": ["bar"], "msg": "missing property"}]
| [
"apischema.deserialize",
"pytest.raises",
"dataclasses.field"
] | [((237, 275), 'dataclasses.field', 'field', ([], {'default': 'None', 'metadata': 'required'}), '(default=None, metadata=required)\n', (242, 275), False, 'from dataclasses import dataclass, field\n'), ((283, 306), 'pytest.raises', 'raises', (['ValidationError'], {}), '(ValidationError)\n', (289, 306), False, 'from pytest import raises\n'), ((319, 339), 'apischema.deserialize', 'deserialize', (['Foo', '{}'], {}), '(Foo, {})\n', (330, 339), False, 'from apischema import ValidationError, deserialize\n')] |
from django.test import TestCase
# from django.db.utils import IntegrityError
from core.models import User
class CaseInsensitiveUserNameManagerTest(TestCase):
@classmethod
def setUpTestData(cls):
cls.user1 = User.objects.create_user(username="user1",
password="<PASSWORD>",
email="<EMAIL>")
def test_get_by_natural_key(self):
user = User.objects.get_by_natural_key('user1')
self.assertEqual(user.username, 'user1')
user = User.objects.get_by_natural_key('uSEr1')
self.assertEqual(user.username, 'user1')
def test_create_user_username(self):
with self.assertRaises(ValueError):
User.objects.create_user(username="user1",
password="<PASSWORD>",
email="<EMAIL>")
with self.assertRaises(ValueError):
User.objects.create_user(username="usER1",
password="<PASSWORD>",
email="<EMAIL>")
def test_create_user_email(self):
with self.assertRaises(ValueError):
User.objects.create_user(username="user2",
password="<PASSWORD>",
email="")
with self.assertRaises(ValueError):
User.objects.create_user(username="user2",
password="<PASSWORD>",
email="<EMAIL>")
| [
"core.models.User.objects.create_user",
"core.models.User.objects.get_by_natural_key"
] | [((228, 315), 'core.models.User.objects.create_user', 'User.objects.create_user', ([], {'username': '"""user1"""', 'password': '"""<PASSWORD>"""', 'email': '"""<EMAIL>"""'}), "(username='user1', password='<PASSWORD>', email=\n '<EMAIL>')\n", (252, 315), False, 'from core.models import User\n'), ((456, 496), 'core.models.User.objects.get_by_natural_key', 'User.objects.get_by_natural_key', (['"""user1"""'], {}), "('user1')\n", (487, 496), False, 'from core.models import User\n'), ((561, 601), 'core.models.User.objects.get_by_natural_key', 'User.objects.get_by_natural_key', (['"""uSEr1"""'], {}), "('uSEr1')\n", (592, 601), False, 'from core.models import User\n'), ((749, 836), 'core.models.User.objects.create_user', 'User.objects.create_user', ([], {'username': '"""user1"""', 'password': '"""<PASSWORD>"""', 'email': '"""<EMAIL>"""'}), "(username='user1', password='<PASSWORD>', email=\n '<EMAIL>')\n", (773, 836), False, 'from core.models import User\n'), ((962, 1049), 'core.models.User.objects.create_user', 'User.objects.create_user', ([], {'username': '"""usER1"""', 'password': '"""<PASSWORD>"""', 'email': '"""<EMAIL>"""'}), "(username='usER1', password='<PASSWORD>', email=\n '<EMAIL>')\n", (986, 1049), False, 'from core.models import User\n'), ((1214, 1289), 'core.models.User.objects.create_user', 'User.objects.create_user', ([], {'username': '"""user2"""', 'password': '"""<PASSWORD>"""', 'email': '""""""'}), "(username='user2', password='<PASSWORD>', email='')\n", (1238, 1289), False, 'from core.models import User\n'), ((1420, 1507), 'core.models.User.objects.create_user', 'User.objects.create_user', ([], {'username': '"""user2"""', 'password': '"""<PASSWORD>"""', 'email': '"""<EMAIL>"""'}), "(username='user2', password='<PASSWORD>', email=\n '<EMAIL>')\n", (1444, 1507), False, 'from core.models import User\n')] |
import torch
import torch.nn as nn
from torch.nn import init
from torchvision import models
from torch.autograd import Variable
from resnet import resnet50, resnet18
import torch.nn.functional as F
import math
from attention import IWPA, AVG, MAX, GEM
class Normalize(nn.Module):
def __init__(self, power=2):
super(Normalize, self).__init__()
self.power = power
def forward(self, x):
norm = x.pow(self.power).sum(1, keepdim=True).pow(1. / self.power)
out = x.div(norm)
return out
# #####################################################################
def weights_init_kaiming(m):
classname = m.__class__.__name__
# print(classname)
if classname.find('Conv') != -1:
init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')
elif classname.find('Linear') != -1:
init.kaiming_normal_(m.weight.data, a=0, mode='fan_out')
init.zeros_(m.bias.data)
elif classname.find('BatchNorm1d') != -1:
init.normal_(m.weight.data, 1.0, 0.01)
init.zeros_(m.bias.data)
def weights_init_classifier(m):
classname = m.__class__.__name__
if classname.find('Linear') != -1:
init.normal_(m.weight.data, 0, 0.001)
if m.bias:
init.zeros_(m.bias.data)
# Defines the new fc layer and classification layer
# |--Linear--|--bn--|--relu--|--Linear--|
class FeatureBlock(nn.Module):
def __init__(self, input_dim, low_dim, dropout=0.5, relu=True):
super(FeatureBlock, self).__init__()
feat_block = []
feat_block += [nn.Linear(input_dim, low_dim)]
feat_block += [nn.BatchNorm1d(low_dim)]
feat_block = nn.Sequential(*feat_block)
feat_block.apply(weights_init_kaiming)
self.feat_block = feat_block
def forward(self, x):
x = self.feat_block(x)
return x
class ClassBlock(nn.Module):
def __init__(self, input_dim, class_num, dropout=0.5, relu=True):
super(ClassBlock, self).__init__()
classifier = []
if relu:
classifier += [nn.LeakyReLU(0.1)]
if dropout:
classifier += [nn.Dropout(p=dropout)]
classifier += [nn.Linear(input_dim, class_num)]
classifier = nn.Sequential(*classifier)
classifier.apply(weights_init_classifier)
self.classifier = classifier
def forward(self, x):
x = self.classifier(x)
return x
class visible_module(nn.Module):
def __init__(self, arch='resnet50'):
super(visible_module, self).__init__()
model_v = resnet50(pretrained=True,
last_conv_stride=1, last_conv_dilation=1)
# avg pooling to global pooling
self.visible = model_v
def forward(self, x):
x = self.visible.conv1(x)
x = self.visible.bn1(x)
x = self.visible.relu(x)
x = self.visible.maxpool(x)
x = self.visible.layer1(x)
return x
class thermal_module(nn.Module):
def __init__(self, arch='resnet50'):
super(thermal_module, self).__init__()
model_t = resnet50(pretrained=True,
last_conv_stride=1, last_conv_dilation=1)
# avg pooling to global pooling
self.thermal = model_t
def forward(self, x):
x = self.thermal.conv1(x)
x = self.thermal.bn1(x)
x = self.thermal.relu(x)
x = self.thermal.maxpool(x)
x = self.thermal.layer1(x)
return x
class base_resnet(nn.Module):
def __init__(self, arch='resnet50'):
super(base_resnet, self).__init__()
model_base = resnet50(pretrained=True,
last_conv_stride=1, last_conv_dilation=1)
# avg pooling to global pooling
model_base.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.base = model_base
def forward(self, x):
#x = self.base.layer1(x)
x = self.base.layer2(x)
x = self.base.layer3(x)
x = self.base.layer4(x)
return x
class embed_net(nn.Module):
def __init__(self, class_num, drop=0.2, part = 3, arch='resnet50', cpool = 'no', bpool = 'avg', fuse = 'sum'):
super(embed_net, self).__init__()
self.thermal_module = thermal_module(arch=arch)
self.visible_module = visible_module(arch=arch)
self.base_resnet = base_resnet(arch=arch)
pool_dim = 2048
pool_dim_att = 2048 if fuse == "sum" else 4096
self.dropout = drop
self.part = part
self.cpool = cpool
self.bpool = bpool
self.fuse = fuse
self.l2norm = Normalize(2)
self.bottleneck = nn.BatchNorm1d(pool_dim)
self.bottleneck.bias.requires_grad_(False) # no shift
self.classifier = nn.Linear(pool_dim, class_num, bias=False)
self.bottleneck.apply(weights_init_kaiming)
self.classifier.apply(weights_init_classifier)
if self.cpool == 'wpa':
self.classifier_att = nn.Linear(pool_dim_att, class_num, bias=False)
self.classifier_att.apply(weights_init_classifier)
self.cpool_layer = IWPA(pool_dim, part,fuse)
if self.cpool == 'avg':
self.classifier_att = nn.Linear(pool_dim_att, class_num, bias=False)
self.classifier_att.apply(weights_init_classifier)
self.cpool_layer = AVG(pool_dim,fuse)
if self.cpool == 'max':
self.classifier_att = nn.Linear(pool_dim_att, class_num, bias=False)
self.classifier_att.apply(weights_init_classifier)
self.cpool_layer = MAX(pool_dim,fuse)
if self.cpool == 'gem':
self.classifier_att = nn.Linear(pool_dim_att, class_num, bias=False)
self.classifier_att.apply(weights_init_classifier)
self.cpool_layer = GEM(pool_dim,fuse)
def forward(self, x1, x2, modal=0):
# domain specific block
if modal == 0:
x1 = self.visible_module(x1)
x2 = self.thermal_module(x2)
x = torch.cat((x1, x2), 0)
elif modal == 1:
x = self.visible_module(x1)
elif modal == 2:
x = self.thermal_module(x2)
# shared four blocks
x = self.base_resnet(x)
if self.bpool == 'gem':
b, c, _, _ = x.shape
x_pool = x.view(b, c, -1)
p = 3.0
x_pool = (torch.mean(x_pool**p, dim=-1) + 1e-12)**(1/p)
elif self.bpool == 'avg':
x_pool = F.adaptive_avg_pool2d(x,1)
x_pool = x_pool.view(x_pool.size(0), x_pool.size(1))
elif self.bpool == 'max':
x_pool = F.adaptive_max_pool2d(x,1)
x_pool = x_pool.view(x_pool.size(0), x_pool.size(1))
else:
print("wrong backbone pooling!!!")
exit()
feat = self.bottleneck(x_pool)
if self.cpool != 'no':
# intra-modality weighted part attention
if self.cpool == 'wpa':
feat_att, feat_att_bn = self.cpool_layer(x, feat, 1, self.part)
if self.cpool in ['avg', 'max', 'gem']:
feat_att, feat_att_bn = self.cpool_layer(x, feat)
if self.training:
return x_pool, self.classifier(feat), feat_att_bn, self.classifier_att(feat_att_bn)
else:
return self.l2norm(feat), self.l2norm(feat_att_bn)
else:
if self.training:
return x_pool, self.classifier(feat)
else:
return self.l2norm(feat) | [
"attention.AVG",
"torch.nn.Dropout",
"torch.nn.functional.adaptive_avg_pool2d",
"attention.IWPA",
"torch.nn.LeakyReLU",
"torch.nn.Sequential",
"torch.mean",
"torch.nn.init.kaiming_normal_",
"torch.nn.init.zeros_",
"torch.nn.functional.adaptive_max_pool2d",
"resnet.resnet50",
"torch.nn.BatchNor... | [((739, 794), 'torch.nn.init.kaiming_normal_', 'init.kaiming_normal_', (['m.weight.data'], {'a': '(0)', 'mode': '"""fan_in"""'}), "(m.weight.data, a=0, mode='fan_in')\n", (759, 794), False, 'from torch.nn import init\n'), ((1178, 1215), 'torch.nn.init.normal_', 'init.normal_', (['m.weight.data', '(0)', '(0.001)'], {}), '(m.weight.data, 0, 0.001)\n', (1190, 1215), False, 'from torch.nn import init\n'), ((1659, 1685), 'torch.nn.Sequential', 'nn.Sequential', (['*feat_block'], {}), '(*feat_block)\n', (1672, 1685), True, 'import torch.nn as nn\n'), ((2224, 2250), 'torch.nn.Sequential', 'nn.Sequential', (['*classifier'], {}), '(*classifier)\n', (2237, 2250), True, 'import torch.nn as nn\n'), ((2555, 2622), 'resnet.resnet50', 'resnet50', ([], {'pretrained': '(True)', 'last_conv_stride': '(1)', 'last_conv_dilation': '(1)'}), '(pretrained=True, last_conv_stride=1, last_conv_dilation=1)\n', (2563, 2622), False, 'from resnet import resnet50, resnet18\n'), ((3077, 3144), 'resnet.resnet50', 'resnet50', ([], {'pretrained': '(True)', 'last_conv_stride': '(1)', 'last_conv_dilation': '(1)'}), '(pretrained=True, last_conv_stride=1, last_conv_dilation=1)\n', (3085, 3144), False, 'from resnet import resnet50, resnet18\n'), ((3596, 3663), 'resnet.resnet50', 'resnet50', ([], {'pretrained': '(True)', 'last_conv_stride': '(1)', 'last_conv_dilation': '(1)'}), '(pretrained=True, last_conv_stride=1, last_conv_dilation=1)\n', (3604, 3663), False, 'from resnet import resnet50, resnet18\n'), ((3763, 3791), 'torch.nn.AdaptiveAvgPool2d', 'nn.AdaptiveAvgPool2d', (['(1, 1)'], {}), '((1, 1))\n', (3783, 3791), True, 'import torch.nn as nn\n'), ((4619, 4643), 'torch.nn.BatchNorm1d', 'nn.BatchNorm1d', (['pool_dim'], {}), '(pool_dim)\n', (4633, 4643), True, 'import torch.nn as nn\n'), ((4734, 4776), 'torch.nn.Linear', 'nn.Linear', (['pool_dim', 'class_num'], {'bias': '(False)'}), '(pool_dim, class_num, bias=False)\n', (4743, 4776), True, 'import torch.nn as nn\n'), ((844, 900), 'torch.nn.init.kaiming_normal_', 'init.kaiming_normal_', (['m.weight.data'], {'a': '(0)', 'mode': '"""fan_out"""'}), "(m.weight.data, a=0, mode='fan_out')\n", (864, 900), False, 'from torch.nn import init\n'), ((909, 933), 'torch.nn.init.zeros_', 'init.zeros_', (['m.bias.data'], {}), '(m.bias.data)\n', (920, 933), False, 'from torch.nn import init\n'), ((1247, 1271), 'torch.nn.init.zeros_', 'init.zeros_', (['m.bias.data'], {}), '(m.bias.data)\n', (1258, 1271), False, 'from torch.nn import init\n'), ((1558, 1587), 'torch.nn.Linear', 'nn.Linear', (['input_dim', 'low_dim'], {}), '(input_dim, low_dim)\n', (1567, 1587), True, 'import torch.nn as nn\n'), ((1612, 1635), 'torch.nn.BatchNorm1d', 'nn.BatchNorm1d', (['low_dim'], {}), '(low_dim)\n', (1626, 1635), True, 'import torch.nn as nn\n'), ((2170, 2201), 'torch.nn.Linear', 'nn.Linear', (['input_dim', 'class_num'], {}), '(input_dim, class_num)\n', (2179, 2201), True, 'import torch.nn as nn\n'), ((4952, 4998), 'torch.nn.Linear', 'nn.Linear', (['pool_dim_att', 'class_num'], {'bias': '(False)'}), '(pool_dim_att, class_num, bias=False)\n', (4961, 4998), True, 'import torch.nn as nn\n'), ((5097, 5123), 'attention.IWPA', 'IWPA', (['pool_dim', 'part', 'fuse'], {}), '(pool_dim, part, fuse)\n', (5101, 5123), False, 'from attention import IWPA, AVG, MAX, GEM\n'), ((5189, 5235), 'torch.nn.Linear', 'nn.Linear', (['pool_dim_att', 'class_num'], {'bias': '(False)'}), '(pool_dim_att, class_num, bias=False)\n', (5198, 5235), True, 'import torch.nn as nn\n'), ((5334, 5353), 'attention.AVG', 'AVG', (['pool_dim', 'fuse'], {}), '(pool_dim, fuse)\n', (5337, 5353), False, 'from attention import IWPA, AVG, MAX, GEM\n'), ((5419, 5465), 'torch.nn.Linear', 'nn.Linear', (['pool_dim_att', 'class_num'], {'bias': '(False)'}), '(pool_dim_att, class_num, bias=False)\n', (5428, 5465), True, 'import torch.nn as nn\n'), ((5564, 5583), 'attention.MAX', 'MAX', (['pool_dim', 'fuse'], {}), '(pool_dim, fuse)\n', (5567, 5583), False, 'from attention import IWPA, AVG, MAX, GEM\n'), ((5649, 5695), 'torch.nn.Linear', 'nn.Linear', (['pool_dim_att', 'class_num'], {'bias': '(False)'}), '(pool_dim_att, class_num, bias=False)\n', (5658, 5695), True, 'import torch.nn as nn\n'), ((5794, 5813), 'attention.GEM', 'GEM', (['pool_dim', 'fuse'], {}), '(pool_dim, fuse)\n', (5797, 5813), False, 'from attention import IWPA, AVG, MAX, GEM\n'), ((6009, 6031), 'torch.cat', 'torch.cat', (['(x1, x2)', '(0)'], {}), '((x1, x2), 0)\n', (6018, 6031), False, 'import torch\n'), ((988, 1026), 'torch.nn.init.normal_', 'init.normal_', (['m.weight.data', '(1.0)', '(0.01)'], {}), '(m.weight.data, 1.0, 0.01)\n', (1000, 1026), False, 'from torch.nn import init\n'), ((1035, 1059), 'torch.nn.init.zeros_', 'init.zeros_', (['m.bias.data'], {}), '(m.bias.data)\n', (1046, 1059), False, 'from torch.nn import init\n'), ((2057, 2074), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', (['(0.1)'], {}), '(0.1)\n', (2069, 2074), True, 'import torch.nn as nn\n'), ((2123, 2144), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': 'dropout'}), '(p=dropout)\n', (2133, 2144), True, 'import torch.nn as nn\n'), ((6475, 6502), 'torch.nn.functional.adaptive_avg_pool2d', 'F.adaptive_avg_pool2d', (['x', '(1)'], {}), '(x, 1)\n', (6496, 6502), True, 'import torch.nn.functional as F\n'), ((6374, 6405), 'torch.mean', 'torch.mean', (['(x_pool ** p)'], {'dim': '(-1)'}), '(x_pool ** p, dim=-1)\n', (6384, 6405), False, 'import torch\n'), ((6622, 6649), 'torch.nn.functional.adaptive_max_pool2d', 'F.adaptive_max_pool2d', (['x', '(1)'], {}), '(x, 1)\n', (6643, 6649), True, 'import torch.nn.functional as F\n')] |
import os
import numpy as np
from ._population import Population
from pychemia import pcm_log
from pychemia.utils.mathematics import spherical_to_cartesian, cartesian_to_spherical, rotate_towards_axis, \
angle_between_vectors
from pychemia.code.vasp import read_incar, read_poscar, VaspJob, VaspOutput
from pychemia.crystal import KPoints
class NonCollinearMagMoms(Population):
def __init__(self, name, source_dir='.', mag_atoms=None, magmom_magnitude=2.0, distance_tolerance=0.1):
Population.__init__(self, name, 'global')
if not os.path.isfile(source_dir + os.sep + 'INCAR'):
raise ValueError("INCAR not found")
if not os.path.isfile(source_dir + os.sep + 'POSCAR'):
raise ValueError("POSCAR not found")
self.input = read_incar(source_dir + os.sep + 'INCAR')
magmom = np.array(self.input.get_value('MAGMOM')).reshape((-1, 3))
self.structure = read_poscar(source_dir + os.sep + 'POSCAR')
if mag_atoms is None:
self.mag_atoms = list(np.where(np.apply_along_axis(np.linalg.norm, 1, magmom) > 0.0)[0])
self.mag_atoms = [int(x) for x in self.mag_atoms]
else:
self.mag_atoms = mag_atoms
self.magmom_magnitude = magmom_magnitude
self.distance_tolerance = distance_tolerance
def __str__(self):
ret = ' Population NonColl\n\n'
ret += ' Name: %s\n' % self.name
ret += ' Tag: %s\n' % self.tag
ret += ' Formula: %s\n' % self.structure.formula
ret += ' Members: %d\n' % len(self.members)
ret += ' Actives: %d\n' % len(self.actives)
ret += ' Evaluated: %d\n' % len(self.evaluated)
return ret
@property
def to_dict(self):
return {'name': self.name,
'tag': self.tag,
'mag_atoms': self.mag_atoms,
'magmom_magnitude': self.magmom_magnitude,
'distance_tolerance': self.distance_tolerance}
@staticmethod
def from_dict(self, population_dict):
return NonCollinearMagMoms(name=population_dict['name'],
mag_atoms=population_dict['mag_atoms'],
magmom_magnitude=population_dict['magmom_magnitude'],
distance_tolerance=population_dict['distance_tolerance'])
def new_entry(self, data, active=True):
data = np.array(data)
# Magnetic moments are stored in spherical coordinates
properties = {'magmom': list(data.flatten())}
status = {self.tag: active}
entry={'structure': self.structure.to_dict, 'properties': properties, 'status': status}
entry_id = self.insert_entry(entry)
pcm_log.debug('Added new entry: %s with tag=%s: %s' % (str(entry_id), self.tag, str(active)))
return entry_id
def is_evaluated(self, entry_id):
entry = self.get_entry(entry_id, {'_id': 0, 'properties': 1})
if 'energy' in entry['properties']:
return True
else:
return False
def check_duplicates(self, ids):
selection = self.ids_sorted(ids)
ret = {}
for i in range(len(ids) - 1):
for j in range(i, len(ids)):
if self.distance(selection[i], selection[j]) < self.distance_tolerance:
ret[selection[j]] = selection[i]
return ret
def distance(self, entry_id, entry_jd):
entry = self.get_entry(entry_id, {'properties.magmom': 1})
magmom_i = spherical_to_cartesian(entry['properties']['magmom'])
entry = self.get_entry(entry_id, {'properties.magmom': 1})
magmom_j = spherical_to_cartesian(entry['properties']['magmom'])
magmom_ixyz = spherical_to_cartesian(magmom_i)
magmom_jxyz = spherical_to_cartesian(magmom_j)
distance = np.sum(angle_between_vectors(magmom_ixyz, magmom_jxyz))
distance /= len(self.mag_atoms)
return distance
def move_random(self, entry_id, factor=0.2, in_place=False, kind='move'):
entry = self.get_entry(entry_id, {'properties.magmom': 1})
# Magnetic Momenta are stored in spherical coordinates
magmom_i = spherical_to_cartesian(entry['properties']['magmom'])
# Converted into cartesians
magmom_xyz = spherical_to_cartesian(magmom_i)
# Randomly disturbed using the factor
magmom_xyz += factor * np.random.rand((self.structure.natom, 3)) - factor / 2
# Reconverting to spherical coordinates
magmom_new = cartesian_to_spherical(magmom_xyz)
# Resetting magnitudes
magmom_new[:, 0] = self.magmom_magnitude
properties = {'magmom': magmom_new}
if in_place:
return self.update_properties(entry_id, new_properties=properties)
else:
return self.new_entry(magmom_new, active=False)
def move(self, entry_id, entry_jd, factor=0.2, in_place=False):
magmom_new_xyz = np.zeros((self.structure.natom, 3))
entry = self.get_entry(entry_id, {'properties.magmom': 1})
magmom_i = np.array(entry['properties']['magmom']).reshape((-1, 3))
magmom_ixyz = spherical_to_cartesian(magmom_i)
entry = self.get_entry(entry_id, {'properties.magmom': 1})
magmom_j = np.array(entry['properties']['magmom']).reshape((-1, 3))
magmom_jxyz = spherical_to_cartesian(magmom_j)
for i in range(self.structure.natom):
if magmom_ixyz[i][0] > 0 and magmom_jxyz[i][0] > 0:
magmom_new_xyz[i] = rotate_towards_axis(magmom_ixyz[i], magmom_jxyz[i],
fraction=factor)
magmom_new = cartesian_to_spherical(magmom_new_xyz)
magmom_new[:, 0] = self.magmom_magnitude
properties = {'magmom': magmom_new}
if in_place:
return self.update_properties(entry_id, new_properties=properties)
else:
return self.new_entry(magmom_new, active=False)
def value(self, entry_id):
entry = self.get_entry(entry_id, {'properties.energy': 1})
if 'energy' in entry['properties']:
return entry['properties']['energy']
else:
return None
def str_entry(self, entry_id):
entry = self.get_entry(entry_id, {'properties.magmom': 1})
print(np.array(entry['properties']['magmom']).reshape((-1, 3)))
def get_duplicates(self, ids):
return None
def add_random(self):
"""
:return:
"""
n = self.structure.natom
a = self.magmom_magnitude * np.ones(n)
b = 2 * np.pi * np.random.rand(n)
c = np.pi * np.random.rand(n)
print(a.shape)
print(b.shape)
print(c.shape)
magmom = np.vstack((a, b, c)).T
for i in range(self.structure.natom):
if i not in self.mag_atoms:
magmom[i, :] = 0.0
return self.new_entry(magmom), None
def recover(self):
data = self.get_population_info()
if data is not None:
self.mag_atoms = data['mag_atoms']
self.distance_tolerance = data['distance_tolerance']
self.name = data['name']
self.magmom_magnitude = data['magmom_magnitude']
def cross(self, ids):
entry_id = ids[0]
entry_jd = ids[1]
entry = self.get_entry(entry_id, {'properties.magmom': 1})
magmom_i = np.array(entry['properties']['magmom']).reshape((-1, 3))
entry = self.get_entry(entry_jd, {'properties.magmom': 1})
magmom_j = np.array(entry['properties']['magmom']).reshape((-1, 3))
magmom_inew = np.zeros((self.structure.natom, 3))
magmom_jnew = np.zeros((self.structure.natom, 3))
for i in range(self.structure.natom):
rnd = np.random.rand()
if rnd < 0.5:
magmom_inew[i] = magmom_j[i]
magmom_jnew[i] = magmom_i[i]
else:
magmom_inew[i] = magmom_i[i]
magmom_jnew[i] = magmom_j[i]
entry_id = self.new_entry(magmom_inew, active=True)
entry_jd = self.new_entry(magmom_jnew, active=True)
return entry_id, entry_jd
def prepare_folder(self, entry_id, workdir, binary='vasp', source_dir='.'):
vj = VaspJob()
structure = self.get_structure(entry_id)
kp = KPoints.optimized_grid(structure.lattice, kp_density=2E4)
vj.initialize(structure, workdir=workdir, kpoints=kp, binary=binary)
vj.clean()
vj.input_variables = read_incar(source_dir + '/INCAR')
magmom_sph = self.get_entry(entry_id, {'properties.magmom': 1})['properties']['magmom']
magmom_car = spherical_to_cartesian(magmom_sph)
vj.input_variables.variables['MAGMOM'] = [float(x) for x in magmom_car.flatten()]
vj.input_variables.variables['M_CONSTR'] = [float(x) for x in magmom_car.flatten()]
vj.input_variables.variables['IBRION'] = -1
vj.input_variables.variables['LWAVE'] = True
vj.input_variables.variables['EDIFF'] = 1E-5
vj.input_variables.variables['LAMBDA'] = 10
vj.input_variables.variables['NSW'] = 0
vj.input_variables.variables['I_CONSTRAINED_M'] = 1
vj.set_inputs()
def collect_data(self, entry_id, workdir):
if os.path.isfile(workdir + '/OUTCAR'):
vo = VaspOutput(workdir + '/OUTCAR')
if 'energy' in vo.final_data:
if 'free_energy' in vo.final_data['energy']:
energy = vo.final_data['energy']['free_energy']
print('Uploading energy data for %s' % entry_id)
self.set_in_properties(entry_id, 'energy', energy)
return True
else:
return False
else:
return False
else:
return False
| [
"pychemia.code.vasp.VaspJob",
"numpy.ones",
"pychemia.code.vasp.read_poscar",
"pychemia.utils.mathematics.angle_between_vectors",
"pychemia.code.vasp.read_incar",
"pychemia.utils.mathematics.spherical_to_cartesian",
"pychemia.crystal.KPoints.optimized_grid",
"numpy.random.rand",
"os.path.isfile",
... | [((785, 826), 'pychemia.code.vasp.read_incar', 'read_incar', (["(source_dir + os.sep + 'INCAR')"], {}), "(source_dir + os.sep + 'INCAR')\n", (795, 826), False, 'from pychemia.code.vasp import read_incar, read_poscar, VaspJob, VaspOutput\n'), ((928, 971), 'pychemia.code.vasp.read_poscar', 'read_poscar', (["(source_dir + os.sep + 'POSCAR')"], {}), "(source_dir + os.sep + 'POSCAR')\n", (939, 971), False, 'from pychemia.code.vasp import read_incar, read_poscar, VaspJob, VaspOutput\n'), ((2482, 2496), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (2490, 2496), True, 'import numpy as np\n'), ((3598, 3651), 'pychemia.utils.mathematics.spherical_to_cartesian', 'spherical_to_cartesian', (["entry['properties']['magmom']"], {}), "(entry['properties']['magmom'])\n", (3620, 3651), False, 'from pychemia.utils.mathematics import spherical_to_cartesian, cartesian_to_spherical, rotate_towards_axis, angle_between_vectors\n'), ((3738, 3791), 'pychemia.utils.mathematics.spherical_to_cartesian', 'spherical_to_cartesian', (["entry['properties']['magmom']"], {}), "(entry['properties']['magmom'])\n", (3760, 3791), False, 'from pychemia.utils.mathematics import spherical_to_cartesian, cartesian_to_spherical, rotate_towards_axis, angle_between_vectors\n'), ((3814, 3846), 'pychemia.utils.mathematics.spherical_to_cartesian', 'spherical_to_cartesian', (['magmom_i'], {}), '(magmom_i)\n', (3836, 3846), False, 'from pychemia.utils.mathematics import spherical_to_cartesian, cartesian_to_spherical, rotate_towards_axis, angle_between_vectors\n'), ((3869, 3901), 'pychemia.utils.mathematics.spherical_to_cartesian', 'spherical_to_cartesian', (['magmom_j'], {}), '(magmom_j)\n', (3891, 3901), False, 'from pychemia.utils.mathematics import spherical_to_cartesian, cartesian_to_spherical, rotate_towards_axis, angle_between_vectors\n'), ((4270, 4323), 'pychemia.utils.mathematics.spherical_to_cartesian', 'spherical_to_cartesian', (["entry['properties']['magmom']"], {}), "(entry['properties']['magmom'])\n", (4292, 4323), False, 'from pychemia.utils.mathematics import spherical_to_cartesian, cartesian_to_spherical, rotate_towards_axis, angle_between_vectors\n'), ((4381, 4413), 'pychemia.utils.mathematics.spherical_to_cartesian', 'spherical_to_cartesian', (['magmom_i'], {}), '(magmom_i)\n', (4403, 4413), False, 'from pychemia.utils.mathematics import spherical_to_cartesian, cartesian_to_spherical, rotate_towards_axis, angle_between_vectors\n'), ((4615, 4649), 'pychemia.utils.mathematics.cartesian_to_spherical', 'cartesian_to_spherical', (['magmom_xyz'], {}), '(magmom_xyz)\n', (4637, 4649), False, 'from pychemia.utils.mathematics import spherical_to_cartesian, cartesian_to_spherical, rotate_towards_axis, angle_between_vectors\n'), ((5043, 5078), 'numpy.zeros', 'np.zeros', (['(self.structure.natom, 3)'], {}), '((self.structure.natom, 3))\n', (5051, 5078), True, 'import numpy as np\n'), ((5244, 5276), 'pychemia.utils.mathematics.spherical_to_cartesian', 'spherical_to_cartesian', (['magmom_i'], {}), '(magmom_i)\n', (5266, 5276), False, 'from pychemia.utils.mathematics import spherical_to_cartesian, cartesian_to_spherical, rotate_towards_axis, angle_between_vectors\n'), ((5442, 5474), 'pychemia.utils.mathematics.spherical_to_cartesian', 'spherical_to_cartesian', (['magmom_j'], {}), '(magmom_j)\n', (5464, 5474), False, 'from pychemia.utils.mathematics import spherical_to_cartesian, cartesian_to_spherical, rotate_towards_axis, angle_between_vectors\n'), ((5796, 5834), 'pychemia.utils.mathematics.cartesian_to_spherical', 'cartesian_to_spherical', (['magmom_new_xyz'], {}), '(magmom_new_xyz)\n', (5818, 5834), False, 'from pychemia.utils.mathematics import spherical_to_cartesian, cartesian_to_spherical, rotate_towards_axis, angle_between_vectors\n'), ((7760, 7795), 'numpy.zeros', 'np.zeros', (['(self.structure.natom, 3)'], {}), '((self.structure.natom, 3))\n', (7768, 7795), True, 'import numpy as np\n'), ((7818, 7853), 'numpy.zeros', 'np.zeros', (['(self.structure.natom, 3)'], {}), '((self.structure.natom, 3))\n', (7826, 7853), True, 'import numpy as np\n'), ((8409, 8418), 'pychemia.code.vasp.VaspJob', 'VaspJob', ([], {}), '()\n', (8416, 8418), False, 'from pychemia.code.vasp import read_incar, read_poscar, VaspJob, VaspOutput\n'), ((8481, 8542), 'pychemia.crystal.KPoints.optimized_grid', 'KPoints.optimized_grid', (['structure.lattice'], {'kp_density': '(20000.0)'}), '(structure.lattice, kp_density=20000.0)\n', (8503, 8542), False, 'from pychemia.crystal import KPoints\n'), ((8664, 8697), 'pychemia.code.vasp.read_incar', 'read_incar', (["(source_dir + '/INCAR')"], {}), "(source_dir + '/INCAR')\n", (8674, 8697), False, 'from pychemia.code.vasp import read_incar, read_poscar, VaspJob, VaspOutput\n'), ((8815, 8849), 'pychemia.utils.mathematics.spherical_to_cartesian', 'spherical_to_cartesian', (['magmom_sph'], {}), '(magmom_sph)\n', (8837, 8849), False, 'from pychemia.utils.mathematics import spherical_to_cartesian, cartesian_to_spherical, rotate_towards_axis, angle_between_vectors\n'), ((9433, 9468), 'os.path.isfile', 'os.path.isfile', (["(workdir + '/OUTCAR')"], {}), "(workdir + '/OUTCAR')\n", (9447, 9468), False, 'import os\n'), ((557, 602), 'os.path.isfile', 'os.path.isfile', (["(source_dir + os.sep + 'INCAR')"], {}), "(source_dir + os.sep + 'INCAR')\n", (571, 602), False, 'import os\n'), ((667, 713), 'os.path.isfile', 'os.path.isfile', (["(source_dir + os.sep + 'POSCAR')"], {}), "(source_dir + os.sep + 'POSCAR')\n", (681, 713), False, 'import os\n'), ((3928, 3975), 'pychemia.utils.mathematics.angle_between_vectors', 'angle_between_vectors', (['magmom_ixyz', 'magmom_jxyz'], {}), '(magmom_ixyz, magmom_jxyz)\n', (3949, 3975), False, 'from pychemia.utils.mathematics import spherical_to_cartesian, cartesian_to_spherical, rotate_towards_axis, angle_between_vectors\n'), ((6702, 6712), 'numpy.ones', 'np.ones', (['n'], {}), '(n)\n', (6709, 6712), True, 'import numpy as np\n'), ((6737, 6754), 'numpy.random.rand', 'np.random.rand', (['n'], {}), '(n)\n', (6751, 6754), True, 'import numpy as np\n'), ((6775, 6792), 'numpy.random.rand', 'np.random.rand', (['n'], {}), '(n)\n', (6789, 6792), True, 'import numpy as np\n'), ((6879, 6899), 'numpy.vstack', 'np.vstack', (['(a, b, c)'], {}), '((a, b, c))\n', (6888, 6899), True, 'import numpy as np\n'), ((7918, 7934), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (7932, 7934), True, 'import numpy as np\n'), ((9487, 9518), 'pychemia.code.vasp.VaspOutput', 'VaspOutput', (["(workdir + '/OUTCAR')"], {}), "(workdir + '/OUTCAR')\n", (9497, 9518), False, 'from pychemia.code.vasp import read_incar, read_poscar, VaspJob, VaspOutput\n'), ((4491, 4532), 'numpy.random.rand', 'np.random.rand', (['(self.structure.natom, 3)'], {}), '((self.structure.natom, 3))\n', (4505, 4532), True, 'import numpy as np\n'), ((5165, 5204), 'numpy.array', 'np.array', (["entry['properties']['magmom']"], {}), "(entry['properties']['magmom'])\n", (5173, 5204), True, 'import numpy as np\n'), ((5363, 5402), 'numpy.array', 'np.array', (["entry['properties']['magmom']"], {}), "(entry['properties']['magmom'])\n", (5371, 5402), True, 'import numpy as np\n'), ((5622, 5690), 'pychemia.utils.mathematics.rotate_towards_axis', 'rotate_towards_axis', (['magmom_ixyz[i]', 'magmom_jxyz[i]'], {'fraction': 'factor'}), '(magmom_ixyz[i], magmom_jxyz[i], fraction=factor)\n', (5641, 5690), False, 'from pychemia.utils.mathematics import spherical_to_cartesian, cartesian_to_spherical, rotate_towards_axis, angle_between_vectors\n'), ((7538, 7577), 'numpy.array', 'np.array', (["entry['properties']['magmom']"], {}), "(entry['properties']['magmom'])\n", (7546, 7577), True, 'import numpy as np\n'), ((7681, 7720), 'numpy.array', 'np.array', (["entry['properties']['magmom']"], {}), "(entry['properties']['magmom'])\n", (7689, 7720), True, 'import numpy as np\n'), ((6450, 6489), 'numpy.array', 'np.array', (["entry['properties']['magmom']"], {}), "(entry['properties']['magmom'])\n", (6458, 6489), True, 'import numpy as np\n'), ((1045, 1091), 'numpy.apply_along_axis', 'np.apply_along_axis', (['np.linalg.norm', '(1)', 'magmom'], {}), '(np.linalg.norm, 1, magmom)\n', (1064, 1091), True, 'import numpy as np\n')] |
# Generated by Django 2.2.7 on 2020-02-02 19:42
import datetime
from django.db import migrations, models
import django.db.models.deletion
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('Ecommerce', '0009_review_date'),
]
operations = [
migrations.AlterField(
model_name='review',
name='Date',
field=models.DateTimeField(default=datetime.datetime(2020, 2, 2, 19, 42, 47, 841789, tzinfo=utc)),
),
migrations.CreateModel(
name='Cart',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='Ecommerce.Product')),
],
),
]
| [
"datetime.datetime",
"django.db.models.AutoField",
"django.db.models.ForeignKey"
] | [((445, 506), 'datetime.datetime', 'datetime.datetime', (['(2020)', '(2)', '(2)', '(19)', '(42)', '(47)', '(841789)'], {'tzinfo': 'utc'}), '(2020, 2, 2, 19, 42, 47, 841789, tzinfo=utc)\n', (462, 506), False, 'import datetime\n'), ((621, 714), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (637, 714), False, 'from django.db import migrations, models\n'), ((738, 829), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""Ecommerce.Product"""'}), "(on_delete=django.db.models.deletion.CASCADE, to=\n 'Ecommerce.Product')\n", (755, 829), False, 'from django.db import migrations, models\n')] |
# -*- coding: utf-8 -*-
"""Generator reserve plots.
This module creates plots of reserve provision and shortage at the generation
and region level.
@author: <NAME>
"""
import logging
import numpy as np
import pandas as pd
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.patches import Patch
from matplotlib.lines import Line2D
import marmot.config.mconfig as mconfig
import marmot.plottingmodules.plotutils.plot_library as plotlib
from marmot.plottingmodules.plotutils.plot_data_helper import PlotDataHelper
from marmot.plottingmodules.plotutils.plot_exceptions import (MissingInputData, MissingZoneData)
class MPlot(PlotDataHelper):
"""reserves MPlot class.
All the plotting modules use this same class name.
This class contains plotting methods that are grouped based on the
current module name.
The reserves.py module contains methods that are
related to reserve provision and shortage.
MPlot inherits from the PlotDataHelper class to assist in creating figures.
"""
def __init__(self, argument_dict: dict):
"""
Args:
argument_dict (dict): Dictionary containing all
arguments passed from MarmotPlot.
"""
# iterate over items in argument_dict and set as properties of class
# see key_list in Marmot_plot_main for list of properties
for prop in argument_dict:
self.__setattr__(prop, argument_dict[prop])
# Instantiation of MPlotHelperFunctions
super().__init__(self.Marmot_Solutions_folder, self.AGG_BY, self.ordered_gen,
self.PLEXOS_color_dict, self.Scenarios, self.ylabels,
self.xlabels, self.gen_names_dict, Region_Mapping=self.Region_Mapping)
self.logger = logging.getLogger('marmot_plot.'+__name__)
self.y_axes_decimalpt = mconfig.parser("axes_options","y_axes_decimalpt")
def reserve_gen_timeseries(self, figure_name: str = None, prop: str = None,
start: float = None, end: float= None,
timezone: str = "", start_date_range: str = None,
end_date_range: str = None, **_):
"""Creates a generation timeseries stackplot of total cumulative reserve provision by tech type.
The code will create either a facet plot or a single plot depending on
if the Facet argument is active.
If a facet plot is created, each scenario is plotted on a separate facet,
otherwise all scenarios are plotted on a single plot.
To make a facet plot, ensure the work 'Facet' is found in the figure_name.
Generation order is determined by the ordered_gen_categories.csv.
Args:
figure_name (str, optional): User defined figure output name. Used here
to determine if a Facet plot should be created.
Defaults to None.
prop (str, optional): Special argument used to adjust specific
plot settings. Controlled through the plot_select.csv.
Opinions available are:
- Peak Demand
- Date Range
Defaults to None.
start (float, optional): Used in conjunction with the prop argument.
Will define the number of days to plot before a certain event in
a timeseries plot, e.g Peak Demand.
Defaults to None.
end (float, optional): Used in conjunction with the prop argument.
Will define the number of days to plot after a certain event in
a timeseries plot, e.g Peak Demand.
Defaults to None.
timezone (str, optional): The timezone to display on the x-axes.
Defaults to "".
start_date_range (str, optional): Defines a start date at which to represent data from.
Defaults to None.
end_date_range (str, optional): Defines a end date at which to represent data to.
Defaults to None.
Returns:
dict: Dictionary containing the created plot and its data table.
"""
# If not facet plot, only plot first scenario
facet=False
if 'Facet' in figure_name:
facet = True
if not facet:
Scenarios = [self.Scenarios[0]]
else:
Scenarios = self.Scenarios
outputs = {}
# List of properties needed by the plot, properties are a set of tuples and contain 3 parts:
# required True/False, property name and scenarios required, scenarios must be a list.
properties = [(True,"reserves_generators_Provision",self.Scenarios)]
# Runs get_formatted_data within PlotDataHelper to populate PlotDataHelper dictionary
# with all required properties, returns a 1 if required data is missing
check_input_data = self.get_formatted_data(properties)
# Checks if all data required by plot is available, if 1 in list required data is missing
if 1 in check_input_data:
return MissingInputData()
for region in self.Zones:
self.logger.info(f"Zone = {region}")
xdimension, ydimension = self.setup_facet_xy_dimensions(facet,multi_scenario=Scenarios)
grid_size = xdimension*ydimension
excess_axs = grid_size - len(Scenarios)
fig1, axs = plotlib.setup_plot(xdimension,ydimension)
plt.subplots_adjust(wspace=0.05, hspace=0.2)
data_tables = []
unique_tech_names = []
for n, scenario in enumerate(Scenarios):
self.logger.info(f"Scenario = {scenario}")
reserve_provision_timeseries = self["reserves_generators_Provision"].get(scenario)
#Check if zone has reserves, if not skips
try:
reserve_provision_timeseries = reserve_provision_timeseries.xs(region,level=self.AGG_BY)
except KeyError:
self.logger.info(f"No reserves deployed in: {scenario}")
continue
reserve_provision_timeseries = self.df_process_gen_inputs(reserve_provision_timeseries)
if reserve_provision_timeseries.empty is True:
self.logger.info(f"No reserves deployed in: {scenario}")
continue
# unitconversion based off peak generation hour, only checked once
if n == 0:
unitconversion = PlotDataHelper.capacity_energy_unitconversion(max(reserve_provision_timeseries.sum(axis=1)))
if prop == "Peak Demand":
self.logger.info("Plotting Peak Demand period")
total_reserve = reserve_provision_timeseries.sum(axis=1)/unitconversion['divisor']
peak_reserve_t = total_reserve.idxmax()
start_date = peak_reserve_t - dt.timedelta(days=start)
end_date = peak_reserve_t + dt.timedelta(days=end)
reserve_provision_timeseries = reserve_provision_timeseries[start_date : end_date]
Peak_Reserve = total_reserve[peak_reserve_t]
elif prop == 'Date Range':
self.logger.info(f"Plotting specific date range: \
{str(start_date_range)} to {str(end_date_range)}")
reserve_provision_timeseries = reserve_provision_timeseries[start_date_range : end_date_range]
else:
self.logger.info("Plotting graph for entire timeperiod")
reserve_provision_timeseries = reserve_provision_timeseries/unitconversion['divisor']
scenario_names = pd.Series([scenario] * len(reserve_provision_timeseries),name = 'Scenario')
data_table = reserve_provision_timeseries.add_suffix(f" ({unitconversion['units']})")
data_table = data_table.set_index([scenario_names],append = True)
data_tables.append(data_table)
plotlib.create_stackplot(axs, reserve_provision_timeseries, self.PLEXOS_color_dict, labels=reserve_provision_timeseries.columns,n=n)
PlotDataHelper.set_plot_timeseries_format(axs,n=n,minticks=4, maxticks=8)
if prop == "Peak Demand":
axs[n].annotate('Peak Reserve: \n' + str(format(int(Peak_Reserve), '.2f')) + ' {}'.format(unitconversion['units']),
xy=(peak_reserve_t, Peak_Reserve),
xytext=((peak_reserve_t + dt.timedelta(days=0.25)), (Peak_Reserve + Peak_Reserve*0.05)),
fontsize=13, arrowprops=dict(facecolor='black', width=3, shrink=0.1))
# create list of gen technologies
l1 = reserve_provision_timeseries.columns.tolist()
unique_tech_names.extend(l1)
if not data_tables:
self.logger.warning(f'No reserves in {region}')
out = MissingZoneData()
outputs[region] = out
continue
# create handles list of unique tech names then order
handles = np.unique(np.array(unique_tech_names)).tolist()
handles.sort(key = lambda i:self.ordered_gen.index(i))
handles = reversed(handles)
# create custom gen_tech legend
gen_tech_legend = []
for tech in handles:
legend_handles = [Patch(facecolor=self.PLEXOS_color_dict[tech],
alpha=1.0,
label=tech)]
gen_tech_legend.extend(legend_handles)
# Add legend
axs[grid_size-1].legend(handles=gen_tech_legend, loc='lower left',bbox_to_anchor=(1,0),
facecolor='inherit', frameon=True)
#Remove extra axes
if excess_axs != 0:
PlotDataHelper.remove_excess_axs(axs,excess_axs,grid_size)
# add facet labels
self.add_facet_labels(fig1)
fig1.add_subplot(111, frameon=False)
plt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)
if mconfig.parser("plot_title_as_region"):
plt.title(region)
plt.ylabel(f"Reserve Provision ({unitconversion['units']})", color='black', rotation='vertical', labelpad=40)
data_table_out = pd.concat(data_tables)
outputs[region] = {'fig': fig1, 'data_table': data_table_out}
return outputs
def total_reserves_by_gen(self, start_date_range: str = None,
end_date_range: str = None, **_):
"""Creates a generation stacked barplot of total reserve provision by generator tech type.
A separate bar is created for each scenario.
Args:
start_date_range (str, optional): Defines a start date at which to represent data from.
Defaults to None.
end_date_range (str, optional): Defines a end date at which to represent data to.
Defaults to None.
Returns:
dict: Dictionary containing the created plot and its data table.
"""
outputs = {}
# List of properties needed by the plot, properties are a set of tuples and contain 3 parts:
# required True/False, property name and scenarios required, scenarios must be a list.
properties = [(True,"reserves_generators_Provision",self.Scenarios)]
# Runs get_formatted_data within PlotDataHelper to populate PlotDataHelper dictionary
# with all required properties, returns a 1 if required data is missing
check_input_data = self.get_formatted_data(properties)
# Checks if all data required by plot is available, if 1 in list required data is missing
if 1 in check_input_data:
return MissingInputData()
for region in self.Zones:
self.logger.info(f"Zone = {region}")
Total_Reserves_Out = pd.DataFrame()
unique_tech_names = []
for scenario in self.Scenarios:
self.logger.info(f"Scenario = {scenario}")
reserve_provision_timeseries = self["reserves_generators_Provision"].get(scenario)
#Check if zone has reserves, if not skips
try:
reserve_provision_timeseries = reserve_provision_timeseries.xs(region,level=self.AGG_BY)
except KeyError:
self.logger.info(f"No reserves deployed in {scenario}")
continue
reserve_provision_timeseries = self.df_process_gen_inputs(reserve_provision_timeseries)
if reserve_provision_timeseries.empty is True:
self.logger.info(f"No reserves deployed in: {scenario}")
continue
# Calculates interval step to correct for MWh of generation
interval_count = PlotDataHelper.get_sub_hour_interval_count(reserve_provision_timeseries)
# sum totals by fuel types
reserve_provision_timeseries = reserve_provision_timeseries/interval_count
reserve_provision = reserve_provision_timeseries.sum(axis=0)
reserve_provision.rename(scenario, inplace=True)
Total_Reserves_Out = pd.concat([Total_Reserves_Out, reserve_provision], axis=1, sort=False).fillna(0)
Total_Reserves_Out = self.create_categorical_tech_index(Total_Reserves_Out)
Total_Reserves_Out = Total_Reserves_Out.T
Total_Reserves_Out = Total_Reserves_Out.loc[:, (Total_Reserves_Out != 0).any(axis=0)]
if Total_Reserves_Out.empty:
out = MissingZoneData()
outputs[region] = out
continue
Total_Reserves_Out.index = Total_Reserves_Out.index.str.replace('_',' ')
Total_Reserves_Out.index = Total_Reserves_Out.index.str.wrap(5, break_long_words=False)
# Convert units
unitconversion = PlotDataHelper.capacity_energy_unitconversion(max(Total_Reserves_Out.sum()))
Total_Reserves_Out = Total_Reserves_Out/unitconversion['divisor']
data_table_out = Total_Reserves_Out.add_suffix(f" ({unitconversion['units']}h)")
# create figure
fig1, axs = plotlib.create_stacked_bar_plot(Total_Reserves_Out, self.PLEXOS_color_dict,
custom_tick_labels=self.custom_xticklabels)
# additional figure formatting
#fig1.set_ylabel(f"Total Reserve Provision ({unitconversion['units']}h)", color='black', rotation='vertical')
axs.set_ylabel(f"Total Reserve Provision ({unitconversion['units']}h)", color='black', rotation='vertical')
# create list of gen technologies
l1 = Total_Reserves_Out.columns.tolist()
unique_tech_names.extend(l1)
# create handles list of unique tech names then order
handles = np.unique(np.array(unique_tech_names)).tolist()
handles.sort(key = lambda i:self.ordered_gen.index(i))
handles = reversed(handles)
# create custom gen_tech legend
gen_tech_legend = []
for tech in handles:
legend_handles = [Patch(facecolor=self.PLEXOS_color_dict[tech],
alpha=1.0,label=tech)]
gen_tech_legend.extend(legend_handles)
# Add legend
axs.legend(handles=gen_tech_legend, loc='lower left',bbox_to_anchor=(1,0),
facecolor='inherit', frameon=True)
if mconfig.parser("plot_title_as_region"):
axs.set_title(region)
outputs[region] = {'fig': fig1, 'data_table': data_table_out}
return outputs
def reg_reserve_shortage(self, **kwargs):
"""Creates a bar plot of reserve shortage for each region in MWh.
Bars are grouped by reserve type, each scenario is plotted as a differnet color.
The 'Shortage' argument is passed to the _reserve_bar_plots() method to
create this plot.
Returns:
dict: Dictionary containing the created plot and its data table.
"""
outputs = self._reserve_bar_plots("Shortage", **kwargs)
return outputs
def reg_reserve_provision(self, **kwargs):
"""Creates a bar plot of reserve provision for each region in MWh.
Bars are grouped by reserve type, each scenario is plotted as a differnet color.
The 'Provision' argument is passed to the _reserve_bar_plots() method to
create this plot.
Returns:
dict: Dictionary containing the created plot and its data table.
"""
outputs = self._reserve_bar_plots("Provision", **kwargs)
return outputs
def reg_reserve_shortage_hrs(self, **kwargs):
"""creates a bar plot of reserve shortage for each region in hrs.
Bars are grouped by reserve type, each scenario is plotted as a differnet color.
The 'Shortage' argument and count_hours=True is passed to the _reserve_bar_plots() method to
create this plot.
Returns:
dict: Dictionary containing the created plot and its data table.
"""
outputs = self._reserve_bar_plots("Shortage", count_hours=True)
return outputs
def _reserve_bar_plots(self, data_set: str, count_hours: bool = False,
start_date_range: str = None,
end_date_range: str = None, **_):
"""internal _reserve_bar_plots method, creates 'Shortage', 'Provision' and 'Shortage' bar
plots
Bars are grouped by reserve type, each scenario is plotted as a differnet color.
Args:
data_set (str): Identifies the reserve data set to use and pull
from the formatted h5 file.
count_hours (bool, optional): if True creates a 'Shortage' hours plot.
Defaults to False.
start_date_range (str, optional): Defines a start date at which to represent data from.
Defaults to None.
end_date_range (str, optional): Defines a end date at which to represent data to.
Defaults to None.
Returns:
dict: Dictionary containing the created plot and its data table.
"""
outputs = {}
# List of properties needed by the plot, properties are a set of tuples and contain 3 parts:
# required True/False, property name and scenarios required, scenarios must be a list.
properties = [(True, f"reserve_{data_set}", self.Scenarios)]
# Runs get_formatted_data within PlotDataHelper to populate PlotDataHelper dictionary
# with all required properties, returns a 1 if required data is missing
check_input_data = self.get_formatted_data(properties)
# Checks if all data required by plot is available, if 1 in list required data is missing
if 1 in check_input_data:
return MissingInputData()
for region in self.Zones:
self.logger.info(f"Zone = {region}")
Data_Table_Out=pd.DataFrame()
reserve_total_chunk = []
for scenario in self.Scenarios:
self.logger.info(f'Scenario = {scenario}')
reserve_timeseries = self[f"reserve_{data_set}"].get(scenario)
# Check if zone has reserves, if not skips
try:
reserve_timeseries = reserve_timeseries.xs(region,level=self.AGG_BY)
except KeyError:
self.logger.info(f"No reserves deployed in {scenario}")
continue
interval_count = PlotDataHelper.get_sub_hour_interval_count(reserve_timeseries)
reserve_timeseries = reserve_timeseries.reset_index(["timestamp","Type","parent"],drop=False)
# Drop duplicates to remove double counting
reserve_timeseries.drop_duplicates(inplace=True)
# Set Type equal to parent value if Type equals '-'
reserve_timeseries['Type'] = reserve_timeseries['Type'].mask(reserve_timeseries['Type'] == '-', reserve_timeseries['parent'])
reserve_timeseries.set_index(["timestamp","Type","parent"],append=True,inplace=True)
# Groupby Type
if count_hours == False:
reserve_total = reserve_timeseries.groupby(["Type"]).sum()/interval_count
elif count_hours == True:
reserve_total = reserve_timeseries[reserve_timeseries[0]>0] #Filter for non zero values
reserve_total = reserve_total.groupby("Type").count()/interval_count
reserve_total.rename(columns={0:scenario},inplace=True)
reserve_total_chunk.append(reserve_total)
if reserve_total_chunk:
reserve_out = pd.concat(reserve_total_chunk,axis=1, sort='False')
reserve_out.columns = reserve_out.columns.str.replace('_',' ')
else:
reserve_out=pd.DataFrame()
# If no reserves return nothing
if reserve_out.empty:
out = MissingZoneData()
outputs[region] = out
continue
if count_hours == False:
# Convert units
unitconversion = PlotDataHelper.capacity_energy_unitconversion(max(reserve_out.sum()))
reserve_out = reserve_out/unitconversion['divisor']
Data_Table_Out = reserve_out.add_suffix(f" ({unitconversion['units']}h)")
else:
Data_Table_Out = reserve_out.add_suffix(" (hrs)")
# create color dictionary
color_dict = dict(zip(reserve_out.columns,self.color_list))
fig2,axs = plotlib.create_grouped_bar_plot(reserve_out, color_dict)
if count_hours == False:
axs.yaxis.set_major_formatter(mpl.ticker.FuncFormatter(lambda x, p: format(x, f',.{self.y_axes_decimalpt}f')))
axs.set_ylabel(f"Reserve {data_set} [{unitconversion['units']}h]", color='black', rotation='vertical')
elif count_hours == True:
axs.set_ylabel(f"Reserve {data_set} Hours", color='black', rotation='vertical')
handles, labels = axs.get_legend_handles_labels()
axs.legend(handles,labels, loc='lower left',bbox_to_anchor=(1,0),
facecolor='inherit', frameon=True)
if mconfig.parser("plot_title_as_region"):
axs.set_title(region)
outputs[region] = {'fig': fig2,'data_table': Data_Table_Out}
return outputs
def reg_reserve_shortage_timeseries(self, figure_name: str = None,
timezone: str = "", start_date_range: str = None,
end_date_range: str = None, **_):
"""Creates a timeseries line plot of reserve shortage.
A line is plotted for each reserve type shortage.
The code will create either a facet plot or a single plot depending on
if the Facet argument is active.
If a facet plot is created, each scenario is plotted on a separate facet,
otherwise all scenarios are plotted on a single plot.
To make a facet plot, ensure the work 'Facet' is found in the figure_name.
Args:
figure_name (str, optional): User defined figure output name. Used here
to determine if a Facet plot should be created.
Defaults to None.
timezone (str, optional): The timezone to display on the x-axes.
Defaults to "".
start_date_range (str, optional): Defines a start date at which to represent data from.
Defaults to None.
end_date_range (str, optional): Defines a end date at which to represent data to.
Defaults to None.
Returns:
dict: Dictionary containing the created plot and its data table.
"""
facet=False
if 'Facet' in figure_name:
facet = True
# If not facet plot, only plot first scenario
if not facet:
Scenarios = [self.Scenarios[0]]
else:
Scenarios = self.Scenarios
outputs = {}
# List of properties needed by the plot, properties are a set of tuples and contain 3 parts:
# required True/False, property name and scenarios required, scenarios must be a list.
properties = [(True, "reserve_Shortage", Scenarios)]
# Runs get_formatted_data within PlotDataHelper to populate PlotDataHelper dictionary
# with all required properties, returns a 1 if required data is missing
check_input_data = self.get_formatted_data(properties)
# Checks if all data required by plot is available, if 1 in list required data is missing
if 1 in check_input_data:
return MissingInputData()
for region in self.Zones:
self.logger.info(f"Zone = {region}")
xdimension, ydimension = self.setup_facet_xy_dimensions(facet,multi_scenario = Scenarios)
grid_size = xdimension*ydimension
excess_axs = grid_size - len(Scenarios)
fig3, axs = plotlib.setup_plot(xdimension,ydimension)
plt.subplots_adjust(wspace=0.05, hspace=0.2)
data_tables = []
unique_reserve_types = []
for n, scenario in enumerate(Scenarios):
self.logger.info(f'Scenario = {scenario}')
reserve_timeseries = self["reserve_Shortage"].get(scenario)
# Check if zone has reserves, if not skips
try:
reserve_timeseries = reserve_timeseries.xs(region,level=self.AGG_BY)
except KeyError:
self.logger.info(f"No reserves deployed in {scenario}")
continue
reserve_timeseries.reset_index(["timestamp","Type","parent"],drop=False,inplace=True)
reserve_timeseries = reserve_timeseries.drop_duplicates()
# Set Type equal to parent value if Type equals '-'
reserve_timeseries['Type'] = reserve_timeseries['Type'].mask(reserve_timeseries['Type'] == '-',
reserve_timeseries['parent'])
reserve_timeseries = reserve_timeseries.pivot(index='timestamp', columns='Type', values=0)
if pd.notna(start_date_range):
self.logger.info(f"Plotting specific date range: \
{str(start_date_range)} to {str(end_date_range)}")
reserve_timeseries = reserve_timeseries[start_date_range : end_date_range]
else:
self.logger.info("Plotting graph for entire timeperiod")
# create color dictionary
color_dict = dict(zip(reserve_timeseries.columns,self.color_list))
scenario_names = pd.Series([scenario] * len(reserve_timeseries),name = 'Scenario')
data_table = reserve_timeseries.add_suffix(" (MW)")
data_table = data_table.set_index([scenario_names],append = True)
data_tables.append(data_table)
for column in reserve_timeseries:
plotlib.create_line_plot(axs,reserve_timeseries,column,color_dict=color_dict,label=column, n=n)
axs[n].yaxis.set_major_formatter(mpl.ticker.FuncFormatter(lambda x, p: format(x, f',.{self.y_axes_decimalpt}f')))
axs[n].margins(x=0.01)
PlotDataHelper.set_plot_timeseries_format(axs,n=n,minticks=6, maxticks=12)
# scenario_names = pd.Series([scenario]*len(reserve_timeseries),name='Scenario')
# reserve_timeseries = reserve_timeseries.set_index([scenario_names],append=True)
# reserve_timeseries_chunk.append(reserve_timeseries)
# create list of gen technologies
l1 = reserve_timeseries.columns.tolist()
unique_reserve_types.extend(l1)
if not data_tables:
out = MissingZoneData()
outputs[region] = out
continue
# create handles list of unique reserve names
handles = np.unique(np.array(unique_reserve_types)).tolist()
# create color dictionary
color_dict = dict(zip(handles,self.color_list))
# create custom gen_tech legend
reserve_legend = []
for Type in handles:
legend_handles = [Line2D([0], [0], color=color_dict[Type], lw=2, label=Type)]
reserve_legend.extend(legend_handles)
axs[grid_size-1].legend(handles=reserve_legend, loc='lower left',
bbox_to_anchor=(1,0), facecolor='inherit',
frameon=True)
#Remove extra axes
if excess_axs != 0:
PlotDataHelper.remove_excess_axs(axs,excess_axs,grid_size)
# add facet labels
self.add_facet_labels(fig3)
fig3.add_subplot(111, frameon=False)
plt.tick_params(labelcolor='none', top=False, bottom=False,
left=False, right=False)
# plt.xlabel(timezone, color='black', rotation='horizontal',labelpad = 30)
plt.ylabel('Reserve Shortage [MW]', color='black',
rotation='vertical',labelpad = 40)
if mconfig.parser("plot_title_as_region"):
plt.title(region)
data_table_out = pd.concat(data_tables)
outputs[region] = {'fig': fig3, 'data_table': data_table_out}
return outputs | [
"logging.getLogger",
"marmot.plottingmodules.plotutils.plot_library.create_stackplot",
"matplotlib.pyplot.ylabel",
"numpy.array",
"marmot.plottingmodules.plotutils.plot_data_helper.PlotDataHelper.get_sub_hour_interval_count",
"datetime.timedelta",
"marmot.plottingmodules.plotutils.plot_exceptions.Missin... | [((1826, 1870), 'logging.getLogger', 'logging.getLogger', (["('marmot_plot.' + __name__)"], {}), "('marmot_plot.' + __name__)\n", (1843, 1870), False, 'import logging\n'), ((1901, 1951), 'marmot.config.mconfig.parser', 'mconfig.parser', (['"""axes_options"""', '"""y_axes_decimalpt"""'], {}), "('axes_options', 'y_axes_decimalpt')\n", (1915, 1951), True, 'import marmot.config.mconfig as mconfig\n'), ((5253, 5271), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (5269, 5271), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, MissingZoneData\n'), ((5580, 5622), 'marmot.plottingmodules.plotutils.plot_library.setup_plot', 'plotlib.setup_plot', (['xdimension', 'ydimension'], {}), '(xdimension, ydimension)\n', (5598, 5622), True, 'import marmot.plottingmodules.plotutils.plot_library as plotlib\n'), ((5634, 5678), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.05)', 'hspace': '(0.2)'}), '(wspace=0.05, hspace=0.2)\n', (5653, 5678), True, 'import matplotlib.pyplot as plt\n'), ((10420, 10508), 'matplotlib.pyplot.tick_params', 'plt.tick_params', ([], {'labelcolor': '"""none"""', 'top': '(False)', 'bottom': '(False)', 'left': '(False)', 'right': '(False)'}), "(labelcolor='none', top=False, bottom=False, left=False,\n right=False)\n", (10435, 10508), True, 'import matplotlib.pyplot as plt\n'), ((10520, 10558), 'marmot.config.mconfig.parser', 'mconfig.parser', (['"""plot_title_as_region"""'], {}), "('plot_title_as_region')\n", (10534, 10558), True, 'import marmot.config.mconfig as mconfig\n'), ((10606, 10719), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['f"""Reserve Provision ({unitconversion[\'units\']})"""'], {'color': '"""black"""', 'rotation': '"""vertical"""', 'labelpad': '(40)'}), '(f"Reserve Provision ({unitconversion[\'units\']})", color=\'black\',\n rotation=\'vertical\', labelpad=40)\n', (10616, 10719), True, 'import matplotlib.pyplot as plt\n'), ((10747, 10769), 'pandas.concat', 'pd.concat', (['data_tables'], {}), '(data_tables)\n', (10756, 10769), True, 'import pandas as pd\n'), ((12249, 12267), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (12265, 12267), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, MissingZoneData\n'), ((12386, 12400), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (12398, 12400), True, 'import pandas as pd\n'), ((14810, 14933), 'marmot.plottingmodules.plotutils.plot_library.create_stacked_bar_plot', 'plotlib.create_stacked_bar_plot', (['Total_Reserves_Out', 'self.PLEXOS_color_dict'], {'custom_tick_labels': 'self.custom_xticklabels'}), '(Total_Reserves_Out, self.PLEXOS_color_dict,\n custom_tick_labels=self.custom_xticklabels)\n', (14841, 14933), True, 'import marmot.plottingmodules.plotutils.plot_library as plotlib\n'), ((16142, 16180), 'marmot.config.mconfig.parser', 'mconfig.parser', (['"""plot_title_as_region"""'], {}), "('plot_title_as_region')\n", (16156, 16180), True, 'import marmot.config.mconfig as mconfig\n'), ((19651, 19669), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (19667, 19669), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, MissingZoneData\n'), ((19782, 19796), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (19794, 19796), True, 'import pandas as pd\n'), ((22546, 22602), 'marmot.plottingmodules.plotutils.plot_library.create_grouped_bar_plot', 'plotlib.create_grouped_bar_plot', (['reserve_out', 'color_dict'], {}), '(reserve_out, color_dict)\n', (22577, 22602), True, 'import marmot.plottingmodules.plotutils.plot_library as plotlib\n'), ((23238, 23276), 'marmot.config.mconfig.parser', 'mconfig.parser', (['"""plot_title_as_region"""'], {}), "('plot_title_as_region')\n", (23252, 23276), True, 'import marmot.config.mconfig as mconfig\n'), ((25756, 25774), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingInputData', 'MissingInputData', ([], {}), '()\n', (25772, 25774), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, MissingZoneData\n'), ((26094, 26136), 'marmot.plottingmodules.plotutils.plot_library.setup_plot', 'plotlib.setup_plot', (['xdimension', 'ydimension'], {}), '(xdimension, ydimension)\n', (26112, 26136), True, 'import marmot.plottingmodules.plotutils.plot_library as plotlib\n'), ((26148, 26192), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.05)', 'hspace': '(0.2)'}), '(wspace=0.05, hspace=0.2)\n', (26167, 26192), True, 'import matplotlib.pyplot as plt\n'), ((30139, 30227), 'matplotlib.pyplot.tick_params', 'plt.tick_params', ([], {'labelcolor': '"""none"""', 'top': '(False)', 'bottom': '(False)', 'left': '(False)', 'right': '(False)'}), "(labelcolor='none', top=False, bottom=False, left=False,\n right=False)\n", (30154, 30227), True, 'import matplotlib.pyplot as plt\n'), ((30353, 30441), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Reserve Shortage [MW]"""'], {'color': '"""black"""', 'rotation': '"""vertical"""', 'labelpad': '(40)'}), "('Reserve Shortage [MW]', color='black', rotation='vertical',\n labelpad=40)\n", (30363, 30441), True, 'import matplotlib.pyplot as plt\n'), ((30492, 30530), 'marmot.config.mconfig.parser', 'mconfig.parser', (['"""plot_title_as_region"""'], {}), "('plot_title_as_region')\n", (30506, 30530), True, 'import marmot.config.mconfig as mconfig\n'), ((30607, 30629), 'pandas.concat', 'pd.concat', (['data_tables'], {}), '(data_tables)\n', (30616, 30629), True, 'import pandas as pd\n'), ((8318, 8456), 'marmot.plottingmodules.plotutils.plot_library.create_stackplot', 'plotlib.create_stackplot', (['axs', 'reserve_provision_timeseries', 'self.PLEXOS_color_dict'], {'labels': 'reserve_provision_timeseries.columns', 'n': 'n'}), '(axs, reserve_provision_timeseries, self.\n PLEXOS_color_dict, labels=reserve_provision_timeseries.columns, n=n)\n', (8342, 8456), True, 'import marmot.plottingmodules.plotutils.plot_library as plotlib\n'), ((8467, 8542), 'marmot.plottingmodules.plotutils.plot_data_helper.PlotDataHelper.set_plot_timeseries_format', 'PlotDataHelper.set_plot_timeseries_format', (['axs'], {'n': 'n', 'minticks': '(4)', 'maxticks': '(8)'}), '(axs, n=n, minticks=4, maxticks=8)\n', (8508, 8542), False, 'from marmot.plottingmodules.plotutils.plot_data_helper import PlotDataHelper\n'), ((9301, 9318), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingZoneData', 'MissingZoneData', ([], {}), '()\n', (9316, 9318), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, MissingZoneData\n'), ((10227, 10287), 'marmot.plottingmodules.plotutils.plot_data_helper.PlotDataHelper.remove_excess_axs', 'PlotDataHelper.remove_excess_axs', (['axs', 'excess_axs', 'grid_size'], {}), '(axs, excess_axs, grid_size)\n', (10259, 10287), False, 'from marmot.plottingmodules.plotutils.plot_data_helper import PlotDataHelper\n'), ((10576, 10593), 'matplotlib.pyplot.title', 'plt.title', (['region'], {}), '(region)\n', (10585, 10593), True, 'import matplotlib.pyplot as plt\n'), ((13349, 13421), 'marmot.plottingmodules.plotutils.plot_data_helper.PlotDataHelper.get_sub_hour_interval_count', 'PlotDataHelper.get_sub_hour_interval_count', (['reserve_provision_timeseries'], {}), '(reserve_provision_timeseries)\n', (13391, 13421), False, 'from marmot.plottingmodules.plotutils.plot_data_helper import PlotDataHelper\n'), ((14135, 14152), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingZoneData', 'MissingZoneData', ([], {}), '()\n', (14150, 14152), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, MissingZoneData\n'), ((20359, 20421), 'marmot.plottingmodules.plotutils.plot_data_helper.PlotDataHelper.get_sub_hour_interval_count', 'PlotDataHelper.get_sub_hour_interval_count', (['reserve_timeseries'], {}), '(reserve_timeseries)\n', (20401, 20421), False, 'from marmot.plottingmodules.plotutils.plot_data_helper import PlotDataHelper\n'), ((21586, 21638), 'pandas.concat', 'pd.concat', (['reserve_total_chunk'], {'axis': '(1)', 'sort': '"""False"""'}), "(reserve_total_chunk, axis=1, sort='False')\n", (21595, 21638), True, 'import pandas as pd\n'), ((21763, 21777), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (21775, 21777), True, 'import pandas as pd\n'), ((21878, 21895), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingZoneData', 'MissingZoneData', ([], {}), '()\n', (21893, 21895), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, MissingZoneData\n'), ((27367, 27393), 'pandas.notna', 'pd.notna', (['start_date_range'], {}), '(start_date_range)\n', (27375, 27393), True, 'import pandas as pd\n'), ((28506, 28582), 'marmot.plottingmodules.plotutils.plot_data_helper.PlotDataHelper.set_plot_timeseries_format', 'PlotDataHelper.set_plot_timeseries_format', (['axs'], {'n': 'n', 'minticks': '(6)', 'maxticks': '(12)'}), '(axs, n=n, minticks=6, maxticks=12)\n', (28547, 28582), False, 'from marmot.plottingmodules.plotutils.plot_data_helper import PlotDataHelper\n'), ((29070, 29087), 'marmot.plottingmodules.plotutils.plot_exceptions.MissingZoneData', 'MissingZoneData', ([], {}), '()\n', (29085, 29087), False, 'from marmot.plottingmodules.plotutils.plot_exceptions import MissingInputData, MissingZoneData\n'), ((29946, 30006), 'marmot.plottingmodules.plotutils.plot_data_helper.PlotDataHelper.remove_excess_axs', 'PlotDataHelper.remove_excess_axs', (['axs', 'excess_axs', 'grid_size'], {}), '(axs, excess_axs, grid_size)\n', (29978, 30006), False, 'from marmot.plottingmodules.plotutils.plot_data_helper import PlotDataHelper\n'), ((30547, 30564), 'matplotlib.pyplot.title', 'plt.title', (['region'], {}), '(region)\n', (30556, 30564), True, 'import matplotlib.pyplot as plt\n'), ((9787, 9855), 'matplotlib.patches.Patch', 'Patch', ([], {'facecolor': 'self.PLEXOS_color_dict[tech]', 'alpha': '(1.0)', 'label': 'tech'}), '(facecolor=self.PLEXOS_color_dict[tech], alpha=1.0, label=tech)\n', (9792, 9855), False, 'from matplotlib.patches import Patch\n'), ((15805, 15873), 'matplotlib.patches.Patch', 'Patch', ([], {'facecolor': 'self.PLEXOS_color_dict[tech]', 'alpha': '(1.0)', 'label': 'tech'}), '(facecolor=self.PLEXOS_color_dict[tech], alpha=1.0, label=tech)\n', (15810, 15873), False, 'from matplotlib.patches import Patch\n'), ((28225, 28329), 'marmot.plottingmodules.plotutils.plot_library.create_line_plot', 'plotlib.create_line_plot', (['axs', 'reserve_timeseries', 'column'], {'color_dict': 'color_dict', 'label': 'column', 'n': 'n'}), '(axs, reserve_timeseries, column, color_dict=\n color_dict, label=column, n=n)\n', (28249, 28329), True, 'import marmot.plottingmodules.plotutils.plot_library as plotlib\n'), ((29542, 29600), 'matplotlib.lines.Line2D', 'Line2D', (['[0]', '[0]'], {'color': 'color_dict[Type]', 'lw': '(2)', 'label': 'Type'}), '([0], [0], color=color_dict[Type], lw=2, label=Type)\n', (29548, 29600), False, 'from matplotlib.lines import Line2D\n'), ((7141, 7165), 'datetime.timedelta', 'dt.timedelta', ([], {'days': 'start'}), '(days=start)\n', (7153, 7165), True, 'import datetime as dt\n'), ((7214, 7236), 'datetime.timedelta', 'dt.timedelta', ([], {'days': 'end'}), '(days=end)\n', (7226, 7236), True, 'import datetime as dt\n'), ((9497, 9524), 'numpy.array', 'np.array', (['unique_tech_names'], {}), '(unique_tech_names)\n', (9505, 9524), True, 'import numpy as np\n'), ((13736, 13806), 'pandas.concat', 'pd.concat', (['[Total_Reserves_Out, reserve_provision]'], {'axis': '(1)', 'sort': '(False)'}), '([Total_Reserves_Out, reserve_provision], axis=1, sort=False)\n', (13745, 13806), True, 'import pandas as pd\n'), ((15515, 15542), 'numpy.array', 'np.array', (['unique_tech_names'], {}), '(unique_tech_names)\n', (15523, 15542), True, 'import numpy as np\n'), ((29258, 29288), 'numpy.array', 'np.array', (['unique_reserve_types'], {}), '(unique_reserve_types)\n', (29266, 29288), True, 'import numpy as np\n'), ((8846, 8869), 'datetime.timedelta', 'dt.timedelta', ([], {'days': '(0.25)'}), '(days=0.25)\n', (8858, 8869), True, 'import datetime as dt\n')] |
# -*- coding:utf-8 -*-
from yepes.apps import apps
AbstractConnection = apps.get_class('emails.abstract_models', 'AbstractConnection')
AbstractDelivery = apps.get_class('emails.abstract_models', 'AbstractDelivery')
AbstractMessage = apps.get_class('emails.abstract_models', 'AbstractMessage')
class Connection(AbstractConnection):
pass
class Delivery(AbstractDelivery):
pass
class Message(AbstractMessage):
pass
| [
"yepes.apps.apps.get_class"
] | [((74, 136), 'yepes.apps.apps.get_class', 'apps.get_class', (['"""emails.abstract_models"""', '"""AbstractConnection"""'], {}), "('emails.abstract_models', 'AbstractConnection')\n", (88, 136), False, 'from yepes.apps import apps\n'), ((156, 216), 'yepes.apps.apps.get_class', 'apps.get_class', (['"""emails.abstract_models"""', '"""AbstractDelivery"""'], {}), "('emails.abstract_models', 'AbstractDelivery')\n", (170, 216), False, 'from yepes.apps import apps\n'), ((235, 294), 'yepes.apps.apps.get_class', 'apps.get_class', (['"""emails.abstract_models"""', '"""AbstractMessage"""'], {}), "('emails.abstract_models', 'AbstractMessage')\n", (249, 294), False, 'from yepes.apps import apps\n')] |
"""
Top level function calls for pentomino solver
"""
from tree_find_pents import build_pent_tree
from rect_find_x import solve_case
def fill_rectangles_with_pentominos(io_obj=print, low=3, high=7):
"""
Loop through rectangle sizes and solve for each. build_pent_tree
is called to initialize the tree. Io_obj is a routine to be used
to display or store results. It defaults to a straight print in
python3, but can be overridden.
"""
_solve_rectangles(build_pent_tree(), tuple(range(low, high)), io_obj)
def _solve_rectangles(tree, zrange, io_obj):
"""
Call wrap_rectangle for all values inside the range of rectangle heights
"""
tuple(map(_wrap_rectangle(tree)(io_obj), zrange))
def _wrap_rectangle(tree):
"""
Curry process_rectangle calls (called from inside a map function)
"""
def _inner0(io_obj):
def _inner1(ysize):
_process_rectangle(tree, ysize, io_obj)
return _inner1
return _inner0
def _process_rectangle(tree, ysize, io_obj):
"""
Call solve case. Generate layout of the rectangle first (ysize rows each
of which are 60 // ysize squares long)
"""
solve_case([[0 for _ in range(60 // ysize)]
for _ in range(ysize)], tree, io_obj)
if __name__ == "__main__":
fill_rectangles_with_pentominos()
| [
"tree_find_pents.build_pent_tree"
] | [((484, 501), 'tree_find_pents.build_pent_tree', 'build_pent_tree', ([], {}), '()\n', (499, 501), False, 'from tree_find_pents import build_pent_tree\n')] |
# --------------------------------------------------------------------------- #
# Title: Wifi/Ethernet communication server script
# Author: <NAME>
# Date: 04/07/2018 (DD/MM/YYYY)
# Description: This function opens up a port for wifi/ethernet communication
# and listens to the channel, if it receives a string, it crops part of it to
# extract the angle. If the string received contains "flag" as content, it
# breaks the listening loop.
# --------------------------------------------------------------------------- #
# taken from https://pymotw.com/3/socket/tcp.html
import socket
import sys
import time
class wifi_rx():
def receber(self):
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the address given on the command line
# You may extract this address from a rpi3 with ifconfig
server_name = '192.168.43.62'
server_address = (server_name, 10000)
#print (str(sys.stderr) + 'starting up on %s port %s' % server_address)
sock.bind(server_address)
sock.listen(1)
data = False
flag = False
while not(flag):
#print (str(sys.stderr) + 'waiting for a connection')
connection, client_address = sock.accept()
try:
#print(sys.stderr)
#print('client connected:')
#print(client_address)
while not(flag):
data2 = connection.recv(64)
#print ('received "%s' % data2)
#print("data 2: " + str(data2))
# cropping the strint to extract the desired part
self.angulo = str(data2)[2:-1]
self.retornar(self.angulo)
time.sleep(0.005)
print("Received message: {}".format(self.angulo))
if data2:
connection.sendall(data2)
data = data2
if (str(data2)[2:-1] == "flag"):
flag = data
break
else:
break
finally:
connection.close()
def retornar(self,angulo):
print("Relooping and listening again...")
return angulo
#a = wifi_rx()
#a.receber()
#b = a.retornar()
#print(b)
| [
"time.sleep",
"socket.socket"
] | [((700, 749), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (713, 749), False, 'import socket\n'), ((1803, 1820), 'time.sleep', 'time.sleep', (['(0.005)'], {}), '(0.005)\n', (1813, 1820), False, 'import time\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# ade:
# Asynchronous Differential Evolution.
#
# Copyright (C) 2018-20 by <NAME>,
# http://edsuom.com/ade
#
# See edsuom.com for API documentation as well as information about
# Ed's background and other projects, software and otherwise.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the
# License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an "AS
# IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied. See the License for the specific language
# governing permissions and limitations under the License.
"""
Unit tests for L{specs}.
"""
from ade import specs
from ade.test import testbase as tb
VERBOSE = True
class MockSpecs(object):
def __init__(self):
self.calls = []
def add(self, name, subkey, value):
self.calls.append(['add', name, subkey, value])
class Test_DictStacker(tb.TestCase):
def setUp(self):
self.ds = specs.DictStacker('foo')
def test_add_one(self):
self.ds.add(1, ['first'])
name, dct = self.ds.done()
self.assertEqual(name, 'foo')
self.assertEqual(dct, {'first':1})
def test_add_multiple(self):
self.ds.add(1, ['first'])
self.ds.add(2, ['second'])
name, dct = self.ds.done()
self.assertEqual(name, 'foo')
self.assertEqual(dct, {'first':1, 'second':2})
def test_add_nested(self):
self.ds.add(0, ['zero'])
self.ds.add(1, ['x1', 1])
self.ds.add(2, ['x1', 2])
self.ds.add(10, ['x10', 1])
self.ds.add(20, ['x10', 2])
self.ds.add(4, ['x2', 2])
name, dct = self.ds.done()
self.assertEqual(name, 'foo')
self.assertEqual(dct, {
'zero': 0,
'x1': {1:1, 2:2},
'x2': {2:4},
'x10': {1:10, 2:20},
}
)
class Test_Specs(tb.TestCase):
def setUp(self):
self.s = specs.Specs()
def test_add(self):
self.s.add('foo', 1)
self.assertEqual(self.s.foo, 1)
def test_add_dict_basic(self):
self.s.dict_start('foo')
self.s.dict_add(1, 'alpha')
self.s.dict_add(2, 'bravo')
self.s.dict_done()
self.assertEqual(self.s.foo, {'alpha':1, 'bravo':2})
def test_add_dict_nested(self):
self.s.dict_start('foo')
self.s.dict_add(1.1, 'alpha', 'first')
self.s.dict_add(1.2, 'alpha', 'second')
self.s.dict_add(2.1, 'bravo', 'first')
self.s.dict_add(2.2, 'bravo', 'second')
self.s.dict_done()
self.assertEqual(self.s.foo, {
'alpha': {'first':1.1, 'second':1.2},
'bravo': {'first':2.1, 'second':2.2}})
def test_get_attr(self):
self.s.foo = 1
self.assertEqual(self.s.get('foo'), 1)
self.assertEqual(self.s.get('bar'), {})
def test_get_dict(self):
stuff = {'alpha':1, 'bravo':2}
self.s.stuff = stuff
self.assertEqual(self.s.get('stuff'), stuff)
self.assertEqual(self.s.get('stuff', 'alpha'), 1)
self.assertEqual(self.s.get('stuff', 'bravo'), 2)
self.assertEqual(self.s.get('stuff', 'charlie'), {})
def test_get_subdict(self):
stuff = {'alpha':1, 'bravo':{'second':2, 'third':3}}
self.s.stuff = stuff
self.assertEqual(self.s.get('stuff'), stuff)
self.assertEqual(self.s.get('stuff', 'alpha'), 1)
self.assertEqual(self.s.get('stuff', 'bravo', 'second'), 2)
self.assertEqual(self.s.get('stuff', 'bravo', 'third'), 3)
class Test_SpecsLoader(tb.TestCase):
def setUp(self):
filePath = tb.fileInModuleDir("test.specs")
self.sl = specs.SpecsLoader(filePath)
def test_get_attribute(self):
s = self.sl()
self.assertEqual(s.get('C19_US', 'k0'), 42)
def test_parseName_dictName(self):
self.assertEqual(self.sl.parseName(['foo']), ['foo'])
def test_parseName_dictKey(self):
tokens = ['foo:bar']
self.assertEqual(self.sl.parseName(tokens), ['foo', 'bar'])
def test_parseValue(self):
self.assertIs(self.sl.parseValue("None"), None)
self.assertTrue(self.sl.parseValue("True"))
self.assertFalse(self.sl.parseValue("False"))
self.assertEqual(self.sl.parseValue("3.14159"), 3.14159)
def check(self, value, *args):
self.assertEqual(self.s.get(*args), value)
def test_call(self):
self.s = self.sl()
self.check([0, 1], 'first', 'alpha')
self.check([-1.5, +1.5], 'first', 'bravo')
self.check(3.14159, 'first', 'charlie')
self.check([0, 10], 'second', 'alpha')
self.check([-15, +15], 'second', 'bravo')
def test_call_complicated(self):
self.s = self.sl()
self.check(['t0', -29.486, +75.451, 3.0], 'C19_US', 'relations', 'r')
| [
"ade.specs.DictStacker",
"ade.test.testbase.fileInModuleDir",
"ade.specs.Specs",
"ade.specs.SpecsLoader"
] | [((1198, 1222), 'ade.specs.DictStacker', 'specs.DictStacker', (['"""foo"""'], {}), "('foo')\n", (1215, 1222), False, 'from ade import specs\n'), ((2208, 2221), 'ade.specs.Specs', 'specs.Specs', ([], {}), '()\n', (2219, 2221), False, 'from ade import specs\n'), ((3924, 3956), 'ade.test.testbase.fileInModuleDir', 'tb.fileInModuleDir', (['"""test.specs"""'], {}), "('test.specs')\n", (3942, 3956), True, 'from ade.test import testbase as tb\n'), ((3975, 4002), 'ade.specs.SpecsLoader', 'specs.SpecsLoader', (['filePath'], {}), '(filePath)\n', (3992, 4002), False, 'from ade import specs\n')] |
import numpy as np
import pandas as p
from datetime import datetime, timedelta
class PreprocessData():
def __init__(self, file_name):
self.file_name = file_name
#get only used feature parameters
def get_features(self, file_name):
data = p.read_csv(file_name, skiprows=7, sep=';', header=None)
data.drop(data.columns[len(data.columns)-1], axis=1, inplace=True)
data.columns = ['DateAndTime', 'T', 'Po', 'P', 'Pa', 'U', 'DD', 'Ff', 'ff10',
'ff3', 'N', 'WW', 'W1', 'W2', 'Tn', 'Tx', 'Cl', 'Nh', 'H', 'Cm', 'Ch',
'VV', 'Td', 'RRR', 'tR', 'E', 'Tg', 'E\'', 'sss']
data [['Date', 'Time']] = data.DateAndTime.str.split(expand = True)
data.Date = self.removeYear(data)
return data[['Date', 'Time', 'T', 'Po', 'P', 'Pa', 'DD', 'Ff', 'N', 'Tn', 'Tx', 'VV', 'Td']]
#preprocess data in case of trining model or generating data to run prediction
def preprocess(self, training_flag, predict_date):
data = self.get_features(self.file_name)
data_date = p.get_dummies(data.Date.to_frame())
data_time = p.get_dummies(data.Time.to_frame())
wind_direction = p.get_dummies(data.DD.to_frame())
cloud_rate = p.get_dummies(data.N.to_frame())
data_target = data[['T']];
name = "features.csv"
if training_flag:
temp_data = data.Date.to_frame().apply(lambda x: p.Series(self.training(x, data_target)), axis=1)
result = p.concat([data_date, data_time, wind_direction, cloud_rate, temp_data], axis=1)
result.iloc[:len(result.index) - 365*8].to_csv("features.csv")
data_target.iloc[:len(data_target.index) - 365*8].to_csv("target.csv")
return "features.csv", "target.csv"
else:
temp_data = data.Date.to_frame().apply(lambda x: p.Series(self.predicting(x, data_target)), axis=1)
data_date = data_date.iloc[:8]
predict_date = datetime.strptime(predict_date, "%d.%m.%Y")
new_date_string = ("Date_%02d.%02d") % (predict_date.day, predict_date.month)
predict_date = predict_date - timedelta(days=1)
date_string = ("Date_%02d.%02d") % (predict_date.day, predict_date.month)
data_date[date_string] = 0
data_date[new_date_string] = 1
result = p.concat([data_date, data_time, wind_direction, cloud_rate, temp_data], axis=1)
result.iloc[:8].to_csv("test_f.csv")
return "test_f.csv"
def removeYear(self, data):
data [['Day', 'Month', 'Year']] = data.Date.str.split(pat = '.', expand = True)
data.loc[:, 'Date'] = data[['Day', 'Month']].apply(lambda x: '.'.join(x), axis = 1)
return data.Date
def training(self, row, temperature_data):
after_drop = temperature_data.drop([row.name])
if row.name + 365*8 <= len(after_drop.index):
result = []
count = 0
for i in range(365):
count += 1
result = np.append(result, after_drop.iloc[row.name + i*8])
count = 0 if count == 8 else count
return result
return None
def predicting(self, row, temperature_data):
if row.name < 8:
result = []
count = 0
for i in range(365):
count += 1
result = np.append(result, temperature_data.iloc[row.name + i*8])
count = 0 if count == 8 else count
return result
return None
| [
"pandas.read_csv",
"datetime.datetime.strptime",
"numpy.append",
"datetime.timedelta",
"pandas.concat"
] | [((267, 322), 'pandas.read_csv', 'p.read_csv', (['file_name'], {'skiprows': '(7)', 'sep': '""";"""', 'header': 'None'}), "(file_name, skiprows=7, sep=';', header=None)\n", (277, 322), True, 'import pandas as p\n'), ((1485, 1564), 'pandas.concat', 'p.concat', (['[data_date, data_time, wind_direction, cloud_rate, temp_data]'], {'axis': '(1)'}), '([data_date, data_time, wind_direction, cloud_rate, temp_data], axis=1)\n', (1493, 1564), True, 'import pandas as p\n'), ((1969, 2012), 'datetime.datetime.strptime', 'datetime.strptime', (['predict_date', '"""%d.%m.%Y"""'], {}), "(predict_date, '%d.%m.%Y')\n", (1986, 2012), False, 'from datetime import datetime, timedelta\n'), ((2353, 2432), 'pandas.concat', 'p.concat', (['[data_date, data_time, wind_direction, cloud_rate, temp_data]'], {'axis': '(1)'}), '([data_date, data_time, wind_direction, cloud_rate, temp_data], axis=1)\n', (2361, 2432), True, 'import pandas as p\n'), ((2145, 2162), 'datetime.timedelta', 'timedelta', ([], {'days': '(1)'}), '(days=1)\n', (2154, 2162), False, 'from datetime import datetime, timedelta\n'), ((3041, 3093), 'numpy.append', 'np.append', (['result', 'after_drop.iloc[row.name + i * 8]'], {}), '(result, after_drop.iloc[row.name + i * 8])\n', (3050, 3093), True, 'import numpy as np\n'), ((3397, 3455), 'numpy.append', 'np.append', (['result', 'temperature_data.iloc[row.name + i * 8]'], {}), '(result, temperature_data.iloc[row.name + i * 8])\n', (3406, 3455), True, 'import numpy as np\n')] |
"""
OBJECT RECOGNITION USING A SPIKING NEURAL NETWORK.
* The main code script to run the model.
@author: atenagm1375
"""
# %% IMPORT MODULES
import torch
from utils.data import CaltechDatasetLoader, CaltechDataset
from utils.model import DeepCSNN
from tqdm import tqdm
# %% ENVIRONMENT CONSTANTS
PATH = "../101_ObjectCategories/"
CLASSES = ["Faces", "car_side", "Motorbikes", "watch"]
image_size = (100, 100)
DoG_params = {"size_low": 3, "size_high": 15}
test_ratio = 0.3
# %% LOAD DATA
data = CaltechDatasetLoader(PATH, CLASSES, image_size)
data.split_train_test(test_ratio)
train_dataset = CaltechDataset(data, **DoG_params)
test_dataset = CaltechDataset(data, train=False, **DoG_params)
trainloader = torch.utils.data.DataLoader(train_dataset, batch_size=1,
num_workers=4, pin_memory=False)
testloader = torch.utils.data.DataLoader(test_dataset, batch_size=1,
num_workers=4, pin_memory=False)
# %% RUN DEEPCSNN MODEL
model = DeepCSNN(input_shape=(1, *image_size), n_classes=len(CLASSES))
model.compile()
# model.fit(x_train, y_train, [500, 1000, 1500])
# y_pred = model.predict(x_test)
# model.classification_report(y_test, y_pred)
# %%
| [
"utils.data.CaltechDataset",
"utils.data.CaltechDatasetLoader",
"torch.utils.data.DataLoader"
] | [((505, 552), 'utils.data.CaltechDatasetLoader', 'CaltechDatasetLoader', (['PATH', 'CLASSES', 'image_size'], {}), '(PATH, CLASSES, image_size)\n', (525, 552), False, 'from utils.data import CaltechDatasetLoader, CaltechDataset\n'), ((603, 637), 'utils.data.CaltechDataset', 'CaltechDataset', (['data'], {}), '(data, **DoG_params)\n', (617, 637), False, 'from utils.data import CaltechDatasetLoader, CaltechDataset\n'), ((653, 700), 'utils.data.CaltechDataset', 'CaltechDataset', (['data'], {'train': '(False)'}), '(data, train=False, **DoG_params)\n', (667, 700), False, 'from utils.data import CaltechDatasetLoader, CaltechDataset\n'), ((716, 809), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['train_dataset'], {'batch_size': '(1)', 'num_workers': '(4)', 'pin_memory': '(False)'}), '(train_dataset, batch_size=1, num_workers=4,\n pin_memory=False)\n', (743, 809), False, 'import torch\n'), ((862, 954), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['test_dataset'], {'batch_size': '(1)', 'num_workers': '(4)', 'pin_memory': '(False)'}), '(test_dataset, batch_size=1, num_workers=4,\n pin_memory=False)\n', (889, 954), False, 'import torch\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Datasets
==================
Classes for dataset handling
Dataset - Base class
^^^^^^^^^^^^^^^^^^^^
This is the base class, and all the specialized datasets are inherited from it. One should never use base class itself.
Usage examples:
.. code-block:: python
:linenos:
# Create class
dataset = TUTAcousticScenes_2017_DevelopmentSet(data_path='data')
# Initialize dataset, this will make sure dataset is downloaded, packages are extracted, and needed meta files are created
dataset.initialize()
# Show meta data
dataset.meta.show()
# Get all evaluation setup folds
folds = dataset.folds()
# Get all evaluation setup folds
train_data_fold1 = dataset.train(fold=folds[0])
test_data_fold1 = dataset.test(fold=folds[0])
.. autosummary::
:toctree: generated/
Dataset
Dataset.initialize
Dataset.show_info
Dataset.audio_files
Dataset.audio_file_count
Dataset.meta
Dataset.meta_count
Dataset.error_meta
Dataset.error_meta_count
Dataset.fold_count
Dataset.scene_labels
Dataset.scene_label_count
Dataset.event_labels
Dataset.event_label_count
Dataset.audio_tags
Dataset.audio_tag_count
Dataset.download_packages
Dataset.extract
Dataset.train
Dataset.test
Dataset.eval
Dataset.folds
Dataset.file_meta
Dataset.file_error_meta
Dataset.file_error_meta
Dataset.relative_to_absolute_path
Dataset.absolute_to_relative
AcousticSceneDataset
^^^^^^^^^^^^^^^^^^^^
.. autosummary::
:toctree: generated/
AcousticSceneDataset
Specialized classes inherited AcousticSceneDataset:
.. autosummary::
:toctree: generated/
TUTAcousticScenes_2017_DevelopmentSet
TUTAcousticScenes_2016_DevelopmentSet
TUTAcousticScenes_2016_EvaluationSet
SoundEventDataset
^^^^^^^^^^^^^^^^^
.. autosummary::
:toctree: generated/
SoundEventDataset
SoundEventDataset.event_label_count
SoundEventDataset.event_labels
SoundEventDataset.train
SoundEventDataset.test
Specialized classes inherited SoundEventDataset:
.. autosummary::
:toctree: generated/
TUTRareSoundEvents_2017_DevelopmentSet
TUTSoundEvents_2016_DevelopmentSet
TUTSoundEvents_2016_EvaluationSet
AudioTaggingDataset
^^^^^^^^^^^^^^^^^^^
.. autosummary::
:toctree: generated/
AudioTaggingDataset
"""
from __future__ import print_function, absolute_import
import sys
import os
import logging
import socket
import zipfile
import tarfile
import collections
import csv
import numpy
import hashlib
import yaml
from tqdm import tqdm
from six import iteritems
from .utils import get_parameter_hash, get_class_inheritors
from .decorators import before_and_after_function_wrapper
from .files import TextFile, ParameterFile, ParameterListFile, AudioFile
from .containers import DottedDict
from .metadata import MetaDataContainer, MetaDataItem
def dataset_list(data_path, group=None):
"""List of datasets available
Parameters
----------
data_path : str
Base path for the datasets
group : str
Group label for the datasets, currently supported ['acoustic scene', 'sound event', 'audio tagging']
Returns
-------
str
Multi line string containing dataset table
"""
output = ''
output += ' Dataset list\n'
output += ' {class_name:<45s} | {group:20s} | {valid:5s} | {files:10s} |\n'.format(
class_name='Class Name',
group='Group',
valid='Valid',
files='Files'
)
output += ' {class_name:<45s} + {group:20s} + {valid:5s} + {files:10s} +\n'.format(
class_name='-' * 45,
group='-' * 20,
valid='-'*5,
files='-'*10
)
def get_empty_row():
return ' {class_name:<45s} | {group:20s} | {valid:5s} | {files:10s} |\n'.format(
class_name='',
group='',
valid='',
files=''
)
def get_row(d):
file_count = 0
if d.meta_container.exists():
file_count = len(d.meta)
return ' {class_name:<45s} | {group:20s} | {valid:5s} | {files:10s} |\n'.format(
class_name=d.__class__.__name__,
group=d.dataset_group,
valid='Yes' if d.check_filelist() else 'No',
files=str(file_count) if file_count else ''
)
if not group or group == 'acoustic scene':
for dataset_class in get_class_inheritors(AcousticSceneDataset):
d = dataset_class(data_path=data_path)
output += get_row(d)
if not group or group == 'sound event':
for dataset_class in get_class_inheritors(SoundEventDataset):
d = dataset_class(data_path=data_path)
output += get_row(d)
if not group or group == 'audio tagging':
for dataset_class in get_class_inheritors(AudioTaggingDataset):
d = dataset_class(data_path=data_path)
output += get_row(d)
return output
def dataset_factory(*args, **kwargs):
"""Factory to get correct dataset class based on name
Parameters
----------
dataset_class_name : str
Class name
Default value "None"
Raises
------
NameError
Class does not exists
Returns
-------
Dataset class
"""
dataset_class_name = kwargs.get('dataset_class_name', None)
try:
return eval(dataset_class_name)(*args, **kwargs)
except NameError:
message = '{name}: No valid dataset given [{dataset_class_name}]'.format(
name='dataset_factory',
dataset_class_name=dataset_class_name
)
logging.getLogger('dataset_factory').exception(message)
raise NameError(message)
class Dataset(object):
"""Dataset base class
The specific dataset classes are inherited from this class, and only needed methods are reimplemented.
"""
def __init__(self, *args, **kwargs):
"""Constructor
Parameters
----------
name : str
storage_name : str
data_path : str
Basepath where the dataset is stored.
(Default value='data')
logger : logger
Instance of logging
Default value "none"
show_progress_in_console : bool
Show progress in console.
Default value "True"
log_system_progress : bool
Show progress in log.
Default value "False"
use_ascii_progress_bar : bool
Show progress bar using ASCII characters. Use this if your console does not support UTF-8 characters.
Default value "False"
"""
self.logger = kwargs.get('logger') or logging.getLogger(__name__)
self.disable_progress_bar = not kwargs.get('show_progress_in_console', True)
self.log_system_progress = kwargs.get('log_system_progress', False)
self.use_ascii_progress_bar = kwargs.get('use_ascii_progress_bar', True)
# Dataset name
self.name = kwargs.get('name', 'dataset')
# Folder name for dataset
self.storage_name = kwargs.get('storage_name', 'dataset')
# Path to the dataset
self.local_path = os.path.join(kwargs.get('data_path', 'data'), self.storage_name)
# Evaluation setup folder
self.evaluation_setup_folder = kwargs.get('evaluation_setup_folder', 'evaluation_setup')
# Path to the folder containing evaluation setup files
self.evaluation_setup_path = os.path.join(self.local_path, self.evaluation_setup_folder)
# Meta data file, csv-format
self.meta_filename = kwargs.get('meta_filename', 'meta.txt')
# Path to meta data file
self.meta_container = MetaDataContainer(filename=os.path.join(self.local_path, self.meta_filename))
if self.meta_container.exists():
self.meta_container.load()
# Error meta data file, csv-format
self.error_meta_filename = kwargs.get('error_meta_filename', 'error.txt')
# Path to error meta data file
self.error_meta_file = os.path.join(self.local_path, self.error_meta_filename)
# Hash file to detect removed or added files
self.filelisthash_filename = kwargs.get('filelisthash_filename', 'filelist.python.hash')
# Dirs to be excluded when calculating filelist hash
self.filelisthash_exclude_dirs = kwargs.get('filelisthash_exclude_dirs', [])
# Number of evaluation folds
self.crossvalidation_folds = 1
# List containing dataset package items
# Define this in the inherited class.
# Format:
# {
# 'remote_package': download_url,
# 'local_package': os.path.join(self.local_path, 'name_of_downloaded_package'),
# 'local_audio_path': os.path.join(self.local_path, 'name_of_folder_containing_audio_files'),
# }
self.package_list = []
# List of audio files
self.files = None
# List of audio error meta data dict
self.error_meta_data = None
# Training meta data for folds
self.crossvalidation_data_train = {}
# Testing meta data for folds
self.crossvalidation_data_test = {}
# Evaluation meta data for folds
self.crossvalidation_data_eval = {}
# Recognized audio extensions
self.audio_extensions = {'wav', 'flac'}
self.default_audio_extension = 'wav'
# Reference data presence flag, by default dataset should have reference data present.
# However, some evaluation dataset might not have
self.reference_data_present = True
# Info fields for dataset
self.authors = ''
self.name_remote = ''
self.url = ''
self.audio_source = ''
self.audio_type = ''
self.recording_device_model = ''
self.microphone_model = ''
def initialize(self):
# Create the dataset path if does not exist
if not os.path.isdir(self.local_path):
os.makedirs(self.local_path)
if not self.check_filelist():
self.download_packages()
self.extract()
self._save_filelist_hash()
return self
def show_info(self):
DottedDict(self.dataset_meta).show()
@property
def audio_files(self):
"""Get all audio files in the dataset
Parameters
----------
Returns
-------
filelist : list
File list with absolute paths
"""
if self.files is None:
self.files = []
for item in self.package_list:
path = item['local_audio_path']
if path:
l = os.listdir(path)
for f in l:
file_name, file_extension = os.path.splitext(f)
if file_extension[1:] in self.audio_extensions:
if os.path.abspath(os.path.join(path, f)) not in self.files:
self.files.append(os.path.abspath(os.path.join(path, f)))
self.files.sort()
return self.files
@property
def audio_file_count(self):
"""Get number of audio files in dataset
Parameters
----------
Returns
-------
filecount : int
Number of audio files
"""
return len(self.audio_files)
@property
def meta(self):
"""Get meta data for dataset. If not already read from disk, data is read and returned.
Parameters
----------
Returns
-------
meta_container : list
List containing meta data as dict.
Raises
-------
IOError
meta file not found.
"""
if self.meta_container.empty():
if self.meta_container.exists():
self.meta_container.load()
else:
message = '{name}: Meta file not found [{filename}]'.format(
name=self.__class__.__name__,
filename=self.meta_container.filename
)
self.logger.exception(message)
raise IOError(message)
return self.meta_container
@property
def meta_count(self):
"""Number of meta data items.
Parameters
----------
Returns
-------
meta_item_count : int
Meta data item count
"""
return len(self.meta_container)
@property
def error_meta(self):
"""Get audio error meta data for dataset. If not already read from disk, data is read and returned.
Parameters
----------
Raises
-------
IOError:
audio error meta file not found.
Returns
-------
error_meta_data : list
List containing audio error meta data as dict.
"""
if self.error_meta_data is None:
self.error_meta_data = MetaDataContainer(filename=self.error_meta_file)
if self.error_meta_data.exists():
self.error_meta_data.load()
else:
message = '{name}: Error meta file not found [{filename}]'.format(name=self.__class__.__name__,
filename=self.error_meta_file)
self.logger.exception(message)
raise IOError(message)
return self.error_meta_data
def error_meta_count(self):
"""Number of error meta data items.
Parameters
----------
Returns
-------
meta_item_count : int
Meta data item count
"""
return len(self.error_meta)
@property
def fold_count(self):
"""Number of fold in the evaluation setup.
Parameters
----------
Returns
-------
fold_count : int
Number of folds
"""
return self.crossvalidation_folds
@property
def scene_labels(self):
"""List of unique scene labels in the meta data.
Parameters
----------
Returns
-------
labels : list
List of scene labels in alphabetical order.
"""
return self.meta_container.unique_scene_labels
@property
def scene_label_count(self):
"""Number of unique scene labels in the meta data.
Parameters
----------
Returns
-------
scene_label_count : int
Number of unique scene labels.
"""
return self.meta_container.scene_label_count
def event_labels(self):
"""List of unique event labels in the meta data.
Parameters
----------
Returns
-------
labels : list
List of event labels in alphabetical order.
"""
return self.meta_container.unique_event_labels
@property
def event_label_count(self):
"""Number of unique event labels in the meta data.
Parameters
----------
Returns
-------
event_label_count : int
Number of unique event labels
"""
return self.meta_container.event_label_count
@property
def audio_tags(self):
"""List of unique audio tags in the meta data.
Parameters
----------
Returns
-------
labels : list
List of audio tags in alphabetical order.
"""
tags = []
for item in self.meta:
if 'tags' in item:
for tag in item['tags']:
if tag and tag not in tags:
tags.append(tag)
tags.sort()
return tags
@property
def audio_tag_count(self):
"""Number of unique audio tags in the meta data.
Parameters
----------
Returns
-------
audio_tag_count : int
Number of unique audio tags
"""
return len(self.audio_tags)
def __getitem__(self, i):
"""Getting meta data item
Parameters
----------
i : int
item id
Returns
-------
meta_data : dict
Meta data item
"""
if i < len(self.meta_container):
return self.meta_container[i]
else:
return None
def __iter__(self):
"""Iterator for meta data items
Parameters
----------
Nothing
Returns
-------
Nothing
"""
i = 0
meta = self[i]
# yield window while it's valid
while meta is not None:
yield meta
# get next item
i += 1
meta = self[i]
def download_packages(self):
"""Download dataset packages over the internet to the local path
Parameters
----------
Returns
-------
Nothing
Raises
-------
IOError
Download failed.
"""
try:
from urllib.request import urlretrieve
except ImportError:
from urllib import urlretrieve
# Set socket timeout
socket.setdefaulttimeout(120)
item_progress = tqdm(self.package_list,
desc="{0: <25s}".format('Download package list'),
file=sys.stdout,
leave=False,
disable=self.disable_progress_bar,
ascii=self.use_ascii_progress_bar)
for item in item_progress:
try:
if item['remote_package'] and not os.path.isfile(item['local_package']):
def progress_hook(t):
"""
Wraps tqdm instance. Don't forget to close() or __exit__()
the tqdm instance once you're done with it (easiest using `with` syntax).
"""
last_b = [0]
def inner(b=1, bsize=1, tsize=None):
"""
b : int, optional
Number of blocks just transferred [default: 1].
bsize : int, optional
Size of each block (in tqdm units) [default: 1].
tsize : int, optional
Total size (in tqdm units). If [default: None] remains unchanged.
"""
if tsize is not None:
t.total = tsize
t.update((b - last_b[0]) * bsize)
last_b[0] = b
return inner
remote_file = item['remote_package']
tmp_file = os.path.join(self.local_path, 'tmp_file')
with tqdm(desc="{0: >25s}".format(os.path.splitext(remote_file.split('/')[-1])[0]),
file=sys.stdout,
unit='B',
unit_scale=True,
miniters=1,
leave=False,
disable=self.disable_progress_bar,
ascii=self.use_ascii_progress_bar) as t:
local_filename, headers = urlretrieve(
remote_file,
filename=tmp_file,
reporthook=progress_hook(t),
data=None
)
os.rename(tmp_file, item['local_package'])
except Exception as e:
message = '{name}: Download failed [{filename}] [{errno}: {strerror}]'.format(
name=self.__class__.__name__,
filename=item['remote_package'],
errno=e.errno if hasattr(e, 'errno') else '',
strerror=e.strerror if hasattr(e, 'strerror') else '',
)
self.logger.exception(message)
raise
@before_and_after_function_wrapper
def extract(self):
"""Extract the dataset packages
Parameters
----------
Returns
-------
Nothing
"""
item_progress = tqdm(self.package_list,
desc="{0: <25s}".format('Extract packages'),
file=sys.stdout,
leave=False,
disable=self.disable_progress_bar,
ascii=self.use_ascii_progress_bar)
for item_id, item in enumerate(item_progress):
if self.log_system_progress:
self.logger.info(' {title:<15s} [{item_id:d}/{total:d}] {package:<30s}'.format(
title='Extract packages ',
item_id=item_id,
total=len(item_progress),
package=item['local_package'])
)
if item['local_package'] and os.path.isfile(item['local_package']):
if item['local_package'].endswith('.zip'):
with zipfile.ZipFile(item['local_package'], "r") as z:
# Trick to omit first level folder
parts = []
for name in z.namelist():
if not name.endswith('/'):
parts.append(name.split('/')[:-1])
prefix = os.path.commonprefix(parts) or ''
if prefix:
if len(prefix) > 1:
prefix_ = list()
prefix_.append(prefix[0])
prefix = prefix_
prefix = '/'.join(prefix) + '/'
offset = len(prefix)
# Start extraction
members = z.infolist()
file_count = 1
progress = tqdm(members,
desc="{0: <25s}".format('Extract'),
file=sys.stdout,
leave=False,
disable=self.disable_progress_bar,
ascii=self.use_ascii_progress_bar)
for i, member in enumerate(progress):
if self.log_system_progress:
self.logger.info(' {title:<15s} [{item_id:d}/{total:d}] {file:<30s}'.format(
title='Extract ',
item_id=i,
total=len(progress),
file=member.filename)
)
if len(member.filename) > offset:
member.filename = member.filename[offset:]
progress.set_description("{0: >35s}".format(member.filename.split('/')[-1]))
progress.update()
if not os.path.isfile(os.path.join(self.local_path, member.filename)):
try:
z.extract(member, self.local_path)
except KeyboardInterrupt:
# Delete latest file, since most likely it was not extracted fully
os.remove(os.path.join(self.local_path, member.filename))
# Quit
sys.exit()
file_count += 1
elif item['local_package'].endswith('.tar.gz'):
tar = tarfile.open(item['local_package'], "r:gz")
progress = tqdm(tar,
desc="{0: <25s}".format('Extract'),
file=sys.stdout,
leave=False,
disable=self.disable_progress_bar,
ascii=self.use_ascii_progress_bar)
for i, tar_info in enumerate(progress):
if self.log_system_progress:
self.logger.info(' {title:<15s} [{item_id:d}/{total:d}] {file:<30s}'.format(
title='Extract ',
item_id=i,
total=len(progress),
file=tar_info.name)
)
if not os.path.isfile(os.path.join(self.local_path, tar_info.name)):
tar.extract(tar_info, self.local_path)
tar.members = []
tar.close()
def _get_filelist(self, exclude_dirs=None):
"""List of files under local_path
Parameters
----------
exclude_dirs : list of str
List of directories to be excluded
Default value "[]"
Returns
-------
filelist: list
File list
"""
if exclude_dirs is None:
exclude_dirs = []
filelist = []
for path, subdirs, files in os.walk(self.local_path):
for name in files:
if os.path.splitext(name)[1] != os.path.splitext(self.filelisthash_filename)[1] and os.path.split(path)[1] not in exclude_dirs:
filelist.append(os.path.join(path, name))
return sorted(filelist)
def check_filelist(self):
"""Generates hash from file list and check does it matches with one saved in filelist.hash.
If some files have been deleted or added, checking will result False.
Parameters
----------
Returns
-------
result: bool
Result
"""
if os.path.isfile(os.path.join(self.local_path, self.filelisthash_filename)):
old_hash_value = TextFile(filename=os.path.join(self.local_path, self.filelisthash_filename)).load()[0]
file_list = self._get_filelist(exclude_dirs=self.filelisthash_exclude_dirs)
new_hash_value = get_parameter_hash(file_list)
if old_hash_value != new_hash_value:
return False
else:
return True
else:
return False
def _save_filelist_hash(self):
"""Generates file list hash, and saves it as filelist.hash under local_path.
Parameters
----------
Nothing
Returns
-------
Nothing
"""
filelist = self._get_filelist()
hash_value = get_parameter_hash(filelist)
TextFile([hash_value], filename=os.path.join(self.local_path, self.filelisthash_filename)).save()
def train(self, fold=0):
"""List of training items.
Parameters
----------
fold : int > 0 [scalar]
Fold id, if zero all meta data is returned.
(Default value=0)
Returns
-------
list : list of dicts
List containing all meta data assigned to training set for given fold.
"""
if fold not in self.crossvalidation_data_train:
self.crossvalidation_data_train[fold] = []
if fold > 0:
self.crossvalidation_data_train[fold] = MetaDataContainer(
filename=self._get_evaluation_setup_filename(setup_part='train', fold=fold)).load()
else:
self.crossvalidation_data_train[0] = self.meta_container
for item in self.crossvalidation_data_train[fold]:
item['file'] = self.relative_to_absolute_path(item['file'])
return self.crossvalidation_data_train[fold]
def test(self, fold=0):
"""List of testing items.
Parameters
----------
fold : int > 0 [scalar]
Fold id, if zero all meta data is returned.
(Default value=0)
Returns
-------
list : list of dicts
List containing all meta data assigned to testing set for given fold.
"""
if fold not in self.crossvalidation_data_test:
self.crossvalidation_data_test[fold] = []
if fold > 0:
self.crossvalidation_data_test[fold] = MetaDataContainer(
filename=self._get_evaluation_setup_filename(setup_part='test', fold=fold)).load()
for item in self.crossvalidation_data_test[fold]:
item['file'] = self.relative_to_absolute_path(item['file'])
else:
self.crossvalidation_data_test[fold] = self.meta_container
for item in self.crossvalidation_data_test[fold]:
item['file'] = self.relative_to_absolute_path(item['file'])
return self.crossvalidation_data_test[fold]
def eval(self, fold=0):
"""List of evaluation items.
Parameters
----------
fold : int > 0 [scalar]
Fold id, if zero all meta data is returned.
(Default value=0)
Returns
-------
list : list of dicts
List containing all meta data assigned to testing set for given fold.
"""
if fold not in self.crossvalidation_data_eval:
self.crossvalidation_data_eval[fold] = []
if fold > 0:
self.crossvalidation_data_eval[fold] = MetaDataContainer(
filename=self._get_evaluation_setup_filename(setup_part='evaluate', fold=fold)).load()
else:
self.crossvalidation_data_eval[fold] = self.meta_container
for item in self.crossvalidation_data_eval[fold]:
item['file'] = self.relative_to_absolute_path(item['file'])
return self.crossvalidation_data_eval[fold]
def folds(self, mode='folds'):
"""List of fold ids
Parameters
----------
mode : str {'folds','full'}
Fold setup type, possible values are 'folds' and 'full'. In 'full' mode fold number is set 0 and all data is used for training.
(Default value=folds)
Returns
-------
list : list of integers
Fold ids
"""
if mode == 'folds':
return range(1, self.crossvalidation_folds + 1)
elif mode == 'full':
return [0]
def file_meta(self, filename):
"""Meta data for given file
Parameters
----------
filename : str
File name
Returns
-------
list : list of dicts
List containing all meta data related to given file.
"""
return self.meta_container.filter(filename=self.absolute_to_relative(filename))
def file_error_meta(self, filename):
"""Error meta data for given file
Parameters
----------
filename : str
File name
Returns
-------
list : list of dicts
List containing all error meta data related to given file.
"""
return self.error_meta.filter(file=self.absolute_to_relative(filename))
def relative_to_absolute_path(self, path):
"""Converts relative path into absolute path.
Parameters
----------
path : str
Relative path
Returns
-------
path : str
Absolute path
"""
return os.path.abspath(os.path.expanduser(os.path.join(self.local_path, path)))
def absolute_to_relative(self, path):
"""Converts absolute path into relative path.
Parameters
----------
path : str
Absolute path
Returns
-------
path : str
Relative path
"""
if path.startswith(os.path.abspath(self.local_path)):
return os.path.relpath(path, self.local_path)
else:
return path
def _get_evaluation_setup_filename(self, setup_part='train', fold=None, scene_label=None, file_extension='txt'):
parts = []
if scene_label:
parts.append(scene_label)
if fold:
parts.append('fold' + str(fold))
if setup_part == 'train':
parts.append('train')
elif setup_part == 'test':
parts.append('test')
elif setup_part == 'evaluate':
parts.append('evaluate')
return os.path.join(self.evaluation_setup_path, '_'.join(parts) + '.' + file_extension)
class AcousticSceneDataset(Dataset):
def __init__(self, *args, **kwargs):
super(AcousticSceneDataset, self).__init__(*args, **kwargs)
self.dataset_group = 'base class'
class SoundEventDataset(Dataset):
def __init__(self, *args, **kwargs):
super(SoundEventDataset, self).__init__(*args, **kwargs)
self.dataset_group = 'base class'
def event_label_count(self, scene_label=None):
"""Number of unique scene labels in the meta data.
Parameters
----------
scene_label : str
Scene label
Default value "None"
Returns
-------
scene_label_count : int
Number of unique scene labels.
"""
return len(self.event_labels(scene_label=scene_label))
def event_labels(self, scene_label=None):
"""List of unique event labels in the meta data.
Parameters
----------
scene_label : str
Scene label
Default value "None"
Returns
-------
labels : list
List of event labels in alphabetical order.
"""
if scene_label is not None:
labels = self.meta_container.filter(scene_label=scene_label).unique_event_labels
else:
labels = self.meta_container.unique_event_labels
labels.sort()
return labels
def train(self, fold=0, scene_label=None):
"""List of training items.
Parameters
----------
fold : int > 0 [scalar]
Fold id, if zero all meta data is returned.
(Default value=0)
scene_label : str
Scene label
Default value "None"
Returns
-------
list : list of dicts
List containing all meta data assigned to training set for given fold.
"""
if fold not in self.crossvalidation_data_train:
self.crossvalidation_data_train[fold] = {}
for scene_label_ in self.scene_labels:
if scene_label_ not in self.crossvalidation_data_train[fold]:
self.crossvalidation_data_train[fold][scene_label_] = MetaDataContainer()
if fold > 0:
self.crossvalidation_data_train[fold][scene_label_] = MetaDataContainer(
filename=self._get_evaluation_setup_filename(setup_part='train', fold=fold, scene_label=scene_label_)).load()
else:
self.crossvalidation_data_train[0][scene_label_] = self.meta_container.filter(
scene_label=scene_label_
)
for item in self.crossvalidation_data_train[fold][scene_label_]:
item['file'] = self.relative_to_absolute_path(item['file'])
if scene_label:
return self.crossvalidation_data_train[fold][scene_label]
else:
data = MetaDataContainer()
for scene_label_ in self.scene_labels:
data += self.crossvalidation_data_train[fold][scene_label_]
return data
def test(self, fold=0, scene_label=None):
"""List of testing items.
Parameters
----------
fold : int > 0 [scalar]
Fold id, if zero all meta data is returned.
(Default value=0)
scene_label : str
Scene label
Default value "None"
Returns
-------
list : list of dicts
List containing all meta data assigned to testing set for given fold.
"""
if fold not in self.crossvalidation_data_test:
self.crossvalidation_data_test[fold] = {}
for scene_label_ in self.scene_labels:
if scene_label_ not in self.crossvalidation_data_test[fold]:
self.crossvalidation_data_test[fold][scene_label_] = MetaDataContainer()
if fold > 0:
self.crossvalidation_data_test[fold][scene_label_] = MetaDataContainer(
filename=self._get_evaluation_setup_filename(
setup_part='test', fold=fold, scene_label=scene_label_)
).load()
else:
self.crossvalidation_data_test[0][scene_label_] = self.meta_container.filter(
scene_label=scene_label_
)
for item in self.crossvalidation_data_test[fold][scene_label_]:
item['file'] = self.relative_to_absolute_path(item['file'])
if scene_label:
return self.crossvalidation_data_test[fold][scene_label]
else:
data = MetaDataContainer()
for scene_label_ in self.scene_labels:
data += self.crossvalidation_data_test[fold][scene_label_]
return data
class SyntheticSoundEventDataset(SoundEventDataset):
def __init__(self, *args, **kwargs):
super(SyntheticSoundEventDataset, self).__init__(*args, **kwargs)
self.dataset_group = 'base class'
def initialize(self):
# Create the dataset path if does not exist
if not os.path.isdir(self.local_path):
os.makedirs(self.local_path)
if not self.check_filelist():
self.download_packages()
self.extract()
self._save_filelist_hash()
self.synthesize()
return self
@before_and_after_function_wrapper
def synthesize(self):
pass
class AudioTaggingDataset(Dataset):
def __init__(self, *args, **kwargs):
super(AudioTaggingDataset, self).__init__(*args, **kwargs)
self.dataset_group = 'base class'
# =====================================================
# DCASE 2017
# =====================================================
class TUTAcousticScenes_2017_DevelopmentSet(AcousticSceneDataset):
"""TUT Acoustic scenes 2017 development dataset
This dataset is used in DCASE2017 - Task 1, Acoustic scene classification
"""
def __init__(self, *args, **kwargs):
kwargs['storage_name'] = kwargs.get('storage_name', 'TUT-acoustic-scenes-2017-development')
super(TUTAcousticScenes_2017_DevelopmentSet, self).__init__(*args, **kwargs)
self.dataset_group = 'acoustic scene'
self.dataset_meta = {
'authors': '<NAME>, <NAME>, and <NAME>',
'name_remote': 'TUT Acoustic Scenes 2017, development dataset',
'url': None,
'audio_source': 'Field recording',
'audio_type': 'Natural',
'recording_device_model': 'Roland Edirol R-09',
'microphone_model': 'Soundman OKM II Klassik/studio A3 electret microphone',
}
self.crossvalidation_folds = 4
self.package_list = [
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400515/files/TUT-acoustic-scenes-2017-development.doc.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2017-development.doc.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400515/files/TUT-acoustic-scenes-2017-development.meta.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2017-development.meta.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400515/files/TUT-acoustic-scenes-2017-development.error.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2017-development.error.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400515/files/TUT-acoustic-scenes-2017-development.audio.1.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2017-development.audio.1.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400515/files/TUT-acoustic-scenes-2017-development.audio.2.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2017-development.audio.2.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400515/files/TUT-acoustic-scenes-2017-development.audio.3.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2017-development.audio.3.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400515/files/TUT-acoustic-scenes-2017-development.audio.4.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2017-development.audio.4.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400515/files/TUT-acoustic-scenes-2017-development.audio.5.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2017-development.audio.5.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400515/files/TUT-acoustic-scenes-2017-development.audio.6.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2017-development.audio.6.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400515/files/TUT-acoustic-scenes-2017-development.audio.7.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2017-development.audio.7.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400515/files/TUT-acoustic-scenes-2017-development.audio.8.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2017-development.audio.8.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400515/files/TUT-acoustic-scenes-2017-development.audio.9.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2017-development.audio.9.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400515/files/TUT-acoustic-scenes-2017-development.audio.10.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2017-development.audio.10.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
}
]
def _after_extract(self, to_return=None):
"""After dataset packages are downloaded and extracted, meta-files are checked.
Parameters
----------
nothing
Returns
-------
nothing
"""
if not self.meta_container.exists():
meta_data = collections.OrderedDict()
for fold in range(1, self.crossvalidation_folds):
# Read train files in
fold_data = MetaDataContainer(
filename=os.path.join(self.evaluation_setup_path, 'fold' + str(fold) + '_train.txt')).load()
fold_data += MetaDataContainer(
filename=os.path.join(self.evaluation_setup_path, 'fold' + str(fold) + '_evaluate.txt')).load()
for item in fold_data:
if item['file'] not in meta_data:
raw_path, raw_filename = os.path.split(item['file'])
relative_path = self.absolute_to_relative(raw_path)
location_id = raw_filename.split('_')[0]
item['file'] = os.path.join(relative_path, raw_filename)
item['identifier'] = location_id
meta_data[item['file']] = item
self.meta_container.update(meta_data.values())
self.meta_container.save()
else:
self.meta_container.load()
def train(self, fold=0):
"""List of training items.
Parameters
----------
fold : int > 0 [scalar]
Fold id, if zero all meta data is returned.
(Default value=0)
Returns
-------
list : list of dicts
List containing all meta data assigned to training set for given fold.
"""
if fold not in self.crossvalidation_data_train:
self.crossvalidation_data_train[fold] = []
if fold > 0:
self.crossvalidation_data_train[fold] = MetaDataContainer(
filename=os.path.join(self.evaluation_setup_path, 'fold' + str(fold) + '_train.txt')).load()
for item in self.crossvalidation_data_train[fold]:
item['file'] = self.relative_to_absolute_path(item['file'])
raw_path, raw_filename = os.path.split(item['file'])
location_id = raw_filename.split('_')[0]
item['identifier'] = location_id
else:
self.crossvalidation_data_train[0] = self.meta_container
return self.crossvalidation_data_train[fold]
class TUTAcousticScenes_2017_EvaluationSet(AcousticSceneDataset):
"""TUT Acoustic scenes 2017 evaluation dataset
This dataset is used in DCASE2017 - Task 1, Acoustic scene classification
"""
def __init__(self, *args, **kwargs):
kwargs['storage_name'] = kwargs.get('storage_name', 'TUT-acoustic-scenes-2017-evaluation')
super(TUTAcousticScenes_2017_EvaluationSet, self).__init__(*args, **kwargs)
self.reference_data_present = False
self.dataset_group = 'acoustic scene'
self.dataset_meta = {
'authors': '<NAME>, <NAME>, and <NAME>',
'name_remote': 'TUT Acoustic Scenes 2017, development dataset',
'url': None,
'audio_source': 'Field recording',
'audio_type': 'Natural',
'recording_device_model': 'Roland Edirol R-09',
'microphone_model': 'Soundman OKM II Klassik/studio A3 electret microphone',
}
self.crossvalidation_folds = 1
self.package_list = [
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio'),
}
]
def _after_extract(self, to_return=None):
"""After dataset packages are downloaded and extracted, meta-files are checked.
Parameters
----------
nothing
Returns
-------
nothing
"""
if not self.meta_container.exists():
meta_data = collections.OrderedDict()
for fold in range(1, self.crossvalidation_folds):
# Read train files in
fold_data = MetaDataContainer(
filename=os.path.join(self.evaluation_setup_path, 'fold' + str(fold) + '_test.txt')).load()
for item in fold_data:
if item['file'] not in meta_data:
raw_path, raw_filename = os.path.split(item['file'])
relative_path = self.absolute_to_relative(raw_path)
location_id = raw_filename.split('_')[0]
item['file'] = os.path.join(relative_path, raw_filename)
meta_data[item['file']] = item
self.meta_container.update(meta_data.values())
self.meta_container.save()
else:
self.meta_container.load()
def train(self, fold=0):
return []
def test(self, fold=0):
return []
class TUTRareSoundEvents_2017_DevelopmentSet(SyntheticSoundEventDataset):
"""TUT Acoustic scenes 2017 development dataset
This dataset is used in DCASE2017 - Task 1, Acoustic scene classification
"""
def __init__(self, *args, **kwargs):
kwargs['storage_name'] = kwargs.get('storage_name', 'TUT-rare-sound-events-2017-development')
kwargs['filelisthash_exclude_dirs'] = kwargs.get('filelisthash_exclude_dirs', ['generated_data'])
self.synth_parameters = DottedDict({
'train': {
'seed': 42,
'mixture': {
'fs': 44100,
'bitdepth': 24,
'length_seconds': 30.0,
'anticlipping_factor': 0.2,
},
'event_presence_prob': 0.5,
'mixtures_per_class': 500,
'ebr_list': [-6, 0, 6],
},
'test': {
'seed': 42,
'mixture': {
'fs': 44100,
'bitdepth': 24,
'length_seconds': 30.0,
'anticlipping_factor': 0.2,
},
'event_presence_prob': 0.5,
'mixtures_per_class': 500,
'ebr_list': [-6, 0, 6],
}
})
# Override synth parameters
if kwargs.get('synth_parameters'):
self.synth_parameters.merge(kwargs.get('synth_parameters'))
# Meta filename depends on synth parameters
meta_filename = 'meta_'+self.synth_parameters.get_hash_for_path()+'.txt'
kwargs['meta_filename'] = kwargs.get('meta_filename', os.path.join('generated_data', meta_filename))
# Initialize baseclass
super(TUTRareSoundEvents_2017_DevelopmentSet, self).__init__(*args, **kwargs)
self.dataset_group = 'sound event'
self.dataset_meta = {
'authors': '<NAME>, <NAME>, <NAME>, and <NAME>',
'name_remote': 'TUT Rare Sound Events 2017, development dataset',
'url': None,
'audio_source': 'Synthetic',
'audio_type': 'Natural',
'recording_device_model': 'Unknown',
'microphone_model': 'Unknown',
}
self.crossvalidation_folds = 1
self.package_list = [
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'http://www.cs.tut.fi/sgn/arg/dcase2017/data/TUT-rare-sound-events-2017-development/TUT-rare-sound-events-2017-development.doc.zip',
'local_package': os.path.join(self.local_path, 'TUT-rare-sound-events-2017-development.doc.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'http://www.cs.tut.fi/sgn/arg/dcase2017/data/TUT-rare-sound-events-2017-development/TUT-rare-sound-events-2017-development.code.zip',
'local_package': os.path.join(self.local_path, 'TUT-rare-sound-events-2017-development.code.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'http://www.cs.tut.fi/sgn/arg/dcase2017/data/TUT-rare-sound-events-2017-development/TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.1.zip',
'local_package': os.path.join(self.local_path, 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.1.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'http://www.cs.tut.fi/sgn/arg/dcase2017/data/TUT-rare-sound-events-2017-development/TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.2.zip',
'local_package': os.path.join(self.local_path, 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.2.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'http://www.cs.tut.fi/sgn/arg/dcase2017/data/TUT-rare-sound-events-2017-development/TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.3.zip',
'local_package': os.path.join(self.local_path, 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.3.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'http://www.cs.tut.fi/sgn/arg/dcase2017/data/TUT-rare-sound-events-2017-development/TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.4.zip',
'local_package': os.path.join(self.local_path, 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.4.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'http://www.cs.tut.fi/sgn/arg/dcase2017/data/TUT-rare-sound-events-2017-development/TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.5.zip',
'local_package': os.path.join(self.local_path, 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.5.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'http://www.cs.tut.fi/sgn/arg/dcase2017/data/TUT-rare-sound-events-2017-development/TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.6.zip',
'local_package': os.path.join(self.local_path, 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.6.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'http://www.cs.tut.fi/sgn/arg/dcase2017/data/TUT-rare-sound-events-2017-development/TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.7.zip',
'local_package': os.path.join(self.local_path, 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.7.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'http://www.cs.tut.fi/sgn/arg/dcase2017/data/TUT-rare-sound-events-2017-development/TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.8.zip',
'local_package': os.path.join(self.local_path, 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.8.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'http://www.cs.tut.fi/sgn/arg/dcase2017/data/TUT-rare-sound-events-2017-development/TUT-rare-sound-events-2017-development.source_data_events.zip',
'local_package': os.path.join(self.local_path, 'TUT-rare-sound-events-2017-development.source_data_events.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
}
]
@property
def event_labels(self, scene_label=None):
"""List of unique event labels in the meta data.
Parameters
----------
Returns
-------
labels : list
List of event labels in alphabetical order.
"""
labels = ['babycry', 'glassbreak', 'gunshot']
labels.sort()
return labels
def train(self, fold=0, event_label=None):
"""List of training items.
Parameters
----------
fold : int > 0 [scalar]
Fold id, if zero all meta data is returned.
(Default value=0)
event_label : str
Event label
Default value "None"
Returns
-------
list : list of dicts
List containing all meta data assigned to training set for given fold.
"""
if fold not in self.crossvalidation_data_train:
self.crossvalidation_data_train[fold] = {}
for event_label_ in self.event_labels:
if event_label_ not in self.crossvalidation_data_train[fold]:
self.crossvalidation_data_train[fold][event_label_] = MetaDataContainer()
if fold == 1:
params_hash = self.synth_parameters.get_hash_for_path('train')
mixture_meta_path = os.path.join(
self.local_path,
'generated_data',
'mixtures_devtrain_' + params_hash,
'meta'
)
event_list_filename = os.path.join(
mixture_meta_path,
'event_list_devtrain_' + event_label_ + '.csv'
)
self.crossvalidation_data_train[fold][event_label_] = MetaDataContainer(
filename=event_list_filename).load()
elif fold == 0:
params_hash = self.synth_parameters.get_hash_for_path('train')
mixture_meta_path = os.path.join(
self.local_path,
'generated_data',
'mixtures_devtrain_' + params_hash,
'meta'
)
event_list_filename = os.path.join(
mixture_meta_path,
'event_list_devtrain_' + event_label_ + '.csv'
)
# Load train files
self.crossvalidation_data_train[0][event_label_] = MetaDataContainer(
filename=event_list_filename).load()
params_hash = self.synth_parameters.get_hash_for_path('test')
mixture_meta_path = os.path.join(
self.local_path,
'generated_data',
'mixtures_devtest_' + params_hash,
'meta'
)
event_list_filename = os.path.join(
mixture_meta_path,
'event_list_devtest_' + event_label_ + '.csv'
)
# Load test files
self.crossvalidation_data_train[0][event_label_] += MetaDataContainer(
filename=event_list_filename).load()
for item in self.crossvalidation_data_train[fold][event_label_]:
item['file'] = self.relative_to_absolute_path(item['file'])
if event_label:
return self.crossvalidation_data_train[fold][event_label]
else:
data = MetaDataContainer()
for event_label_ in self.event_labels:
data += self.crossvalidation_data_train[fold][event_label_]
return data
def test(self, fold=0, event_label=None):
"""List of testing items.
Parameters
----------
fold : int > 0 [scalar]
Fold id, if zero all meta data is returned.
(Default value=0)
event_label : str
Event label
Default value "None"
Returns
-------
list : list of dicts
List containing all meta data assigned to testing set for given fold.
"""
if fold not in self.crossvalidation_data_test:
self.crossvalidation_data_test[fold] = {}
for event_label_ in self.event_labels:
if event_label_ not in self.crossvalidation_data_test[fold]:
self.crossvalidation_data_test[fold][event_label_] = MetaDataContainer()
if fold == 1:
params_hash = self.synth_parameters.get_hash_for_path('test')
mixture_meta_path = os.path.join(
self.local_path,
'generated_data',
'mixtures_devtest_' + params_hash,
'meta'
)
event_list_filename = os.path.join(mixture_meta_path, 'event_list_devtest_' + event_label_ + '.csv')
self.crossvalidation_data_test[fold][event_label_] = MetaDataContainer(
filename=event_list_filename
).load()
elif fold == 0:
params_hash = self.synth_parameters.get_hash_for_path('train')
mixture_meta_path = os.path.join(
self.local_path,
'generated_data',
'mixtures_devtrain_' + params_hash,
'meta'
)
event_list_filename = os.path.join(
mixture_meta_path,
'event_list_devtrain_' + event_label_ + '.csv'
)
# Load train files
self.crossvalidation_data_test[0][event_label_] = MetaDataContainer(
filename=event_list_filename
).load()
params_hash = self.synth_parameters.get_hash_for_path('test')
mixture_meta_path = os.path.join(
self.local_path,
'generated_data',
'mixtures_devtest_' + params_hash,
'meta'
)
event_list_filename = os.path.join(
mixture_meta_path,
'event_list_devtest_' + event_label_ + '.csv'
)
# Load test files
self.crossvalidation_data_test[0][event_label_] += MetaDataContainer(
filename=event_list_filename
).load()
for item in self.crossvalidation_data_test[fold][event_label_]:
item['file'] = self.relative_to_absolute_path(item['file'])
if event_label:
return self.crossvalidation_data_test[fold][event_label]
else:
data = MetaDataContainer()
for event_label_ in self.event_labels:
data += self.crossvalidation_data_test[fold][event_label_]
return data
@before_and_after_function_wrapper
def synthesize(self):
subset_map = {'train': 'devtrain',
'test': 'devtest'}
background_audio_path = os.path.join(self.local_path, 'data', 'source_data', 'bgs')
event_audio_path = os.path.join(self.local_path, 'data', 'source_data', 'events')
cv_setup_path = os.path.join(self.local_path, 'data', 'source_data', 'cv_setup')
set_progress = tqdm(['train', 'test'],
desc="{0: <25s}".format('Set'),
file=sys.stdout,
leave=False,
disable=self.disable_progress_bar,
ascii=self.use_ascii_progress_bar)
for subset_label in set_progress:
if self.log_system_progress:
self.logger.info(' {title:<15s} [{subset_label:<30s}]'.format(
title='Set ',
subset_label=subset_label)
)
subset_name_on_disk = subset_map[subset_label]
background_meta = ParameterListFile().load(filename=os.path.join(cv_setup_path, 'bgs_' + subset_name_on_disk + '.yaml'))
event_meta = ParameterFile().load(
filename=os.path.join(cv_setup_path, 'events_' + subset_name_on_disk + '.yaml')
)
params = self.synth_parameters.get_path(subset_label)
params_hash = self.synth_parameters.get_hash_for_path(subset_label)
r = numpy.random.RandomState(params.get('seed', 42))
mixture_path = os.path.join(
self.local_path,
'generated_data',
'mixtures_' + subset_name_on_disk + '_' + params_hash
)
mixture_audio_path = os.path.join(
self.local_path,
'generated_data',
'mixtures_' + subset_name_on_disk + '_' + params_hash,
'audio'
)
mixture_meta_path = os.path.join(
self.local_path,
'generated_data',
'mixtures_' + subset_name_on_disk + '_' + params_hash,
'meta'
)
# Make sure folder exists
if not os.path.isdir(mixture_path):
os.makedirs(mixture_path)
if not os.path.isdir(mixture_audio_path):
os.makedirs(mixture_audio_path)
if not os.path.isdir(mixture_meta_path):
os.makedirs(mixture_meta_path)
class_progress = tqdm(self.event_labels,
desc="{0: <25s}".format('Class'),
file=sys.stdout,
leave=False,
disable=self.disable_progress_bar,
ascii=self.use_ascii_progress_bar)
for class_label in class_progress:
if self.log_system_progress:
self.logger.info(' {title:<15s} [{class_label:<30s}]'.format(
title='Class ',
class_label=class_label)
)
mixture_recipes_filename = os.path.join(
mixture_meta_path,
'mixture_recipes_' + subset_name_on_disk + '_' + class_label + '.yaml'
)
# Generate recipes if not exists
if not os.path.isfile(mixture_recipes_filename):
self._generate_mixture_recipes(
params=params,
class_label=class_label,
subset=subset_name_on_disk,
mixture_recipes_filename=mixture_recipes_filename,
background_meta=background_meta,
event_meta=event_meta[class_label],
background_audio_path=background_audio_path,
event_audio_path=event_audio_path,
r=r
)
mixture_meta = ParameterListFile().load(filename=mixture_recipes_filename)
# Generate mixture signals
item_progress = tqdm(mixture_meta,
desc="{0: <25s}".format('Generate mixture'),
file=sys.stdout,
leave=False,
disable=self.disable_progress_bar,
ascii=self.use_ascii_progress_bar)
for item_id, item in enumerate(item_progress):
if self.log_system_progress:
self.logger.info(' {title:<15s} [{item_id:d}/{total:d}] {file:<30s}'.format(
title='Generate mixture ',
item_id=item_id,
total=len(item_progress),
file=item['mixture_audio_filename'])
)
mixture_file = os.path.join(mixture_audio_path, item['mixture_audio_filename'])
if not os.path.isfile(mixture_file):
mixture = self._synthesize_mixture(
mixture_recipe=item,
params=params,
background_audio_path=background_audio_path,
event_audio_path=event_audio_path
)
audio_container = AudioFile(
data=mixture,
fs=params['mixture']['fs']
)
audio_container.save(
filename=mixture_file,
bitdepth=params['mixture']['bitdepth']
)
# Generate event lists
event_list_filename = os.path.join(
mixture_meta_path,
'event_list_' + subset_name_on_disk + '_' + class_label + '.csv'
)
event_list = MetaDataContainer(filename=event_list_filename)
if not event_list.exists():
item_progress = tqdm(mixture_meta,
desc="{0: <25s}".format('Event list'),
file=sys.stdout,
leave=False,
disable=self.disable_progress_bar,
ascii=self.use_ascii_progress_bar)
for item_id, item in enumerate(item_progress):
if self.log_system_progress:
self.logger.info(' {title:<15s} [{item_id:d}/{total:d}] {file:<30s}'.format(
title='Event list ',
item_id=item_id,
total=len(item_progress),
file=item['mixture_audio_filename'])
)
event_list_item = {
'file': os.path.join(
'generated_data',
'mixtures_' + subset_name_on_disk + '_' + params_hash,
'audio',
item['mixture_audio_filename']
),
}
if item['event_present']:
event_list_item['event_label'] = item['event_class']
event_list_item['event_onset'] = float(item['event_start_in_mixture_seconds'])
event_list_item['event_offset'] = float(item['event_start_in_mixture_seconds'] + item['event_length_seconds'])
event_list.append(MetaDataItem(event_list_item))
event_list.save()
mixture_parameters = os.path.join(mixture_path, 'parameters.yaml')
# Save parameters
if not os.path.isfile(mixture_parameters):
ParameterFile(params).save(filename=mixture_parameters)
if not self.meta_container.exists():
# Collect meta data
meta_data = MetaDataContainer()
for class_label in self.event_labels:
for subset_label, subset_name_on_disk in iteritems(subset_map):
params_hash = self.synth_parameters.get_hash_for_path(subset_label)
mixture_meta_path = os.path.join(
self.local_path,
'generated_data',
'mixtures_' + subset_name_on_disk + '_' + params_hash,
'meta'
)
event_list_filename = os.path.join(
mixture_meta_path,
'event_list_' + subset_name_on_disk + '_' + class_label + '.csv'
)
meta_data += MetaDataContainer(filename=event_list_filename).load()
self.meta_container.update(meta_data)
self.meta_container.save()
def _generate_mixture_recipes(self, params, subset, class_label, mixture_recipes_filename, background_meta,
event_meta, background_audio_path, event_audio_path, r):
try:
from itertools import izip as zip
except ImportError: # will be 3.x series
pass
def get_event_amplitude_scaling_factor(signal, noise, target_snr_db):
"""Get amplitude scaling factor
Different lengths for signal and noise allowed: longer noise assumed to be stationary enough,
and rmse is calculated over the whole signal
Parameters
----------
signal : numpy.ndarray
noise : numpy.ndarray
target_snr_db : float
Returns
-------
float > 0.0
"""
def rmse(y):
"""RMSE"""
return numpy.sqrt(numpy.mean(numpy.abs(y) ** 2, axis=0, keepdims=False))
original_sn_rmse_ratio = rmse(signal) / rmse(noise)
target_sn_rmse_ratio = 10 ** (target_snr_db / float(20))
signal_scaling_factor = target_sn_rmse_ratio / original_sn_rmse_ratio
return signal_scaling_factor
# Internal variables
fs = float(params.get('mixture').get('fs', 44100))
current_class_events = []
# Inject fields to meta data
for event in event_meta:
event['classname'] = class_label
event['audio_filepath'] = os.path.join(class_label, event['audio_filename'])
event['length_seconds'] = numpy.diff(event['segment'])[0]
current_class_events.append(event)
# Randomize order of event and background
events = r.choice(current_class_events,
int(round(params.get('mixtures_per_class') * params.get('event_presence_prob'))))
bgs = r.choice(background_meta, params.get('mixtures_per_class'))
# Event presence flags
event_presence_flags = (numpy.hstack((numpy.ones(len(events)), numpy.zeros(len(bgs) - len(events))))).astype(bool)
event_presence_flags = r.permutation(event_presence_flags)
# Event instance IDs, by default event id set to nan: no event. fill it later with actual event ids when needed
event_instance_ids = numpy.nan * numpy.ones(len(bgs)).astype(int)
event_instance_ids[event_presence_flags] = numpy.arange(len(events))
# Randomize event position inside background
for event in events:
event['offset_seconds'] = (params.get('mixture').get('length_seconds') - event['length_seconds']) * r.rand()
# Get offsets for all mixtures, If no event present, use nans
event_offsets_seconds = numpy.nan * numpy.ones(len(bgs))
event_offsets_seconds[event_presence_flags] = [event['offset_seconds'] for event in events]
# Double-check that we didn't shuffle things wrongly: check that the offset never exceeds bg_len-event_len
checker = [offset + events[int(event_instance_id)]['length_seconds'] for offset, event_instance_id in
zip(event_offsets_seconds[event_presence_flags], event_instance_ids[event_presence_flags])]
assert numpy.max(numpy.array(checker)) < params.get('mixture').get('length_seconds')
# Target EBRs
target_ebrs = -numpy.inf * numpy.ones(len(bgs))
target_ebrs[event_presence_flags] = r.choice(params.get('ebr_list'), size=numpy.sum(event_presence_flags))
# For recipes, we got to provide amplitude scaling factors instead of SNRs: the latter are more ambiguous
# so, go through files, measure levels, calculate scaling factors
mixture_recipes = ParameterListFile()
for mixture_id, (bg, event_presence_flag, event_start_in_mixture_seconds, ebr, event_instance_id) in tqdm(
enumerate(zip(bgs, event_presence_flags, event_offsets_seconds, target_ebrs, event_instance_ids)),
desc="{0: <25s}".format('Generate recipe'),
file=sys.stdout,
leave=False,
total=len(bgs),
disable=self.disable_progress_bar,
ascii=self.use_ascii_progress_bar):
# Read the bgs and events, measure their energies, find amplitude scaling factors
mixture_recipe = {
'bg_path': bg['filepath'],
'bg_classname': bg['classname'],
'event_present': bool(event_presence_flag),
'ebr': float(ebr)
}
if event_presence_flag:
# We have an event assigned
assert not numpy.isnan(event_instance_id)
# Load background and event audio in
bg_audio, fs_bg = AudioFile(fs=params.get('mixture').get('fs')).load(
filename=os.path.join(background_audio_path, bg['filepath'])
)
event_audio, fs_event = AudioFile(fs=params.get('mixture').get('fs')).load(
filename=os.path.join(event_audio_path, events[int(event_instance_id)]['audio_filepath'])
)
assert fs_bg == fs_event, 'Fs mismatch! Expected resampling taken place already'
# Segment onset and offset in samples
segment_start_samples = int(events[int(event_instance_id)]['segment'][0] * fs)
segment_end_samples = int(events[int(event_instance_id)]['segment'][1] * fs)
# Cut event audio
event_audio = event_audio[segment_start_samples:segment_end_samples]
# Let's calculate the levels of bgs also at the location of the event only
eventful_part_of_bg = bg_audio[int(event_start_in_mixture_seconds * fs):int(event_start_in_mixture_seconds * fs + len(event_audio))]
if eventful_part_of_bg.shape[0] == 0:
message = '{name}: Background segment having an event has zero length.'.format(
name=self.__class__.__name__
)
self.logger.exception(message)
raise ValueError(message)
scaling_factor = get_event_amplitude_scaling_factor(event_audio, eventful_part_of_bg, target_snr_db=ebr)
# Store information
mixture_recipe['event_path'] = events[int(event_instance_id)]['audio_filepath']
mixture_recipe['event_class'] = events[int(event_instance_id)]['classname']
mixture_recipe['event_start_in_mixture_seconds'] = float(event_start_in_mixture_seconds)
mixture_recipe['event_length_seconds'] = float(events[int(event_instance_id)]['length_seconds'])
mixture_recipe['scaling_factor'] = float(scaling_factor)
mixture_recipe['segment_start_seconds'] = events[int(event_instance_id)]['segment'][0]
mixture_recipe['segment_end_seconds'] = events[int(event_instance_id)]['segment'][1]
# Generate mixture filename
mixing_param_hash = hashlib.md5(yaml.dump(mixture_recipe)).hexdigest()
mixture_recipe['mixture_audio_filename'] = 'mixture' + '_' + subset + '_' + class_label + '_' + '%03d' % mixture_id + '_' + mixing_param_hash + '.' + self.default_audio_extension
# Generate mixture annotation
if event_presence_flag:
mixture_recipe['annotation_string'] = \
mixture_recipe['mixture_audio_filename'] + '\t' + \
"{0:.14f}".format(mixture_recipe['event_start_in_mixture_seconds']) + '\t' + \
"{0:.14f}".format(mixture_recipe['event_start_in_mixture_seconds'] + mixture_recipe['event_length_seconds']) + '\t' + \
mixture_recipe['event_class']
else:
mixture_recipe['annotation_string'] = mixture_recipe['mixture_audio_filename'] + '\t' + 'None' + '\t0\t30'
# Store mixture recipe
mixture_recipes.append(mixture_recipe)
# Save mixture recipe
mixture_recipes.save(filename=mixture_recipes_filename)
def _synthesize_mixture(self, mixture_recipe, params, background_audio_path, event_audio_path):
background_audiofile = os.path.join(background_audio_path, mixture_recipe['bg_path'])
# Load background audio
bg_audio_data, fs_bg = AudioFile().load(filename=background_audiofile,
fs=params['mixture']['fs'],
mono=True)
if mixture_recipe['event_present']:
event_audiofile = os.path.join(event_audio_path, mixture_recipe['event_path'])
# Load event audio
event_audio_data, fs_event = AudioFile().load(filename=event_audiofile,
fs=params['mixture']['fs'],
mono=True)
if fs_bg != fs_event:
message = '{name}: Sampling frequency mismatch. Material should be resampled.'.format(
name=self.__class__.__name__
)
self.logger.exception(message)
raise ValueError(message)
# Slice event audio
segment_start_samples = int(mixture_recipe['segment_start_seconds'] * params['mixture']['fs'])
segment_end_samples = int(mixture_recipe['segment_end_seconds'] * params['mixture']['fs'])
event_audio_data = event_audio_data[segment_start_samples:segment_end_samples]
event_start_in_mixture_samples = int(mixture_recipe['event_start_in_mixture_seconds'] * params['mixture']['fs'])
scaling_factor = mixture_recipe['scaling_factor']
# Mix event into background audio
mixture = self._mix(bg_audio_data=bg_audio_data,
event_audio_data=event_audio_data,
event_start_in_mixture_samples=event_start_in_mixture_samples,
scaling_factor=scaling_factor,
magic_anticlipping_factor=params['mixture']['anticlipping_factor'])
else:
mixture = params['mixture']['anticlipping_factor'] * bg_audio_data
return mixture
def _mix(self, bg_audio_data, event_audio_data, event_start_in_mixture_samples, scaling_factor, magic_anticlipping_factor):
"""Mix numpy arrays of background and event audio (mono, non-matching lengths supported, sampling frequency
better be the same, no operation in terms of seconds is performed though)
Parameters
----------
bg_audio_data : numpy.array
event_audio_data : numpy.array
event_start_in_mixture_samples : float
scaling_factor : float
magic_anticlipping_factor : float
Returns
-------
numpy.array
"""
# Store current event audio max value
event_audio_original_max = numpy.max(numpy.abs(event_audio_data))
# Adjust SNRs
event_audio_data *= scaling_factor
# Check that the offset is not too long
longest_possible_offset = len(bg_audio_data) - len(event_audio_data)
if event_start_in_mixture_samples > longest_possible_offset:
message = '{name}: Wrongly generated event offset: event tries to go outside the boundaries of the bg.'.format(name=self.__class__.__name__)
self.logger.exception(message)
raise AssertionError(message)
# Measure how much to pad from the right
tail_length = len(bg_audio_data) - len(event_audio_data) - event_start_in_mixture_samples
# Pad zeros at the beginning of event signal
padded_event = numpy.pad(event_audio_data,
pad_width=((event_start_in_mixture_samples, tail_length)),
mode='constant',
constant_values=0)
if not len(padded_event) == len(bg_audio_data):
message = '{name}: Mixing yielded a signal of different length than bg! Should not happen.'.format(
name=self.__class__.__name__
)
self.logger.exception(message)
raise AssertionError(message)
mixture = magic_anticlipping_factor * (padded_event + bg_audio_data)
# Also nice to make sure that we did not introduce clipping
if numpy.max(numpy.abs(mixture)) >= 1:
normalisation_factor = 1 / float(numpy.max(numpy.abs(mixture)))
print('Attention! Had to normalise the mixture by [{factor}]'.format(factor=normalisation_factor))
print('I.e. bg max: {bg_max:2.4f}, event max: {event_max:2.4f}, sum max: {sum_max:2.4f}'.format(
bg_max=numpy.max(numpy.abs(bg_audio_data)),
event_max=numpy.max(numpy.abs(padded_event)),
sum_max=numpy.max(numpy.abs(mixture)))
)
print('The scaling factor for the event was [{factor}]'.format(factor=scaling_factor))
print('The event before scaling was max [{max}]'.format(max=event_audio_original_max))
mixture /= numpy.max(numpy.abs(mixture))
return mixture
class TUTRareSoundEvents_2017_EvaluationSet(SyntheticSoundEventDataset):
"""TUT Acoustic scenes 2017 evaluation dataset
This dataset is used in DCASE2017 - Task 1, Acoustic scene classification
"""
def __init__(self, *args, **kwargs):
kwargs['storage_name'] = kwargs.get('storage_name', 'TUT-rare-sound-events-2017-evaluation')
kwargs['filelisthash_exclude_dirs'] = kwargs.get('filelisthash_exclude_dirs', ['generated_data'])
# Initialize baseclass
super(TUTRareSoundEvents_2017_EvaluationSet, self).__init__(*args, **kwargs)
self.reference_data_present = True
self.dataset_group = 'sound event'
self.dataset_meta = {
'authors': '<NAME>, <NAME>, <NAME>, and <NAME>',
'name_remote': 'TUT Rare Sound Events 2017, evaluation dataset',
'url': None,
'audio_source': 'Synthetic',
'audio_type': 'Natural',
'recording_device_model': 'Unknown',
'microphone_model': 'Unknown',
}
self.crossvalidation_folds = 1
self.package_list = [
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
]
@property
def event_labels(self, scene_label=None):
"""List of unique event labels in the meta data.
Parameters
----------
Returns
-------
labels : list
List of event labels in alphabetical order.
"""
labels = ['babycry', 'glassbreak', 'gunshot']
labels.sort()
return labels
def _after_extract(self, to_return=None):
"""After dataset packages are downloaded and extracted, meta-files are checked.
Parameters
----------
nothing
Returns
-------
nothing
"""
if not self.meta_container.exists():
meta_data = MetaDataContainer()
for event_label_ in self.event_labels:
event_list_filename = os.path.join(
self.local_path,
'meta',
'event_list_evaltest_' + event_label_ + '.csv'
)
if os.path.isfile(event_list_filename):
# Load train files
current_meta = MetaDataContainer(filename=event_list_filename).load()
# Fix path
for item in current_meta:
item['file'] = os.path.join('audio', item['file'])
meta_data += current_meta
else:
current_meta = MetaDataContainer()
for filename in self.audio_files:
raw_path, raw_filename = os.path.split(filename)
relative_path = self.absolute_to_relative(raw_path)
base_filename, file_extension = os.path.splitext(raw_filename)
if event_label_ in base_filename:
current_meta.append(MetaDataItem({'file': os.path.join(relative_path, raw_filename)}))
self.meta_container.update(meta_data)
self.meta_container.save()
def train(self, fold=0, event_label=None):
return []
def test(self, fold=0, event_label=None):
"""List of testing items.
Parameters
----------
fold : int > 0 [scalar]
Fold id, if zero all meta data is returned.
(Default value=0)
event_label : str
Event label
Default value "None"
Returns
-------
list : list of dicts
List containing all meta data assigned to testing set for given fold.
"""
if fold not in self.crossvalidation_data_test:
self.crossvalidation_data_test[fold] = {}
for event_label_ in self.event_labels:
if event_label_ not in self.crossvalidation_data_test[fold]:
self.crossvalidation_data_test[fold][event_label_] = MetaDataContainer()
if fold == 0:
event_list_filename = os.path.join(
self.local_path,
'meta',
'event_list_evaltest_' + event_label_ + '.csv'
)
if os.path.isfile(event_list_filename):
# Load train files
self.crossvalidation_data_test[0][event_label_] = MetaDataContainer(
filename=event_list_filename).load()
# Fix file paths
for item in self.crossvalidation_data_test[fold][event_label_]:
item['file'] = os.path.join('audio', item['file'])
else:
# Recover files from audio files
meta = MetaDataContainer()
for item in self.meta:
if event_label_ in item.file:
meta.append(item)
# Change file paths to absolute
for item in self.crossvalidation_data_test[fold][event_label_]:
item['file'] = self.relative_to_absolute_path(item['file'])
if event_label:
return self.crossvalidation_data_test[fold][event_label]
else:
data = MetaDataContainer()
for event_label_ in self.event_labels:
data += self.crossvalidation_data_test[fold][event_label_]
return data
class TUTSoundEvents_2017_DevelopmentSet(SoundEventDataset):
"""TUT Sound events 2017 development dataset
This dataset is used in DCASE2017 - Task 3, Sound event detection in real life audio
"""
def __init__(self, *args, **kwargs):
kwargs['storage_name'] = kwargs.get('storage_name', 'TUT-sound-events-2017-development')
super(TUTSoundEvents_2017_DevelopmentSet, self).__init__(*args, **kwargs)
self.dataset_group = 'sound event'
self.dataset_meta = {
'authors': '<NAME>, <NAME>, and <NAME>',
'name_remote': 'TUT Sound Events 2016, development dataset',
'url': 'https://zenodo.org/record/45759',
'audio_source': 'Field recording',
'audio_type': 'Natural',
'recording_device_model': 'Roland Edirol R-09',
'microphone_model': 'Soundman OKM II Klassik/studio A3 electret microphone',
}
self.crossvalidation_folds = 4
self.package_list = [
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio', 'street'),
},
{
'remote_package': 'https://zenodo.org/record/400516/files/TUT-sound-events-2017-development.doc.zip',
'local_package': os.path.join(self.local_path, 'TUT-sound-events-2017-development.doc.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400516/files/TUT-sound-events-2017-development.meta.zip',
'local_package': os.path.join(self.local_path, 'TUT-sound-events-2017-development.meta.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400516/files/TUT-sound-events-2017-development.audio.1.zip',
'local_package': os.path.join(self.local_path, 'TUT-sound-events-2017-development.audio.1.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/400516/files/TUT-sound-events-2017-development.audio.2.zip',
'local_package': os.path.join(self.local_path, 'TUT-sound-events-2017-development.audio.2.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
]
def _after_extract(self, to_return=None):
"""After dataset packages are downloaded and extracted, meta-files are checked.
Parameters
----------
nothing
Returns
-------
nothing
"""
if not self.meta_container.exists():
meta_data = MetaDataContainer()
for filename in self.audio_files:
raw_path, raw_filename = os.path.split(filename)
relative_path = self.absolute_to_relative(raw_path)
scene_label = relative_path.replace('audio', '')[1:]
base_filename, file_extension = os.path.splitext(raw_filename)
annotation_filename = os.path.join(
self.local_path,
relative_path.replace('audio', 'meta'),
base_filename + '.ann'
)
data = MetaDataContainer(filename=annotation_filename).load()
for item in data:
item['file'] = os.path.join(relative_path, raw_filename)
item['scene_label'] = scene_label
item['identifier'] = os.path.splitext(raw_filename)[0]
item['source_label'] = 'mixture'
meta_data += data
self.meta_container.update(meta_data)
self.meta_container.save()
else:
self.meta_container.load()
def train(self, fold=0, scene_label=None):
"""List of training items.
Parameters
----------
fold : int > 0 [scalar]
Fold id, if zero all meta data is returned.
(Default value=0)
scene_label : str
Scene label
Default value "None"
Returns
-------
list : list of dicts
List containing all meta data assigned to training set for given fold.
"""
if fold not in self.crossvalidation_data_train:
self.crossvalidation_data_train[fold] = {}
for scene_label_ in self.scene_labels:
if scene_label_ not in self.crossvalidation_data_train[fold]:
self.crossvalidation_data_train[fold][scene_label_] = MetaDataContainer()
if fold > 0:
self.crossvalidation_data_train[fold][scene_label_] = MetaDataContainer(
filename=self._get_evaluation_setup_filename(
setup_part='train',
fold=fold, scene_label=scene_label_)).load()
else:
self.crossvalidation_data_train[0][scene_label_] = self.meta_container.filter(
scene_label=scene_label_
)
for item in self.crossvalidation_data_train[fold][scene_label_]:
item['file'] = self.relative_to_absolute_path(item['file'])
raw_path, raw_filename = os.path.split(item['file'])
item['identifier'] = os.path.splitext(raw_filename)[0]
item['source_label'] = 'mixture'
if scene_label:
return self.crossvalidation_data_train[fold][scene_label]
else:
data = MetaDataContainer()
for scene_label_ in self.scene_labels:
data += self.crossvalidation_data_train[fold][scene_label_]
return data
class TUTSoundEvents_2017_EvaluationSet(SoundEventDataset):
"""TUT Sound events 2017 evaluation dataset
This dataset is used in DCASE2017 - Task 3, Sound event detection in real life audio
"""
def __init__(self, *args, **kwargs):
kwargs['storage_name'] = kwargs.get('storage_name', 'TUT-sound-events-2017-evaluation')
super(TUTSoundEvents_2017_EvaluationSet, self).__init__(*args, **kwargs)
self.reference_data_present = True
self.dataset_group = 'sound event'
self.dataset_meta = {
'authors': '<NAME>, <NAME>, and <NAME>',
'name_remote': 'TUT Sound Events 2016, development dataset',
'url': 'https://zenodo.org/record/45759',
'audio_source': 'Field recording',
'audio_type': 'Natural',
'recording_device_model': 'Roland Edirol R-09',
'microphone_model': 'Soundman OKM II Klassik/studio A3 electret microphone',
}
self.crossvalidation_folds = 1
self.package_list = [
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio', 'street'),
},
]
@property
def scene_labels(self):
labels = ['street']
labels.sort()
return labels
def _after_extract(self, to_return=None):
"""After dataset packages are downloaded and extracted, meta-files are checked.
Parameters
----------
nothing
Returns
-------
nothing
"""
if not self.meta_container.exists():
meta_data = MetaDataContainer()
for filename in self.audio_files:
raw_path, raw_filename = os.path.split(filename)
relative_path = self.absolute_to_relative(raw_path)
scene_label = relative_path.replace('audio', '')[1:]
base_filename, file_extension = os.path.splitext(raw_filename)
annotation_filename = os.path.join(self.local_path, relative_path.replace('audio', 'meta'),
base_filename + '.ann')
data = MetaDataContainer(filename=annotation_filename).load()
for item in data:
item['file'] = os.path.join(relative_path, raw_filename)
item['scene_label'] = scene_label
item['identifier'] = os.path.splitext(raw_filename)[0]
item['source_label'] = 'mixture'
meta_data += data
meta_data.save(filename=self.meta_container.filename)
else:
self.meta_container.load()
def train(self, fold=0, scene_label=None):
return []
def test(self, fold=0, scene_label=None):
if fold not in self.crossvalidation_data_test:
self.crossvalidation_data_test[fold] = {}
for scene_label_ in self.scene_labels:
if scene_label_ not in self.crossvalidation_data_test[fold]:
self.crossvalidation_data_test[fold][scene_label_] = MetaDataContainer()
if fold > 0:
self.crossvalidation_data_test[fold][scene_label_] = MetaDataContainer(
filename=self._get_evaluation_setup_filename(
setup_part='test', fold=fold, scene_label=scene_label_)
).load()
else:
self.crossvalidation_data_test[fold][scene_label_] = MetaDataContainer(
filename=self._get_evaluation_setup_filename(
setup_part='test', fold=fold, scene_label=scene_label_)
).load()
if scene_label:
return self.crossvalidation_data_test[fold][scene_label]
else:
data = MetaDataContainer()
for scene_label_ in self.scene_labels:
data += self.crossvalidation_data_test[fold][scene_label_]
return data
class DCASE2017_Task4tagging_DevelopmentSet(SoundEventDataset):
"""DCASE 2017 Large-scale weakly supervised sound event detection for smart cars
"""
def __init__(self, *args, **kwargs):
kwargs['storage_name'] = kwargs.get('storage_name', 'DCASE2017-task4-development')
super(DCASE2017_Task4tagging_DevelopmentSet, self).__init__(*args, **kwargs)
self.dataset_group = 'audio tagging'
self.dataset_meta = {
'authors': '<NAME>, <NAME>, <NAME>',
'name_remote': 'Task 4 Large-scale weakly supervised sound event detection for smart cars',
'url': 'https://github.com/ankitshah009/Task-4-Large-scale-weakly-supervised-sound-event-detection-for-smart-cars',
'audio_source': 'Field recording',
'audio_type': 'Natural',
'recording_device_model': None,
'microphone_model': None,
}
self.crossvalidation_folds = 1
self.default_audio_extension = 'flac'
github_url = 'https://raw.githubusercontent.com/ankitshah009/Task-4-Large-scale-weakly-supervised-sound-event-detection-for-smart-cars/master/'
self.package_list = [
{
'remote_package': github_url + 'training_set.csv',
'local_package': os.path.join(self.local_path, 'training_set.csv'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': github_url + 'testing_set.csv',
'local_package': os.path.join(self.local_path, 'testing_set.csv'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': github_url + 'groundtruth_weak_label_training_set.csv',
'local_package': os.path.join(self.local_path, 'groundtruth_weak_label_training_set.csv'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': github_url + 'groundtruth_weak_label_testing_set.csv',
'local_package': os.path.join(self.local_path, 'groundtruth_weak_label_testing_set.csv'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': github_url + 'APACHE_LICENSE.txt',
'local_package': os.path.join(self.local_path, 'APACHE_LICENSE.txt'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': github_url + 'README.txt',
'local_package': os.path.join(self.local_path, 'README.txt'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': github_url + 'sound_event_list_17_classes.txt',
'local_package': os.path.join(self.local_path, 'sound_event_list_17_classes.txt'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': github_url + 'groundtruth_strong_label_testing_set.csv',
'local_package': os.path.join(self.local_path, 'groundtruth_strong_label_testing_set.csv'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
}
]
@property
def scene_labels(self):
labels = ['youtube']
labels.sort()
return labels
def _after_extract(self, to_return=None):
import csv
from httplib import BadStatusLine
from dcase_framework.files import AudioFile
def progress_hook(t):
"""
Wraps tqdm instance. Don't forget to close() or __exit__()
the tqdm instance once you're done with it (easiest using `with` syntax).
"""
def inner(total, recvd, ratio, rate, eta):
t.total = int(total / 1024.0)
t.update(int(recvd / 1024.0))
return inner
# Collect file ids
files = []
with open(os.path.join(self.local_path, 'testing_set.csv'), 'rb') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
files.append({
'query_id': row[0],
'segment_start': row[1],
'segment_end': row[2]}
)
with open(os.path.join(self.local_path, 'training_set.csv'), 'rb') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
files.append({
'query_id': row[0],
'segment_start': row[1],
'segment_end': row[2]}
)
# Make sure audio directory exists
if not os.path.isdir(os.path.join(self.local_path, 'audio')):
os.makedirs(os.path.join(self.local_path, 'audio'))
file_progress = tqdm(files,
desc="{0: <25s}".format('Files'),
file=sys.stdout,
leave=False,
disable=self.disable_progress_bar,
ascii=self.use_ascii_progress_bar)
non_existing_videos = []
# Check that audio files exists
for file_data in file_progress:
audio_filename = os.path.join(self.local_path,
'audio',
'Y{query_id}_{segment_start}_{segment_end}.{extension}'.format(
query_id=file_data['query_id'],
segment_start=file_data['segment_start'],
segment_end=file_data['segment_end'],
extension=self.default_audio_extension
)
)
# Download segment if it does not exists
if not os.path.isfile(audio_filename):
import pafy
#
try:
# Access youtube video and get best quality audio stream
youtube_audio = pafy.new(
url='https://www.youtube.com/watch?v={query_id}'.format(query_id=file_data['query_id']),
basic=False,
gdata=False,
size=False
).getbestaudio()
# Get temp file
tmp_file = os.path.join(self.local_path, 'tmp_file.{extension}'.format(
extension=youtube_audio.extension)
)
# Create download progress bar
download_progress_bar = tqdm(
desc="{0: <25s}".format('Download youtube item '),
file=sys.stdout,
unit='B',
unit_scale=True,
leave=False,
disable=self.disable_progress_bar,
ascii=self.use_ascii_progress_bar
)
# Download audio
youtube_audio.download(
filepath=tmp_file,
quiet=True,
callback=progress_hook(download_progress_bar)
)
# Close progress bar
download_progress_bar.close()
# Create audio processing progress bar
audio_processing_progress_bar = tqdm(
desc="{0: <25s}".format('Processing '),
initial=0,
total=4,
file=sys.stdout,
leave=False,
disable=self.disable_progress_bar,
ascii=self.use_ascii_progress_bar
)
# Load audio
audio_file = AudioFile()
audio_file.load(
filename=tmp_file,
mono=True,
fs=44100,
res_type='kaiser_best',
start=float(file_data['segment_start']),
stop=float(file_data['segment_end'])
)
audio_processing_progress_bar.update(1)
# Save the segment
audio_file.save(
filename=audio_filename,
bitdepth=16
)
audio_processing_progress_bar.update(3)
# Remove temporal file
os.remove(tmp_file)
audio_processing_progress_bar.close()
except (IOError, BadStatusLine) as e:
# Store files with errors
file_data['error'] = str(e.message)
non_existing_videos.append(file_data)
except (KeyboardInterrupt, SystemExit):
# Remove temporal file and current audio file.
os.remove(tmp_file)
os.remove(audio_filename)
raise
log_filename = os.path.join(self.local_path, 'item_access_error.log')
with open(log_filename, 'wb') as csv_file:
csv_writer = csv.writer(csv_file, delimiter=',')
for item in non_existing_videos:
csv_writer.writerow(
(item['query_id'], item['error'].replace('\n', ' '))
)
# Make sure evaluation_setup directory exists
if not os.path.isdir(os.path.join(self.local_path, self.evaluation_setup_folder)):
os.makedirs(os.path.join(self.local_path, self.evaluation_setup_folder))
# Check that evaluation setup exists
evaluation_setup_exists = True
train_filename = self._get_evaluation_setup_filename(
setup_part='train',
fold=1,
scene_label='youtube',
file_extension='txt'
)
test_filename = self._get_evaluation_setup_filename(
setup_part='test',
fold=1,
scene_label='youtube',
file_extension='txt'
)
evaluate_filename = self._get_evaluation_setup_filename(
setup_part='evaluate',
fold=1,
scene_label='youtube',
file_extension='txt'
)
if not os.path.isfile(train_filename) or not os.path.isfile(test_filename) or not os.path.isfile(
evaluate_filename):
evaluation_setup_exists = False
# Evaluation setup was not found generate
if not evaluation_setup_exists:
fold = 1
train_meta = MetaDataContainer()
for item in MetaDataContainer().load(
os.path.join(self.local_path, 'groundtruth_weak_label_training_set.csv')):
if not item['file'].endswith('flac'):
item['file'] = os.path.join('audio', 'Y' + os.path.splitext(item['file'])[
0] + '.' + self.default_audio_extension)
# Set scene label
item['scene_label'] = 'youtube'
# Translate event onset and offset, weak labels
item['event_offset'] -= item['event_onset']
item['event_onset'] -= item['event_onset']
# Only collect items which exists
if os.path.isfile(os.path.join(self.local_path, item['file'])):
train_meta.append(item)
train_meta.save(filename=self._get_evaluation_setup_filename(
setup_part='train',
fold=fold,
scene_label='youtube',
file_extension='txt')
)
evaluate_meta = MetaDataContainer()
for item in MetaDataContainer().load(
os.path.join(self.local_path, 'groundtruth_strong_label_testing_set.csv')):
if not item['file'].endswith('flac'):
item['file'] = os.path.join('audio', 'Y' + os.path.splitext(item['file'])[
0] + '.' + self.default_audio_extension)
# Set scene label
item['scene_label'] = 'youtube'
# Only collect items which exists
if os.path.isfile(os.path.join(self.local_path, item['file'])):
evaluate_meta.append(item)
evaluate_meta.save(filename=self._get_evaluation_setup_filename(
setup_part='evaluate',
fold=fold,
scene_label='youtube',
file_extension='txt')
)
test_meta = MetaDataContainer()
for item in evaluate_meta:
test_meta.append(MetaDataItem({'file': item['file']}))
test_meta.save(filename=self._get_evaluation_setup_filename(
setup_part='test',
fold=fold,
scene_label='youtube',
file_extension='txt')
)
if not self.meta_container.exists():
fold = 1
meta_data = MetaDataContainer()
meta_data += MetaDataContainer().load(self._get_evaluation_setup_filename(
setup_part='train',
fold=fold,
scene_label='youtube',
file_extension='txt')
)
meta_data += MetaDataContainer().load(self._get_evaluation_setup_filename(
setup_part='evaluate',
fold=fold,
scene_label='youtube',
file_extension='txt')
)
self.meta_container.update(meta_data)
self.meta_container.save()
else:
self.meta_container.load()
# =====================================================
# DCASE 2016
# =====================================================
class TUTAcousticScenes_2016_DevelopmentSet(AcousticSceneDataset):
"""TUT Acoustic scenes 2016 development dataset
This dataset is used in DCASE2016 - Task 1, Acoustic scene classification
"""
def __init__(self, *args, **kwargs):
kwargs['storage_name'] = kwargs.get('storage_name', 'TUT-acoustic-scenes-2016-development')
super(TUTAcousticScenes_2016_DevelopmentSet, self).__init__(*args, **kwargs)
self.dataset_group = 'acoustic scene'
self.dataset_meta = {
'authors': '<NAME>, <NAME>, and <NAME>',
'name_remote': 'TUT Acoustic Scenes 2016, development dataset',
'url': 'https://zenodo.org/record/45739',
'audio_source': 'Field recording',
'audio_type': 'Natural',
'recording_device_model': 'Roland Edirol R-09',
'microphone_model': 'Soundman OKM II Klassik/studio A3 electret microphone',
}
self.crossvalidation_folds = 4
self.package_list = [
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/45739/files/TUT-acoustic-scenes-2016-development.doc.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-development.doc.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/45739/files/TUT-acoustic-scenes-2016-development.meta.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-development.meta.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/45739/files/TUT-acoustic-scenes-2016-development.error.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-development.error.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/45739/files/TUT-acoustic-scenes-2016-development.audio.1.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-development.audio.1.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/45739/files/TUT-acoustic-scenes-2016-development.audio.2.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-development.audio.2.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/45739/files/TUT-acoustic-scenes-2016-development.audio.3.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-development.audio.3.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/45739/files/TUT-acoustic-scenes-2016-development.audio.4.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-development.audio.4.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/45739/files/TUT-acoustic-scenes-2016-development.audio.5.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-development.audio.5.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/45739/files/TUT-acoustic-scenes-2016-development.audio.6.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-development.audio.6.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/45739/files/TUT-acoustic-scenes-2016-development.audio.7.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-development.audio.7.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/45739/files/TUT-acoustic-scenes-2016-development.audio.8.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-development.audio.8.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
}
]
def _after_extract(self, to_return=None):
"""After dataset packages are downloaded and extracted, meta-files are checked.
Parameters
----------
nothing
Returns
-------
nothing
"""
if not self.meta_container.exists():
meta_data = {}
for fold in range(1, self.crossvalidation_folds):
# Read train files in
fold_data = MetaDataContainer(
filename=os.path.join(self.evaluation_setup_path, 'fold' + str(fold) + '_train.txt')).load()
fold_data += MetaDataContainer(
filename=os.path.join(self.evaluation_setup_path, 'fold' + str(fold) + '_evaluate.txt')).load()
for item in fold_data:
if item['file'] not in meta_data:
raw_path, raw_filename = os.path.split(item['file'])
relative_path = self.absolute_to_relative(raw_path)
location_id = raw_filename.split('_')[0]
item['file'] = os.path.join(relative_path, raw_filename)
item['identifier'] = location_id
meta_data[item['file']] = item
self.meta_container.update(meta_data.values())
self.meta_container.save()
def train(self, fold=0):
"""List of training items.
Parameters
----------
fold : int > 0 [scalar]
Fold id, if zero all meta data is returned.
(Default value=0)
Returns
-------
list : list of dicts
List containing all meta data assigned to training set for given fold.
"""
if fold not in self.crossvalidation_data_train:
self.crossvalidation_data_train[fold] = []
if fold > 0:
self.crossvalidation_data_train[fold] = MetaDataContainer(
filename=os.path.join(self.evaluation_setup_path, 'fold' + str(fold) + '_train.txt')).load()
for item in self.crossvalidation_data_train[fold]:
item['file'] = self.relative_to_absolute_path(item['file'])
raw_path, raw_filename = os.path.split(item['file'])
location_id = raw_filename.split('_')[0]
item['identifier'] = location_id
else:
self.crossvalidation_data_train[0] = self.meta_container
return self.crossvalidation_data_train[fold]
class TUTAcousticScenes_2016_EvaluationSet(AcousticSceneDataset):
"""TUT Acoustic scenes 2016 evaluation dataset
This dataset is used in DCASE2016 - Task 1, Acoustic scene classification
"""
def __init__(self, *args, **kwargs):
kwargs['storage_name'] = kwargs.get('storage_name', 'TUT-acoustic-scenes-2016-evaluation')
super(TUTAcousticScenes_2016_EvaluationSet, self).__init__(*args, **kwargs)
self.dataset_group = 'acoustic scene'
self.dataset_meta = {
'authors': '<NAME>, <NAME>, and <NAME>',
'name_remote': 'TUT Acoustic Scenes 2016, evaluation dataset',
'url': 'https://zenodo.org/record/165995',
'audio_source': 'Field recording',
'audio_type': 'Natural',
'recording_device_model': 'Roland Edirol R-09',
'microphone_model': 'Soundman OKM II Klassik/studio A3 electret microphone',
}
self.crossvalidation_folds = 1
self.package_list = [
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/165995/files/TUT-acoustic-scenes-2016-evaluation.doc.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-evaluation.doc.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/165995/files/TUT-acoustic-scenes-2016-evaluation.audio.1.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-evaluation.audio.1.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/165995/files/TUT-acoustic-scenes-2016-evaluation.audio.2.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-evaluation.audio.2.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/165995/files/TUT-acoustic-scenes-2016-evaluation.audio.3.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-evaluation.audio.3.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/165995/files/TUT-acoustic-scenes-2016-evaluation.meta.zip',
'local_package': os.path.join(self.local_path, 'TUT-acoustic-scenes-2016-evaluation.meta.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
}
]
def _after_extract(self, to_return=None):
"""After dataset packages are downloaded and extracted, meta-files are checked.
Parameters
----------
nothing
Returns
-------
nothing
"""
eval_file = MetaDataContainer(filename=os.path.join(self.evaluation_setup_path, 'evaluate.txt'))
if not self.meta_container.exists() and eval_file.exists():
eval_data = eval_file.load()
meta_data = {}
for item in eval_data:
if item['file'] not in meta_data:
raw_path, raw_filename = os.path.split(item['file'])
relative_path = self.absolute_to_relative(raw_path)
item['file'] = os.path.join(relative_path, raw_filename)
meta_data[item['file']] = item
self.meta_container.update(meta_data.values())
self.meta_container.save()
def train(self, fold=0):
return []
def test(self, fold=0):
"""List of testing items.
Parameters
----------
fold : int > 0 [scalar]
Fold id, if zero all meta data is returned.
(Default value=0)
Returns
-------
list : list of dicts
List containing all meta data assigned to testing set for given fold.
"""
if fold not in self.crossvalidation_data_test:
self.crossvalidation_data_test[fold] = []
if fold > 0:
with open(os.path.join(self.evaluation_setup_path, 'fold' + str(fold) + '_test.txt'), 'rt') as f:
for row in csv.reader(f, delimiter='\t'):
self.crossvalidation_data_test[fold].append({'file': self.relative_to_absolute_path(row[0])})
else:
data = []
files = []
for item in self.audio_files:
if self.relative_to_absolute_path(item) not in files:
data.append({'file': self.relative_to_absolute_path(item)})
files.append(self.relative_to_absolute_path(item))
self.crossvalidation_data_test[fold] = data
return self.crossvalidation_data_test[fold]
class TUTSoundEvents_2016_DevelopmentSet(SoundEventDataset):
"""TUT Sound events 2016 development dataset
This dataset is used in DCASE2016 - Task 3, Sound event detection in real life audio
"""
def __init__(self, *args, **kwargs):
kwargs['storage_name'] = kwargs.get('storage_name', 'TUT-sound-events-2016-development')
super(TUTSoundEvents_2016_DevelopmentSet, self).__init__(*args, **kwargs)
self.dataset_group = 'sound event'
self.dataset_meta = {
'authors': '<NAME>, <NAME>, and <NAME>',
'name_remote': 'TUT Sound Events 2016, development dataset',
'url': 'https://zenodo.org/record/45759',
'audio_source': 'Field recording',
'audio_type': 'Natural',
'recording_device_model': 'Roland Edirol R-09',
'microphone_model': 'Soundman OKM II Klassik/studio A3 electret microphone',
}
self.crossvalidation_folds = 4
self.package_list = [
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio', 'residential_area'),
},
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio', 'home'),
},
{
'remote_package': 'https://zenodo.org/record/45759/files/TUT-sound-events-2016-development.doc.zip',
'local_package': os.path.join(self.local_path, 'TUT-sound-events-2016-development.doc.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/45759/files/TUT-sound-events-2016-development.meta.zip',
'local_package': os.path.join(self.local_path, 'TUT-sound-events-2016-development.meta.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'https://zenodo.org/record/45759/files/TUT-sound-events-2016-development.audio.zip',
'local_package': os.path.join(self.local_path, 'TUT-sound-events-2016-development.audio.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
]
def _after_extract(self, to_return=None):
"""After dataset packages are downloaded and extracted, meta-files are checked.
Parameters
----------
nothing
Returns
-------
nothing
"""
if not self.meta_container.exists():
meta_data = MetaDataContainer()
for filename in self.audio_files:
raw_path, raw_filename = os.path.split(filename)
relative_path = self.absolute_to_relative(raw_path)
scene_label = relative_path.replace('audio', '')[1:]
base_filename, file_extension = os.path.splitext(raw_filename)
annotation_filename = os.path.join(
self.local_path,
relative_path.replace('audio', 'meta'),
base_filename + '.ann'
)
data = MetaDataContainer(filename=annotation_filename).load()
for item in data:
item['file'] = os.path.join(relative_path, raw_filename)
item['scene_label'] = scene_label
item['identifier'] = os.path.splitext(raw_filename)[0]
item['source_label'] = 'mixture'
meta_data += data
meta_data.save(filename=self.meta_container.filename)
def train(self, fold=0, scene_label=None):
"""List of training items.
Parameters
----------
fold : int > 0 [scalar]
Fold id, if zero all meta data is returned.
(Default value=0)
scene_label : str
Scene label
Default value "None"
Returns
-------
list : list of dicts
List containing all meta data assigned to training set for given fold.
"""
if fold not in self.crossvalidation_data_train:
self.crossvalidation_data_train[fold] = {}
for scene_label_ in self.scene_labels:
if scene_label_ not in self.crossvalidation_data_train[fold]:
self.crossvalidation_data_train[fold][scene_label_] = MetaDataContainer()
if fold > 0:
self.crossvalidation_data_train[fold][scene_label_] = MetaDataContainer(
filename=self._get_evaluation_setup_filename(
setup_part='train', fold=fold, scene_label=scene_label_)).load()
else:
self.crossvalidation_data_train[0][scene_label_] = self.meta_container.filter(
scene_label=scene_label_
)
for item in self.crossvalidation_data_train[fold][scene_label_]:
item['file'] = self.relative_to_absolute_path(item['file'])
raw_path, raw_filename = os.path.split(item['file'])
item['identifier'] = os.path.splitext(raw_filename)[0]
item['source_label'] = 'mixture'
if scene_label:
return self.crossvalidation_data_train[fold][scene_label]
else:
data = MetaDataContainer()
for scene_label_ in self.scene_labels:
data += self.crossvalidation_data_train[fold][scene_label_]
return data
class TUTSoundEvents_2016_EvaluationSet(SoundEventDataset):
"""TUT Sound events 2016 evaluation dataset
This dataset is used in DCASE2016 - Task 3, Sound event detection in real life audio
"""
def __init__(self, *args, **kwargs):
kwargs['storage_name'] = kwargs.get('storage_name', 'TUT-sound-events-2016-evaluation')
super(TUTSoundEvents_2016_EvaluationSet, self).__init__(*args, **kwargs)
self.dataset_group = 'sound event'
self.dataset_meta = {
'authors': '<NAME>, <NAME>, and <NAME>',
'name_remote': 'TUT Sound Events 2016, evaluation dataset',
'url': 'http://www.cs.tut.fi/sgn/arg/dcase2016/download/',
'audio_source': 'Field recording',
'audio_type': 'Natural',
'recording_device_model': 'Roland Edirol R-09',
'microphone_model': 'Soundman OKM II Klassik/studio A3 electret microphone',
}
self.crossvalidation_folds = 1
self.package_list = [
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio', 'home'),
},
{
'remote_package': None,
'local_package': None,
'local_audio_path': os.path.join(self.local_path, 'audio', 'residential_area'),
},
{
'remote_package': 'http://www.cs.tut.fi/sgn/arg/dcase2016/evaluation_data/TUT-sound-events-2016-evaluation.doc.zip',
'local_package': os.path.join(self.local_path, 'TUT-sound-events-2016-evaluation.doc.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'http://www.cs.tut.fi/sgn/arg/dcase2016/evaluation_data/TUT-sound-events-2016-evaluation.meta.zip',
'local_package': os.path.join(self.local_path, 'TUT-sound-events-2016-evaluation.meta.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
{
'remote_package': 'http://www.cs.tut.fi/sgn/arg/dcase2016/evaluation_data/TUT-sound-events-2016-evaluation.audio.zip',
'local_package': os.path.join(self.local_path, 'TUT-sound-events-2016-evaluation.audio.zip'),
'local_audio_path': os.path.join(self.local_path, 'audio'),
},
]
@property
def scene_labels(self):
labels = ['home', 'residential_area']
labels.sort()
return labels
def _after_extract(self, to_return=None):
"""After dataset packages are downloaded and extracted, meta-files are checked.
Parameters
----------
nothing
Returns
-------
nothing
"""
if not self.meta_container.exists() and os.path.isdir(os.path.join(self.local_path, 'meta')):
meta_file_handle = open(self.meta_container.filename, 'wt')
try:
writer = csv.writer(meta_file_handle, delimiter='\t')
for filename in self.audio_files:
raw_path, raw_filename = os.path.split(filename)
relative_path = self.absolute_to_relative(raw_path)
scene_label = relative_path.replace('audio', '')[1:]
base_filename, file_extension = os.path.splitext(raw_filename)
annotation_filename = os.path.join(
self.local_path,
relative_path.replace('audio', 'meta'),
base_filename + '.ann'
)
if os.path.isfile(annotation_filename):
annotation_file_handle = open(annotation_filename, 'rt')
try:
annotation_file_reader = csv.reader(annotation_file_handle, delimiter='\t')
for annotation_file_row in annotation_file_reader:
writer.writerow((os.path.join(relative_path, raw_filename),
scene_label,
float(annotation_file_row[0].replace(',', '.')),
float(annotation_file_row[1].replace(',', '.')),
annotation_file_row[2], 'm'))
finally:
annotation_file_handle.close()
finally:
meta_file_handle.close()
def train(self, fold=0, scene_label=None):
return []
def test(self, fold=0, scene_label=None):
if fold not in self.crossvalidation_data_test:
self.crossvalidation_data_test[fold] = {}
for scene_label_ in self.scene_labels:
if scene_label_ not in self.crossvalidation_data_test[fold]:
self.crossvalidation_data_test[fold][scene_label_] = []
if fold > 0:
with open(
os.path.join(self.evaluation_setup_path, scene_label_ + '_fold' + str(fold) + '_test.txt'),
'rt') as f:
for row in csv.reader(f, delimiter='\t'):
self.crossvalidation_data_test[fold][scene_label_].append(
{'file': self.relative_to_absolute_path(row[0])}
)
else:
with open(os.path.join(self.evaluation_setup_path, scene_label_ + '_test.txt'), 'rt') as f:
for row in csv.reader(f, delimiter='\t'):
self.crossvalidation_data_test[fold][scene_label_].append(
{'file': self.relative_to_absolute_path(row[0])}
)
if scene_label:
return self.crossvalidation_data_test[fold][scene_label]
else:
data = []
for scene_label_ in self.scene_labels:
for item in self.crossvalidation_data_test[fold][scene_label_]:
data.append(item)
return data
| [
"logging.getLogger",
"tarfile.open",
"zipfile.ZipFile",
"numpy.array",
"itertools.izip",
"sys.exit",
"socket.setdefaulttimeout",
"os.walk",
"os.remove",
"os.listdir",
"numpy.diff",
"os.path.split",
"os.path.isdir",
"csv.reader",
"os.path.relpath",
"numpy.abs",
"collections.OrderedDic... | [((7552, 7611), 'os.path.join', 'os.path.join', (['self.local_path', 'self.evaluation_setup_folder'], {}), '(self.local_path, self.evaluation_setup_folder)\n', (7564, 7611), False, 'import os\n'), ((8138, 8193), 'os.path.join', 'os.path.join', (['self.local_path', 'self.error_meta_filename'], {}), '(self.local_path, self.error_meta_filename)\n', (8150, 8193), False, 'import os\n'), ((17431, 17460), 'socket.setdefaulttimeout', 'socket.setdefaulttimeout', (['(120)'], {}), '(120)\n', (17455, 17460), False, 'import socket\n'), ((25813, 25837), 'os.walk', 'os.walk', (['self.local_path'], {}), '(self.local_path)\n', (25820, 25837), False, 'import os\n'), ((64473, 64532), 'os.path.join', 'os.path.join', (['self.local_path', '"""data"""', '"""source_data"""', '"""bgs"""'], {}), "(self.local_path, 'data', 'source_data', 'bgs')\n", (64485, 64532), False, 'import os\n'), ((64560, 64622), 'os.path.join', 'os.path.join', (['self.local_path', '"""data"""', '"""source_data"""', '"""events"""'], {}), "(self.local_path, 'data', 'source_data', 'events')\n", (64572, 64622), False, 'import os\n'), ((64647, 64711), 'os.path.join', 'os.path.join', (['self.local_path', '"""data"""', '"""source_data"""', '"""cv_setup"""'], {}), "(self.local_path, 'data', 'source_data', 'cv_setup')\n", (64659, 64711), False, 'import os\n'), ((81868, 81930), 'os.path.join', 'os.path.join', (['background_audio_path', "mixture_recipe['bg_path']"], {}), "(background_audio_path, mixture_recipe['bg_path'])\n", (81880, 81930), False, 'import os\n'), ((85424, 85548), 'numpy.pad', 'numpy.pad', (['event_audio_data'], {'pad_width': '(event_start_in_mixture_samples, tail_length)', 'mode': '"""constant"""', 'constant_values': '(0)'}), "(event_audio_data, pad_width=(event_start_in_mixture_samples,\n tail_length), mode='constant', constant_values=0)\n", (85433, 85548), False, 'import numpy\n'), ((112519, 112573), 'os.path.join', 'os.path.join', (['self.local_path', '"""item_access_error.log"""'], {}), "(self.local_path, 'item_access_error.log')\n", (112531, 112573), False, 'import os\n'), ((6751, 6778), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (6768, 6778), False, 'import logging\n'), ((10056, 10086), 'os.path.isdir', 'os.path.isdir', (['self.local_path'], {}), '(self.local_path)\n', (10069, 10086), False, 'import os\n'), ((10100, 10128), 'os.makedirs', 'os.makedirs', (['self.local_path'], {}), '(self.local_path)\n', (10111, 10128), False, 'import os\n'), ((26470, 26527), 'os.path.join', 'os.path.join', (['self.local_path', 'self.filelisthash_filename'], {}), '(self.local_path, self.filelisthash_filename)\n', (26482, 26527), False, 'import os\n'), ((32478, 32510), 'os.path.abspath', 'os.path.abspath', (['self.local_path'], {}), '(self.local_path)\n', (32493, 32510), False, 'import os\n'), ((32532, 32570), 'os.path.relpath', 'os.path.relpath', (['path', 'self.local_path'], {}), '(path, self.local_path)\n', (32547, 32570), False, 'import os\n'), ((38369, 38399), 'os.path.isdir', 'os.path.isdir', (['self.local_path'], {}), '(self.local_path)\n', (38382, 38399), False, 'import os\n'), ((38413, 38441), 'os.makedirs', 'os.makedirs', (['self.local_path'], {}), '(self.local_path)\n', (38424, 38441), False, 'import os\n'), ((45002, 45027), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (45025, 45027), False, 'import collections\n'), ((48831, 48856), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (48854, 48856), False, 'import collections\n'), ((51483, 51528), 'os.path.join', 'os.path.join', (['"""generated_data"""', 'meta_filename'], {}), "('generated_data', meta_filename)\n", (51495, 51528), False, 'import os\n'), ((65887, 65993), 'os.path.join', 'os.path.join', (['self.local_path', '"""generated_data"""', "('mixtures_' + subset_name_on_disk + '_' + params_hash)"], {}), "(self.local_path, 'generated_data', 'mixtures_' +\n subset_name_on_disk + '_' + params_hash)\n", (65899, 65993), False, 'import os\n'), ((66086, 66201), 'os.path.join', 'os.path.join', (['self.local_path', '"""generated_data"""', "('mixtures_' + subset_name_on_disk + '_' + params_hash)", '"""audio"""'], {}), "(self.local_path, 'generated_data', 'mixtures_' +\n subset_name_on_disk + '_' + params_hash, 'audio')\n", (66098, 66201), False, 'import os\n'), ((66309, 66423), 'os.path.join', 'os.path.join', (['self.local_path', '"""generated_data"""', "('mixtures_' + subset_name_on_disk + '_' + params_hash)", '"""meta"""'], {}), "(self.local_path, 'generated_data', 'mixtures_' +\n subset_name_on_disk + '_' + params_hash, 'meta')\n", (66321, 66423), False, 'import os\n'), ((75075, 75125), 'os.path.join', 'os.path.join', (['class_label', "event['audio_filename']"], {}), "(class_label, event['audio_filename'])\n", (75087, 75125), False, 'import os\n'), ((82253, 82313), 'os.path.join', 'os.path.join', (['event_audio_path', "mixture_recipe['event_path']"], {}), "(event_audio_path, mixture_recipe['event_path'])\n", (82265, 82313), False, 'import os\n'), ((84671, 84698), 'numpy.abs', 'numpy.abs', (['event_audio_data'], {}), '(event_audio_data)\n', (84680, 84698), False, 'import numpy\n'), ((107246, 107281), 'csv.reader', 'csv.reader', (['csv_file'], {'delimiter': '""","""'}), "(csv_file, delimiter=',')\n", (107256, 107281), False, 'import csv\n'), ((107608, 107643), 'csv.reader', 'csv.reader', (['csv_file'], {'delimiter': '""","""'}), "(csv_file, delimiter=',')\n", (107618, 107643), False, 'import csv\n'), ((112650, 112685), 'csv.writer', 'csv.writer', (['csv_file'], {'delimiter': '""","""'}), "(csv_file, delimiter=',')\n", (112660, 112685), False, 'import csv\n'), ((7810, 7859), 'os.path.join', 'os.path.join', (['self.local_path', 'self.meta_filename'], {}), '(self.local_path, self.meta_filename)\n', (7822, 7859), False, 'import os\n'), ((21406, 21443), 'os.path.isfile', 'os.path.isfile', (["item['local_package']"], {}), "(item['local_package'])\n", (21420, 21443), False, 'import os\n'), ((32140, 32175), 'os.path.join', 'os.path.join', (['self.local_path', 'path'], {}), '(self.local_path, path)\n', (32152, 32175), False, 'import os\n'), ((40134, 40172), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (40146, 40172), False, 'import os\n'), ((40357, 40434), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2017-development.doc.zip"""'], {}), "(self.local_path, 'TUT-acoustic-scenes-2017-development.doc.zip')\n", (40369, 40434), False, 'import os\n'), ((40472, 40510), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (40484, 40510), False, 'import os\n'), ((40696, 40774), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2017-development.meta.zip"""'], {}), "(self.local_path, 'TUT-acoustic-scenes-2017-development.meta.zip')\n", (40708, 40774), False, 'import os\n'), ((40812, 40850), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (40824, 40850), False, 'import os\n'), ((41037, 41116), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2017-development.error.zip"""'], {}), "(self.local_path, 'TUT-acoustic-scenes-2017-development.error.zip')\n", (41049, 41116), False, 'import os\n'), ((41154, 41192), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (41166, 41192), False, 'import os\n'), ((41381, 41466), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2017-development.audio.1.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2017-development.audio.1.zip')\n", (41393, 41466), False, 'import os\n'), ((41500, 41538), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (41512, 41538), False, 'import os\n'), ((41727, 41812), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2017-development.audio.2.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2017-development.audio.2.zip')\n", (41739, 41812), False, 'import os\n'), ((41846, 41884), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (41858, 41884), False, 'import os\n'), ((42073, 42158), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2017-development.audio.3.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2017-development.audio.3.zip')\n", (42085, 42158), False, 'import os\n'), ((42192, 42230), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (42204, 42230), False, 'import os\n'), ((42419, 42504), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2017-development.audio.4.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2017-development.audio.4.zip')\n", (42431, 42504), False, 'import os\n'), ((42538, 42576), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (42550, 42576), False, 'import os\n'), ((42765, 42850), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2017-development.audio.5.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2017-development.audio.5.zip')\n", (42777, 42850), False, 'import os\n'), ((42884, 42922), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (42896, 42922), False, 'import os\n'), ((43111, 43196), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2017-development.audio.6.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2017-development.audio.6.zip')\n", (43123, 43196), False, 'import os\n'), ((43230, 43268), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (43242, 43268), False, 'import os\n'), ((43457, 43542), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2017-development.audio.7.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2017-development.audio.7.zip')\n", (43469, 43542), False, 'import os\n'), ((43576, 43614), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (43588, 43614), False, 'import os\n'), ((43803, 43888), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2017-development.audio.8.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2017-development.audio.8.zip')\n", (43815, 43888), False, 'import os\n'), ((43922, 43960), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (43934, 43960), False, 'import os\n'), ((44149, 44234), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2017-development.audio.9.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2017-development.audio.9.zip')\n", (44161, 44234), False, 'import os\n'), ((44268, 44306), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (44280, 44306), False, 'import os\n'), ((44496, 44582), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2017-development.audio.10.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2017-development.audio.10.zip')\n", (44508, 44582), False, 'import os\n'), ((44616, 44654), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (44628, 44654), False, 'import os\n'), ((48445, 48483), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (48457, 48483), False, 'import os\n'), ((52266, 52304), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (52278, 52304), False, 'import os\n'), ((52535, 52614), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-rare-sound-events-2017-development.doc.zip"""'], {}), "(self.local_path, 'TUT-rare-sound-events-2017-development.doc.zip')\n", (52547, 52614), False, 'import os\n'), ((52652, 52690), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (52664, 52690), False, 'import os\n'), ((52922, 53007), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-rare-sound-events-2017-development.code.zip"""'], {}), "(self.local_path, 'TUT-rare-sound-events-2017-development.code.zip'\n )\n", (52934, 53007), False, 'import os\n'), ((53040, 53078), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (53052, 53078), False, 'import os\n'), ((53335, 53444), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.1.zip"""'], {}), "(self.local_path,\n 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.1.zip')\n", (53347, 53444), False, 'import os\n'), ((53478, 53516), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (53490, 53516), False, 'import os\n'), ((53773, 53882), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.2.zip"""'], {}), "(self.local_path,\n 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.2.zip')\n", (53785, 53882), False, 'import os\n'), ((53916, 53954), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (53928, 53954), False, 'import os\n'), ((54211, 54320), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.3.zip"""'], {}), "(self.local_path,\n 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.3.zip')\n", (54223, 54320), False, 'import os\n'), ((54354, 54392), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (54366, 54392), False, 'import os\n'), ((54649, 54758), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.4.zip"""'], {}), "(self.local_path,\n 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.4.zip')\n", (54661, 54758), False, 'import os\n'), ((54792, 54830), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (54804, 54830), False, 'import os\n'), ((55087, 55196), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.5.zip"""'], {}), "(self.local_path,\n 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.5.zip')\n", (55099, 55196), False, 'import os\n'), ((55230, 55268), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (55242, 55268), False, 'import os\n'), ((55525, 55634), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.6.zip"""'], {}), "(self.local_path,\n 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.6.zip')\n", (55537, 55634), False, 'import os\n'), ((55668, 55706), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (55680, 55706), False, 'import os\n'), ((55963, 56072), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.7.zip"""'], {}), "(self.local_path,\n 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.7.zip')\n", (55975, 56072), False, 'import os\n'), ((56106, 56144), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (56118, 56144), False, 'import os\n'), ((56401, 56510), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.8.zip"""'], {}), "(self.local_path,\n 'TUT-rare-sound-events-2017-development.source_data_bgs_and_cvsetup.8.zip')\n", (56413, 56510), False, 'import os\n'), ((56544, 56582), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (56556, 56582), False, 'import os\n'), ((56828, 56926), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-rare-sound-events-2017-development.source_data_events.zip"""'], {}), "(self.local_path,\n 'TUT-rare-sound-events-2017-development.source_data_events.zip')\n", (56840, 56926), False, 'import os\n'), ((56960, 56998), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (56972, 56998), False, 'import os\n'), ((66556, 66583), 'os.path.isdir', 'os.path.isdir', (['mixture_path'], {}), '(mixture_path)\n', (66569, 66583), False, 'import os\n'), ((66601, 66626), 'os.makedirs', 'os.makedirs', (['mixture_path'], {}), '(mixture_path)\n', (66612, 66626), False, 'import os\n'), ((66647, 66680), 'os.path.isdir', 'os.path.isdir', (['mixture_audio_path'], {}), '(mixture_audio_path)\n', (66660, 66680), False, 'import os\n'), ((66698, 66729), 'os.makedirs', 'os.makedirs', (['mixture_audio_path'], {}), '(mixture_audio_path)\n', (66709, 66729), False, 'import os\n'), ((66750, 66782), 'os.path.isdir', 'os.path.isdir', (['mixture_meta_path'], {}), '(mixture_meta_path)\n', (66763, 66782), False, 'import os\n'), ((66800, 66830), 'os.makedirs', 'os.makedirs', (['mixture_meta_path'], {}), '(mixture_meta_path)\n', (66811, 66830), False, 'import os\n'), ((67520, 67627), 'os.path.join', 'os.path.join', (['mixture_meta_path', "('mixture_recipes_' + subset_name_on_disk + '_' + class_label + '.yaml')"], {}), "(mixture_meta_path, 'mixture_recipes_' + subset_name_on_disk +\n '_' + class_label + '.yaml')\n", (67532, 67627), False, 'import os\n'), ((70254, 70355), 'os.path.join', 'os.path.join', (['mixture_meta_path', "('event_list_' + subset_name_on_disk + '_' + class_label + '.csv')"], {}), "(mixture_meta_path, 'event_list_' + subset_name_on_disk + '_' +\n class_label + '.csv')\n", (70266, 70355), False, 'import os\n'), ((72336, 72381), 'os.path.join', 'os.path.join', (['mixture_path', '"""parameters.yaml"""'], {}), "(mixture_path, 'parameters.yaml')\n", (72348, 72381), False, 'import os\n'), ((72781, 72802), 'six.iteritems', 'iteritems', (['subset_map'], {}), '(subset_map)\n', (72790, 72802), False, 'from six import iteritems\n'), ((75164, 75192), 'numpy.diff', 'numpy.diff', (["event['segment']"], {}), "(event['segment'])\n", (75174, 75192), False, 'import numpy\n'), ((76703, 76798), 'itertools.izip', 'zip', (['event_offsets_seconds[event_presence_flags]', 'event_instance_ids[event_presence_flags]'], {}), '(event_offsets_seconds[event_presence_flags], event_instance_ids[\n event_presence_flags])\n', (76706, 76798), True, 'from itertools import izip as zip\n'), ((76820, 76840), 'numpy.array', 'numpy.array', (['checker'], {}), '(checker)\n', (76831, 76840), False, 'import numpy\n'), ((77049, 77080), 'numpy.sum', 'numpy.sum', (['event_presence_flags'], {}), '(event_presence_flags)\n', (77058, 77080), False, 'import numpy\n'), ((77458, 77548), 'itertools.izip', 'zip', (['bgs', 'event_presence_flags', 'event_offsets_seconds', 'target_ebrs', 'event_instance_ids'], {}), '(bgs, event_presence_flags, event_offsets_seconds, target_ebrs,\n event_instance_ids)\n', (77461, 77548), True, 'from itertools import izip as zip\n'), ((81995, 82006), 'dcase_framework.files.AudioFile', 'AudioFile', ([], {}), '()\n', (82004, 82006), False, 'from dcase_framework.files import AudioFile\n'), ((86128, 86146), 'numpy.abs', 'numpy.abs', (['mixture'], {}), '(mixture)\n', (86137, 86146), False, 'import numpy\n'), ((86872, 86890), 'numpy.abs', 'numpy.abs', (['mixture'], {}), '(mixture)\n', (86881, 86890), False, 'import numpy\n'), ((88157, 88195), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (88169, 88195), False, 'import os\n'), ((89034, 89123), 'os.path.join', 'os.path.join', (['self.local_path', '"""meta"""', "('event_list_evaltest_' + event_label_ + '.csv')"], {}), "(self.local_path, 'meta', 'event_list_evaltest_' + event_label_ +\n '.csv')\n", (89046, 89123), False, 'import os\n'), ((89218, 89253), 'os.path.isfile', 'os.path.isfile', (['event_list_filename'], {}), '(event_list_filename)\n', (89232, 89253), False, 'import os\n'), ((93738, 93776), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (93750, 93776), False, 'import os\n'), ((93922, 93970), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""', '"""street"""'], {}), "(self.local_path, 'audio', 'street')\n", (93934, 93970), False, 'import os\n'), ((94152, 94226), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-sound-events-2017-development.doc.zip"""'], {}), "(self.local_path, 'TUT-sound-events-2017-development.doc.zip')\n", (94164, 94226), False, 'import os\n'), ((94264, 94302), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (94276, 94302), False, 'import os\n'), ((94485, 94560), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-sound-events-2017-development.meta.zip"""'], {}), "(self.local_path, 'TUT-sound-events-2017-development.meta.zip')\n", (94497, 94560), False, 'import os\n'), ((94598, 94636), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (94610, 94636), False, 'import os\n'), ((94822, 94900), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-sound-events-2017-development.audio.1.zip"""'], {}), "(self.local_path, 'TUT-sound-events-2017-development.audio.1.zip')\n", (94834, 94900), False, 'import os\n'), ((94938, 94976), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (94950, 94976), False, 'import os\n'), ((95162, 95240), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-sound-events-2017-development.audio.2.zip"""'], {}), "(self.local_path, 'TUT-sound-events-2017-development.audio.2.zip')\n", (95174, 95240), False, 'import os\n'), ((95278, 95316), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (95290, 95316), False, 'import os\n'), ((95772, 95795), 'os.path.split', 'os.path.split', (['filename'], {}), '(filename)\n', (95785, 95795), False, 'import os\n'), ((95981, 96011), 'os.path.splitext', 'os.path.splitext', (['raw_filename'], {}), '(raw_filename)\n', (95997, 96011), False, 'import os\n'), ((99926, 99964), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (99938, 99964), False, 'import os\n'), ((100110, 100158), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""', '"""street"""'], {}), "(self.local_path, 'audio', 'street')\n", (100122, 100158), False, 'import os\n'), ((100729, 100752), 'os.path.split', 'os.path.split', (['filename'], {}), '(filename)\n', (100742, 100752), False, 'import os\n'), ((100938, 100968), 'os.path.splitext', 'os.path.splitext', (['raw_filename'], {}), '(raw_filename)\n', (100954, 100968), False, 'import os\n'), ((104316, 104365), 'os.path.join', 'os.path.join', (['self.local_path', '"""training_set.csv"""'], {}), "(self.local_path, 'training_set.csv')\n", (104328, 104365), False, 'import os\n'), ((104403, 104441), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (104415, 104441), False, 'import os\n'), ((104571, 104619), 'os.path.join', 'os.path.join', (['self.local_path', '"""testing_set.csv"""'], {}), "(self.local_path, 'testing_set.csv')\n", (104583, 104619), False, 'import os\n'), ((104657, 104695), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (104669, 104695), False, 'import os\n'), ((104849, 104921), 'os.path.join', 'os.path.join', (['self.local_path', '"""groundtruth_weak_label_training_set.csv"""'], {}), "(self.local_path, 'groundtruth_weak_label_training_set.csv')\n", (104861, 104921), False, 'import os\n'), ((104959, 104997), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (104971, 104997), False, 'import os\n'), ((105150, 105221), 'os.path.join', 'os.path.join', (['self.local_path', '"""groundtruth_weak_label_testing_set.csv"""'], {}), "(self.local_path, 'groundtruth_weak_label_testing_set.csv')\n", (105162, 105221), False, 'import os\n'), ((105259, 105297), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (105271, 105297), False, 'import os\n'), ((105430, 105481), 'os.path.join', 'os.path.join', (['self.local_path', '"""APACHE_LICENSE.txt"""'], {}), "(self.local_path, 'APACHE_LICENSE.txt')\n", (105442, 105481), False, 'import os\n'), ((105519, 105557), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (105531, 105557), False, 'import os\n'), ((105682, 105725), 'os.path.join', 'os.path.join', (['self.local_path', '"""README.txt"""'], {}), "(self.local_path, 'README.txt')\n", (105694, 105725), False, 'import os\n'), ((105763, 105801), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (105775, 105801), False, 'import os\n'), ((105947, 106011), 'os.path.join', 'os.path.join', (['self.local_path', '"""sound_event_list_17_classes.txt"""'], {}), "(self.local_path, 'sound_event_list_17_classes.txt')\n", (105959, 106011), False, 'import os\n'), ((106049, 106087), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (106061, 106087), False, 'import os\n'), ((106242, 106315), 'os.path.join', 'os.path.join', (['self.local_path', '"""groundtruth_strong_label_testing_set.csv"""'], {}), "(self.local_path, 'groundtruth_strong_label_testing_set.csv')\n", (106254, 106315), False, 'import os\n'), ((106353, 106391), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (106365, 106391), False, 'import os\n'), ((107152, 107200), 'os.path.join', 'os.path.join', (['self.local_path', '"""testing_set.csv"""'], {}), "(self.local_path, 'testing_set.csv')\n", (107164, 107200), False, 'import os\n'), ((107513, 107562), 'os.path.join', 'os.path.join', (['self.local_path', '"""training_set.csv"""'], {}), "(self.local_path, 'training_set.csv')\n", (107525, 107562), False, 'import os\n'), ((107929, 107967), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (107941, 107967), False, 'import os\n'), ((107994, 108032), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (108006, 108032), False, 'import os\n'), ((109177, 109207), 'os.path.isfile', 'os.path.isfile', (['audio_filename'], {}), '(audio_filename)\n', (109191, 109207), False, 'import os\n'), ((112943, 113002), 'os.path.join', 'os.path.join', (['self.local_path', 'self.evaluation_setup_folder'], {}), '(self.local_path, self.evaluation_setup_folder)\n', (112955, 113002), False, 'import os\n'), ((113029, 113088), 'os.path.join', 'os.path.join', (['self.local_path', 'self.evaluation_setup_folder'], {}), '(self.local_path, self.evaluation_setup_folder)\n', (113041, 113088), False, 'import os\n'), ((113773, 113803), 'os.path.isfile', 'os.path.isfile', (['train_filename'], {}), '(train_filename)\n', (113787, 113803), False, 'import os\n'), ((113811, 113840), 'os.path.isfile', 'os.path.isfile', (['test_filename'], {}), '(test_filename)\n', (113825, 113840), False, 'import os\n'), ((113848, 113881), 'os.path.isfile', 'os.path.isfile', (['evaluate_filename'], {}), '(evaluate_filename)\n', (113862, 113881), False, 'import os\n'), ((114172, 114244), 'os.path.join', 'os.path.join', (['self.local_path', '"""groundtruth_weak_label_training_set.csv"""'], {}), "(self.local_path, 'groundtruth_weak_label_training_set.csv')\n", (114184, 114244), False, 'import os\n'), ((115250, 115323), 'os.path.join', 'os.path.join', (['self.local_path', '"""groundtruth_strong_label_testing_set.csv"""'], {}), "(self.local_path, 'groundtruth_strong_label_testing_set.csv')\n", (115262, 115323), False, 'import os\n'), ((118445, 118483), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (118457, 118483), False, 'import os\n'), ((118667, 118744), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-development.doc.zip"""'], {}), "(self.local_path, 'TUT-acoustic-scenes-2016-development.doc.zip')\n", (118679, 118744), False, 'import os\n'), ((118782, 118820), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (118794, 118820), False, 'import os\n'), ((119005, 119083), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-development.meta.zip"""'], {}), "(self.local_path, 'TUT-acoustic-scenes-2016-development.meta.zip')\n", (119017, 119083), False, 'import os\n'), ((119121, 119159), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (119133, 119159), False, 'import os\n'), ((119345, 119424), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-development.error.zip"""'], {}), "(self.local_path, 'TUT-acoustic-scenes-2016-development.error.zip')\n", (119357, 119424), False, 'import os\n'), ((119462, 119500), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (119474, 119500), False, 'import os\n'), ((119688, 119773), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-development.audio.1.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2016-development.audio.1.zip')\n", (119700, 119773), False, 'import os\n'), ((119807, 119845), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (119819, 119845), False, 'import os\n'), ((120033, 120118), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-development.audio.2.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2016-development.audio.2.zip')\n", (120045, 120118), False, 'import os\n'), ((120152, 120190), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (120164, 120190), False, 'import os\n'), ((120378, 120463), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-development.audio.3.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2016-development.audio.3.zip')\n", (120390, 120463), False, 'import os\n'), ((120497, 120535), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (120509, 120535), False, 'import os\n'), ((120723, 120808), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-development.audio.4.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2016-development.audio.4.zip')\n", (120735, 120808), False, 'import os\n'), ((120842, 120880), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (120854, 120880), False, 'import os\n'), ((121068, 121153), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-development.audio.5.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2016-development.audio.5.zip')\n", (121080, 121153), False, 'import os\n'), ((121187, 121225), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (121199, 121225), False, 'import os\n'), ((121413, 121498), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-development.audio.6.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2016-development.audio.6.zip')\n", (121425, 121498), False, 'import os\n'), ((121532, 121570), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (121544, 121570), False, 'import os\n'), ((121758, 121843), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-development.audio.7.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2016-development.audio.7.zip')\n", (121770, 121843), False, 'import os\n'), ((121877, 121915), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (121889, 121915), False, 'import os\n'), ((122103, 122188), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-development.audio.8.zip"""'], {}), "(self.local_path,\n 'TUT-acoustic-scenes-2016-development.audio.8.zip')\n", (122115, 122188), False, 'import os\n'), ((122222, 122260), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (122234, 122260), False, 'import os\n'), ((125955, 125993), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (125967, 125993), False, 'import os\n'), ((126177, 126253), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-evaluation.doc.zip"""'], {}), "(self.local_path, 'TUT-acoustic-scenes-2016-evaluation.doc.zip')\n", (126189, 126253), False, 'import os\n'), ((126291, 126329), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (126303, 126329), False, 'import os\n'), ((126517, 126602), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-evaluation.audio.1.zip"""'], {}), "(self.local_path, 'TUT-acoustic-scenes-2016-evaluation.audio.1.zip'\n )\n", (126529, 126602), False, 'import os\n'), ((126635, 126673), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (126647, 126673), False, 'import os\n'), ((126861, 126946), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-evaluation.audio.2.zip"""'], {}), "(self.local_path, 'TUT-acoustic-scenes-2016-evaluation.audio.2.zip'\n )\n", (126873, 126946), False, 'import os\n'), ((126979, 127017), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (126991, 127017), False, 'import os\n'), ((127205, 127290), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-evaluation.audio.3.zip"""'], {}), "(self.local_path, 'TUT-acoustic-scenes-2016-evaluation.audio.3.zip'\n )\n", (127217, 127290), False, 'import os\n'), ((127323, 127361), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (127335, 127361), False, 'import os\n'), ((127546, 127623), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-acoustic-scenes-2016-evaluation.meta.zip"""'], {}), "(self.local_path, 'TUT-acoustic-scenes-2016-evaluation.meta.zip')\n", (127558, 127623), False, 'import os\n'), ((127661, 127699), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (127673, 127699), False, 'import os\n'), ((128025, 128081), 'os.path.join', 'os.path.join', (['self.evaluation_setup_path', '"""evaluate.txt"""'], {}), "(self.evaluation_setup_path, 'evaluate.txt')\n", (128037, 128081), False, 'import os\n'), ((131123, 131161), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (131135, 131161), False, 'import os\n'), ((131307, 131365), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""', '"""residential_area"""'], {}), "(self.local_path, 'audio', 'residential_area')\n", (131319, 131365), False, 'import os\n'), ((131511, 131557), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""', '"""home"""'], {}), "(self.local_path, 'audio', 'home')\n", (131523, 131557), False, 'import os\n'), ((131738, 131812), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-sound-events-2016-development.doc.zip"""'], {}), "(self.local_path, 'TUT-sound-events-2016-development.doc.zip')\n", (131750, 131812), False, 'import os\n'), ((131850, 131888), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (131862, 131888), False, 'import os\n'), ((132070, 132145), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-sound-events-2016-development.meta.zip"""'], {}), "(self.local_path, 'TUT-sound-events-2016-development.meta.zip')\n", (132082, 132145), False, 'import os\n'), ((132183, 132221), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (132195, 132221), False, 'import os\n'), ((132404, 132480), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-sound-events-2016-development.audio.zip"""'], {}), "(self.local_path, 'TUT-sound-events-2016-development.audio.zip')\n", (132416, 132480), False, 'import os\n'), ((132518, 132556), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (132530, 132556), False, 'import os\n'), ((133012, 133035), 'os.path.split', 'os.path.split', (['filename'], {}), '(filename)\n', (133025, 133035), False, 'import os\n'), ((133221, 133251), 'os.path.splitext', 'os.path.splitext', (['raw_filename'], {}), '(raw_filename)\n', (133237, 133251), False, 'import os\n'), ((137032, 137070), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (137044, 137070), False, 'import os\n'), ((137216, 137262), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""', '"""home"""'], {}), "(self.local_path, 'audio', 'home')\n", (137228, 137262), False, 'import os\n'), ((137408, 137466), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""', '"""residential_area"""'], {}), "(self.local_path, 'audio', 'residential_area')\n", (137420, 137466), False, 'import os\n'), ((137663, 137736), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-sound-events-2016-evaluation.doc.zip"""'], {}), "(self.local_path, 'TUT-sound-events-2016-evaluation.doc.zip')\n", (137675, 137736), False, 'import os\n'), ((137774, 137812), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (137786, 137812), False, 'import os\n'), ((138010, 138084), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-sound-events-2016-evaluation.meta.zip"""'], {}), "(self.local_path, 'TUT-sound-events-2016-evaluation.meta.zip')\n", (138022, 138084), False, 'import os\n'), ((138122, 138160), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (138134, 138160), False, 'import os\n'), ((138359, 138434), 'os.path.join', 'os.path.join', (['self.local_path', '"""TUT-sound-events-2016-evaluation.audio.zip"""'], {}), "(self.local_path, 'TUT-sound-events-2016-evaluation.audio.zip')\n", (138371, 138434), False, 'import os\n'), ((138472, 138510), 'os.path.join', 'os.path.join', (['self.local_path', '"""audio"""'], {}), "(self.local_path, 'audio')\n", (138484, 138510), False, 'import os\n'), ((138986, 139023), 'os.path.join', 'os.path.join', (['self.local_path', '"""meta"""'], {}), "(self.local_path, 'meta')\n", (138998, 139023), False, 'import os\n'), ((139140, 139184), 'csv.writer', 'csv.writer', (['meta_file_handle'], {'delimiter': '"""\t"""'}), "(meta_file_handle, delimiter='\\t')\n", (139150, 139184), False, 'import csv\n'), ((5687, 5723), 'logging.getLogger', 'logging.getLogger', (['"""dataset_factory"""'], {}), "('dataset_factory')\n", (5704, 5723), False, 'import logging\n'), ((10802, 10818), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (10812, 10818), False, 'import os\n'), ((19128, 19169), 'os.path.join', 'os.path.join', (['self.local_path', '"""tmp_file"""'], {}), "(self.local_path, 'tmp_file')\n", (19140, 19169), False, 'import os\n'), ((19923, 19965), 'os.rename', 'os.rename', (['tmp_file', "item['local_package']"], {}), "(tmp_file, item['local_package'])\n", (19932, 19965), False, 'import os\n'), ((47008, 47035), 'os.path.split', 'os.path.split', (["item['file']"], {}), "(item['file'])\n", (47021, 47035), False, 'import os\n'), ((58375, 58470), 'os.path.join', 'os.path.join', (['self.local_path', '"""generated_data"""', "('mixtures_devtrain_' + params_hash)", '"""meta"""'], {}), "(self.local_path, 'generated_data', 'mixtures_devtrain_' +\n params_hash, 'meta')\n", (58387, 58470), False, 'import os\n'), ((58628, 58707), 'os.path.join', 'os.path.join', (['mixture_meta_path', "('event_list_devtrain_' + event_label_ + '.csv')"], {}), "(mixture_meta_path, 'event_list_devtrain_' + event_label_ + '.csv')\n", (58640, 58707), False, 'import os\n'), ((61820, 61914), 'os.path.join', 'os.path.join', (['self.local_path', '"""generated_data"""', "('mixtures_devtest_' + params_hash)", '"""meta"""'], {}), "(self.local_path, 'generated_data', 'mixtures_devtest_' +\n params_hash, 'meta')\n", (61832, 61914), False, 'import os\n'), ((62072, 62150), 'os.path.join', 'os.path.join', (['mixture_meta_path', "('event_list_devtest_' + event_label_ + '.csv')"], {}), "(mixture_meta_path, 'event_list_devtest_' + event_label_ + '.csv')\n", (62084, 62150), False, 'import os\n'), ((65420, 65487), 'os.path.join', 'os.path.join', (['cv_setup_path', "('bgs_' + subset_name_on_disk + '.yaml')"], {}), "(cv_setup_path, 'bgs_' + subset_name_on_disk + '.yaml')\n", (65432, 65487), False, 'import os\n'), ((65561, 65631), 'os.path.join', 'os.path.join', (['cv_setup_path', "('events_' + subset_name_on_disk + '.yaml')"], {}), "(cv_setup_path, 'events_' + subset_name_on_disk + '.yaml')\n", (65573, 65631), False, 'import os\n'), ((67755, 67795), 'os.path.isfile', 'os.path.isfile', (['mixture_recipes_filename'], {}), '(mixture_recipes_filename)\n', (67769, 67795), False, 'import os\n'), ((69372, 69436), 'os.path.join', 'os.path.join', (['mixture_audio_path', "item['mixture_audio_filename']"], {}), "(mixture_audio_path, item['mixture_audio_filename'])\n", (69384, 69436), False, 'import os\n'), ((72439, 72473), 'os.path.isfile', 'os.path.isfile', (['mixture_parameters'], {}), '(mixture_parameters)\n', (72453, 72473), False, 'import os\n'), ((72932, 73046), 'os.path.join', 'os.path.join', (['self.local_path', '"""generated_data"""', "('mixtures_' + subset_name_on_disk + '_' + params_hash)", '"""meta"""'], {}), "(self.local_path, 'generated_data', 'mixtures_' +\n subset_name_on_disk + '_' + params_hash, 'meta')\n", (72944, 73046), False, 'import os\n'), ((73204, 73305), 'os.path.join', 'os.path.join', (['mixture_meta_path', "('event_list_' + subset_name_on_disk + '_' + class_label + '.csv')"], {}), "(mixture_meta_path, 'event_list_' + subset_name_on_disk + '_' +\n class_label + '.csv')\n", (73216, 73305), False, 'import os\n'), ((78239, 78269), 'numpy.isnan', 'numpy.isnan', (['event_instance_id'], {}), '(event_instance_id)\n', (78250, 78269), False, 'import numpy\n'), ((82387, 82398), 'dcase_framework.files.AudioFile', 'AudioFile', ([], {}), '()\n', (82396, 82398), False, 'from dcase_framework.files import AudioFile\n'), ((91162, 91251), 'os.path.join', 'os.path.join', (['self.local_path', '"""meta"""', "('event_list_evaltest_' + event_label_ + '.csv')"], {}), "(self.local_path, 'meta', 'event_list_evaltest_' + event_label_ +\n '.csv')\n", (91174, 91251), False, 'import os\n'), ((91366, 91401), 'os.path.isfile', 'os.path.isfile', (['event_list_filename'], {}), '(event_list_filename)\n', (91380, 91401), False, 'import os\n'), ((96370, 96411), 'os.path.join', 'os.path.join', (['relative_path', 'raw_filename'], {}), '(relative_path, raw_filename)\n', (96382, 96411), False, 'import os\n'), ((98301, 98328), 'os.path.split', 'os.path.split', (["item['file']"], {}), "(item['file'])\n", (98314, 98328), False, 'import os\n'), ((101299, 101340), 'os.path.join', 'os.path.join', (['relative_path', 'raw_filename'], {}), '(relative_path, raw_filename)\n', (101311, 101340), False, 'import os\n'), ((111241, 111252), 'dcase_framework.files.AudioFile', 'AudioFile', ([], {}), '()\n', (111250, 111252), False, 'from dcase_framework.files import AudioFile\n'), ((111966, 111985), 'os.remove', 'os.remove', (['tmp_file'], {}), '(tmp_file)\n', (111975, 111985), False, 'import os\n'), ((114812, 114855), 'os.path.join', 'os.path.join', (['self.local_path', "item['file']"], {}), "(self.local_path, item['file'])\n", (114824, 114855), False, 'import os\n'), ((115707, 115750), 'os.path.join', 'os.path.join', (['self.local_path', "item['file']"], {}), "(self.local_path, item['file'])\n", (115719, 115750), False, 'import os\n'), ((124534, 124561), 'os.path.split', 'os.path.split', (["item['file']"], {}), "(item['file'])\n", (124547, 124561), False, 'import os\n'), ((128349, 128376), 'os.path.split', 'os.path.split', (["item['file']"], {}), "(item['file'])\n", (128362, 128376), False, 'import os\n'), ((128484, 128525), 'os.path.join', 'os.path.join', (['relative_path', 'raw_filename'], {}), '(relative_path, raw_filename)\n', (128496, 128525), False, 'import os\n'), ((129381, 129410), 'csv.reader', 'csv.reader', (['f'], {'delimiter': '"""\t"""'}), "(f, delimiter='\\t')\n", (129391, 129410), False, 'import csv\n'), ((133610, 133651), 'os.path.join', 'os.path.join', (['relative_path', 'raw_filename'], {}), '(relative_path, raw_filename)\n', (133622, 133651), False, 'import os\n'), ((135436, 135463), 'os.path.split', 'os.path.split', (["item['file']"], {}), "(item['file'])\n", (135449, 135463), False, 'import os\n'), ((139280, 139303), 'os.path.split', 'os.path.split', (['filename'], {}), '(filename)\n', (139293, 139303), False, 'import os\n'), ((139501, 139531), 'os.path.splitext', 'os.path.splitext', (['raw_filename'], {}), '(raw_filename)\n', (139517, 139531), False, 'import os\n'), ((139787, 139822), 'os.path.isfile', 'os.path.isfile', (['annotation_filename'], {}), '(annotation_filename)\n', (139801, 139822), False, 'import os\n'), ((10903, 10922), 'os.path.splitext', 'os.path.splitext', (['f'], {}), '(f)\n', (10919, 10922), False, 'import os\n'), ((17908, 17945), 'os.path.isfile', 'os.path.isfile', (["item['local_package']"], {}), "(item['local_package'])\n", (17922, 17945), False, 'import os\n'), ((21530, 21573), 'zipfile.ZipFile', 'zipfile.ZipFile', (["item['local_package']", '"""r"""'], {}), "(item['local_package'], 'r')\n", (21545, 21573), False, 'import zipfile\n'), ((24275, 24318), 'tarfile.open', 'tarfile.open', (["item['local_package']", '"""r:gz"""'], {}), "(item['local_package'], 'r:gz')\n", (24287, 24318), False, 'import tarfile\n'), ((26050, 26074), 'os.path.join', 'os.path.join', (['path', 'name'], {}), '(path, name)\n', (26062, 26074), False, 'import os\n'), ((27327, 27384), 'os.path.join', 'os.path.join', (['self.local_path', 'self.filelisthash_filename'], {}), '(self.local_path, self.filelisthash_filename)\n', (27339, 27384), False, 'import os\n'), ((45596, 45623), 'os.path.split', 'os.path.split', (["item['file']"], {}), "(item['file'])\n", (45609, 45623), False, 'import os\n'), ((45804, 45845), 'os.path.join', 'os.path.join', (['relative_path', 'raw_filename'], {}), '(relative_path, raw_filename)\n', (45816, 45845), False, 'import os\n'), ((49259, 49286), 'os.path.split', 'os.path.split', (["item['file']"], {}), "(item['file'])\n", (49272, 49286), False, 'import os\n'), ((49467, 49508), 'os.path.join', 'os.path.join', (['relative_path', 'raw_filename'], {}), '(relative_path, raw_filename)\n', (49479, 49508), False, 'import os\n'), ((59089, 59184), 'os.path.join', 'os.path.join', (['self.local_path', '"""generated_data"""', "('mixtures_devtrain_' + params_hash)", '"""meta"""'], {}), "(self.local_path, 'generated_data', 'mixtures_devtrain_' +\n params_hash, 'meta')\n", (59101, 59184), False, 'import os\n'), ((59342, 59421), 'os.path.join', 'os.path.join', (['mixture_meta_path', "('event_list_devtrain_' + event_label_ + '.csv')"], {}), "(mixture_meta_path, 'event_list_devtrain_' + event_label_ + '.csv')\n", (59354, 59421), False, 'import os\n'), ((59806, 59900), 'os.path.join', 'os.path.join', (['self.local_path', '"""generated_data"""', "('mixtures_devtest_' + params_hash)", '"""meta"""'], {}), "(self.local_path, 'generated_data', 'mixtures_devtest_' +\n params_hash, 'meta')\n", (59818, 59900), False, 'import os\n'), ((60057, 60135), 'os.path.join', 'os.path.join', (['mixture_meta_path', "('event_list_devtest_' + event_label_ + '.csv')"], {}), "(mixture_meta_path, 'event_list_devtest_' + event_label_ + '.csv')\n", (60069, 60135), False, 'import os\n'), ((62482, 62577), 'os.path.join', 'os.path.join', (['self.local_path', '"""generated_data"""', "('mixtures_devtrain_' + params_hash)", '"""meta"""'], {}), "(self.local_path, 'generated_data', 'mixtures_devtrain_' +\n params_hash, 'meta')\n", (62494, 62577), False, 'import os\n'), ((62735, 62814), 'os.path.join', 'os.path.join', (['mixture_meta_path', "('event_list_devtrain_' + event_label_ + '.csv')"], {}), "(mixture_meta_path, 'event_list_devtrain_' + event_label_ + '.csv')\n", (62747, 62814), False, 'import os\n'), ((63219, 63313), 'os.path.join', 'os.path.join', (['self.local_path', '"""generated_data"""', "('mixtures_devtest_' + params_hash)", '"""meta"""'], {}), "(self.local_path, 'generated_data', 'mixtures_devtest_' +\n params_hash, 'meta')\n", (63231, 63313), False, 'import os\n'), ((63471, 63549), 'os.path.join', 'os.path.join', (['mixture_meta_path', "('event_list_devtest_' + event_label_ + '.csv')"], {}), "(mixture_meta_path, 'event_list_devtest_' + event_label_ + '.csv')\n", (63483, 63549), False, 'import os\n'), ((69465, 69493), 'os.path.isfile', 'os.path.isfile', (['mixture_file'], {}), '(mixture_file)\n', (69479, 69493), False, 'import os\n'), ((69851, 69902), 'dcase_framework.files.AudioFile', 'AudioFile', ([], {'data': 'mixture', 'fs': "params['mixture']['fs']"}), "(data=mixture, fs=params['mixture']['fs'])\n", (69860, 69902), False, 'from dcase_framework.files import AudioFile\n'), ((78439, 78490), 'os.path.join', 'os.path.join', (['background_audio_path', "bg['filepath']"], {}), "(background_audio_path, bg['filepath'])\n", (78451, 78490), False, 'import os\n'), ((80686, 80711), 'yaml.dump', 'yaml.dump', (['mixture_recipe'], {}), '(mixture_recipe)\n', (80695, 80711), False, 'import yaml\n'), ((86209, 86227), 'numpy.abs', 'numpy.abs', (['mixture'], {}), '(mixture)\n', (86218, 86227), False, 'import numpy\n'), ((89500, 89535), 'os.path.join', 'os.path.join', (['"""audio"""', "item['file']"], {}), "('audio', item['file'])\n", (89512, 89535), False, 'import os\n'), ((89764, 89787), 'os.path.split', 'os.path.split', (['filename'], {}), '(filename)\n', (89777, 89787), False, 'import os\n'), ((89920, 89950), 'os.path.splitext', 'os.path.splitext', (['raw_filename'], {}), '(raw_filename)\n', (89936, 89950), False, 'import os\n'), ((96507, 96537), 'os.path.splitext', 'os.path.splitext', (['raw_filename'], {}), '(raw_filename)\n', (96523, 96537), False, 'import os\n'), ((98370, 98400), 'os.path.splitext', 'os.path.splitext', (['raw_filename'], {}), '(raw_filename)\n', (98386, 98400), False, 'import os\n'), ((101436, 101466), 'os.path.splitext', 'os.path.splitext', (['raw_filename'], {}), '(raw_filename)\n', (101452, 101466), False, 'import os\n'), ((112403, 112422), 'os.remove', 'os.remove', (['tmp_file'], {}), '(tmp_file)\n', (112412, 112422), False, 'import os\n'), ((112443, 112468), 'os.remove', 'os.remove', (['audio_filename'], {}), '(audio_filename)\n', (112452, 112468), False, 'import os\n'), ((123176, 123203), 'os.path.split', 'os.path.split', (["item['file']"], {}), "(item['file'])\n", (123189, 123203), False, 'import os\n'), ((123384, 123425), 'os.path.join', 'os.path.join', (['relative_path', 'raw_filename'], {}), '(relative_path, raw_filename)\n', (123396, 123425), False, 'import os\n'), ((133747, 133777), 'os.path.splitext', 'os.path.splitext', (['raw_filename'], {}), '(raw_filename)\n', (133763, 133777), False, 'import os\n'), ((135505, 135535), 'os.path.splitext', 'os.path.splitext', (['raw_filename'], {}), '(raw_filename)\n', (135521, 135535), False, 'import os\n'), ((141383, 141412), 'csv.reader', 'csv.reader', (['f'], {'delimiter': '"""\t"""'}), "(f, delimiter='\\t')\n", (141393, 141412), False, 'import csv\n'), ((141781, 141810), 'csv.reader', 'csv.reader', (['f'], {'delimiter': '"""\t"""'}), "(f, delimiter='\\t')\n", (141791, 141810), False, 'import csv\n'), ((21879, 21906), 'os.path.commonprefix', 'os.path.commonprefix', (['parts'], {}), '(parts)\n', (21899, 21906), False, 'import os\n'), ((25889, 25911), 'os.path.splitext', 'os.path.splitext', (['name'], {}), '(name)\n', (25905, 25911), False, 'import os\n'), ((25918, 25962), 'os.path.splitext', 'os.path.splitext', (['self.filelisthash_filename'], {}), '(self.filelisthash_filename)\n', (25934, 25962), False, 'import os\n'), ((25970, 25989), 'os.path.split', 'os.path.split', (['path'], {}), '(path)\n', (25983, 25989), False, 'import os\n'), ((71497, 71627), 'os.path.join', 'os.path.join', (['"""generated_data"""', "('mixtures_' + subset_name_on_disk + '_' + params_hash)", '"""audio"""', "item['mixture_audio_filename']"], {}), "('generated_data', 'mixtures_' + subset_name_on_disk + '_' +\n params_hash, 'audio', item['mixture_audio_filename'])\n", (71509, 71627), False, 'import os\n'), ((74497, 74509), 'numpy.abs', 'numpy.abs', (['y'], {}), '(y)\n', (74506, 74509), False, 'import numpy\n'), ((86483, 86507), 'numpy.abs', 'numpy.abs', (['bg_audio_data'], {}), '(bg_audio_data)\n', (86492, 86507), False, 'import numpy\n'), ((86546, 86569), 'numpy.abs', 'numpy.abs', (['padded_event'], {}), '(padded_event)\n', (86555, 86569), False, 'import numpy\n'), ((86606, 86624), 'numpy.abs', 'numpy.abs', (['mixture'], {}), '(mixture)\n', (86615, 86624), False, 'import numpy\n'), ((91777, 91812), 'os.path.join', 'os.path.join', (['"""audio"""', "item['file']"], {}), "('audio', item['file'])\n", (91789, 91812), False, 'import os\n'), ((139987, 140037), 'csv.reader', 'csv.reader', (['annotation_file_handle'], {'delimiter': '"""\t"""'}), "(annotation_file_handle, delimiter='\\t')\n", (139997, 140037), False, 'import csv\n'), ((141664, 141732), 'os.path.join', 'os.path.join', (['self.evaluation_setup_path', "(scene_label_ + '_test.txt')"], {}), "(self.evaluation_setup_path, scene_label_ + '_test.txt')\n", (141676, 141732), False, 'import os\n'), ((26577, 26634), 'os.path.join', 'os.path.join', (['self.local_path', 'self.filelisthash_filename'], {}), '(self.local_path, self.filelisthash_filename)\n', (26589, 26634), False, 'import os\n'), ((11042, 11063), 'os.path.join', 'os.path.join', (['path', 'f'], {}), '(path, f)\n', (11054, 11063), False, 'import os\n'), ((25170, 25214), 'os.path.join', 'os.path.join', (['self.local_path', 'tar_info.name'], {}), '(self.local_path, tar_info.name)\n', (25182, 25214), False, 'import os\n'), ((11150, 11171), 'os.path.join', 'os.path.join', (['path', 'f'], {}), '(path, f)\n', (11162, 11171), False, 'import os\n'), ((23604, 23650), 'os.path.join', 'os.path.join', (['self.local_path', 'member.filename'], {}), '(self.local_path, member.filename)\n', (23616, 23650), False, 'import os\n'), ((90079, 90120), 'os.path.join', 'os.path.join', (['relative_path', 'raw_filename'], {}), '(relative_path, raw_filename)\n', (90091, 90120), False, 'import os\n'), ((114364, 114394), 'os.path.splitext', 'os.path.splitext', (["item['file']"], {}), "(item['file'])\n", (114380, 114394), False, 'import os\n'), ((115443, 115473), 'os.path.splitext', 'os.path.splitext', (["item['file']"], {}), "(item['file'])\n", (115459, 115473), False, 'import os\n'), ((140166, 140207), 'os.path.join', 'os.path.join', (['relative_path', 'raw_filename'], {}), '(relative_path, raw_filename)\n', (140178, 140207), False, 'import os\n'), ((24124, 24134), 'sys.exit', 'sys.exit', ([], {}), '()\n', (24132, 24134), False, 'import sys\n'), ((23988, 24034), 'os.path.join', 'os.path.join', (['self.local_path', 'member.filename'], {}), '(self.local_path, member.filename)\n', (24000, 24034), False, 'import os\n')] |
import logging
import collections
import json
import time
import string
import random
logger = logging.getLogger(__name__)
from schematics.types import BaseType
from schematics.exceptions import ValidationError
from nymms.utils import parse_time
import arrow
class TimestampType(BaseType):
def to_native(self, value, context=None):
if isinstance(value, arrow.arrow.Arrow):
return value
try:
return parse_time(value)
except ValueError:
return arrow.get(value)
def to_primitive(self, value, context=None):
return value.isoformat()
def _mock(self, context=None):
year = 86400 * 365
return arrow.get(time.time() + (random.randrange(-1 * 20 * year,
200 * year)))
class JSONType(BaseType):
def to_native(self, value, context=None):
if isinstance(value, basestring):
return json.loads(value)
return value
def to_primitive(self, value, context=None):
return json.dumps(value)
def _mock(self, context=None):
return dict(
[(random.choice(string.ascii_letters),
random.choice(string.printable)) for i in
range(random.randrange(4, 10))])
StateObject = collections.namedtuple('StateObject', ['name', 'code'])
STATE_OK = StateObject('ok', 0)
STATE_WARNING = STATE_WARN = StateObject('warning', 1)
STATE_CRITICAL = STATE_CRIT = StateObject('critical', 2)
STATE_UNKNOWN = StateObject('unknown', 3)
STATES = collections.OrderedDict([
('ok', STATE_OK),
('warning', STATE_WARNING),
('critical', STATE_CRITICAL),
('unknown', STATE_UNKNOWN)])
class StateType(BaseType):
def __init__(self, *args, **kwargs):
super(StateType, self).__init__(*args, choices=STATES.values(),
**kwargs)
def to_native(self, value, context=None):
if isinstance(value, StateObject):
return value
try:
int_value = int(value)
try:
return STATES.values()[int_value]
except IndexError:
return STATE_UNKNOWN
except ValueError:
try:
return STATES[value.lower()]
except KeyError:
raise ValidationError(self.messages['choices'].format(
unicode(self.choices)))
def to_primitive(self, value, context=None):
return value.code
class StateNameType(StateType):
def to_primitive(self, value, context=None):
return value.name
StateTypeObject = collections.namedtuple('StateTypeObject', ['name', 'code'])
STATE_TYPE_SOFT = StateTypeObject('soft', 0)
STATE_TYPE_HARD = StateTypeObject('hard', 1)
STATE_TYPES = collections.OrderedDict([
('soft', STATE_TYPE_SOFT),
('hard', STATE_TYPE_HARD)])
class StateTypeType(BaseType):
def __init__(self, *args, **kwargs):
super(StateTypeType, self).__init__(*args,
choices=STATE_TYPES.values(),
**kwargs)
def to_native(self, value, context=None):
if isinstance(value, StateTypeObject):
return value
try:
return STATE_TYPES.values()[int(value)]
except ValueError:
try:
return STATE_TYPES[value.lower()]
except KeyError:
raise ValidationError(self.messages['choices'].format(
unicode(self.choices)))
def to_primitive(self, value, context=None):
return value.code
class StateTypeNameType(StateTypeType):
def to_primitive(self, value, context=None):
return value.name
| [
"logging.getLogger",
"collections.OrderedDict",
"collections.namedtuple",
"nymms.utils.parse_time",
"json.loads",
"random.choice",
"random.randrange",
"json.dumps",
"arrow.get",
"time.time"
] | [((96, 123), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (113, 123), False, 'import logging\n'), ((1302, 1357), 'collections.namedtuple', 'collections.namedtuple', (['"""StateObject"""', "['name', 'code']"], {}), "('StateObject', ['name', 'code'])\n", (1324, 1357), False, 'import collections\n'), ((1553, 1687), 'collections.OrderedDict', 'collections.OrderedDict', (["[('ok', STATE_OK), ('warning', STATE_WARNING), ('critical', STATE_CRITICAL),\n ('unknown', STATE_UNKNOWN)]"], {}), "([('ok', STATE_OK), ('warning', STATE_WARNING), (\n 'critical', STATE_CRITICAL), ('unknown', STATE_UNKNOWN)])\n", (1576, 1687), False, 'import collections\n'), ((2628, 2687), 'collections.namedtuple', 'collections.namedtuple', (['"""StateTypeObject"""', "['name', 'code']"], {}), "('StateTypeObject', ['name', 'code'])\n", (2650, 2687), False, 'import collections\n'), ((2792, 2871), 'collections.OrderedDict', 'collections.OrderedDict', (["[('soft', STATE_TYPE_SOFT), ('hard', STATE_TYPE_HARD)]"], {}), "([('soft', STATE_TYPE_SOFT), ('hard', STATE_TYPE_HARD)])\n", (2815, 2871), False, 'import collections\n'), ((1058, 1075), 'json.dumps', 'json.dumps', (['value'], {}), '(value)\n', (1068, 1075), False, 'import json\n'), ((448, 465), 'nymms.utils.parse_time', 'parse_time', (['value'], {}), '(value)\n', (458, 465), False, 'from nymms.utils import parse_time\n'), ((954, 971), 'json.loads', 'json.loads', (['value'], {}), '(value)\n', (964, 971), False, 'import json\n'), ((512, 528), 'arrow.get', 'arrow.get', (['value'], {}), '(value)\n', (521, 528), False, 'import arrow\n'), ((700, 711), 'time.time', 'time.time', ([], {}), '()\n', (709, 711), False, 'import time\n'), ((715, 759), 'random.randrange', 'random.randrange', (['(-1 * 20 * year)', '(200 * year)'], {}), '(-1 * 20 * year, 200 * year)\n', (731, 759), False, 'import random\n'), ((1147, 1182), 'random.choice', 'random.choice', (['string.ascii_letters'], {}), '(string.ascii_letters)\n', (1160, 1182), False, 'import random\n'), ((1198, 1229), 'random.choice', 'random.choice', (['string.printable'], {}), '(string.printable)\n', (1211, 1229), False, 'import random\n'), ((1259, 1282), 'random.randrange', 'random.randrange', (['(4)', '(10)'], {}), '(4, 10)\n', (1275, 1282), False, 'import random\n')] |
from datetime import datetime
import decimal
import json
import os
import random
import uuid
import boto3
from botocore.exceptions import ClientError
# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
if o % 1 > 0:
return float(o)
else:
return int(o)
return super(DecimalEncoder, self).default(o)
# Get the service resource.
dynamodb = boto3.resource('dynamodb')
step_functions = boto3.client("stepfunctions")
sqs = boto3.client("sqs")
# set environment variable
TABLE_NAME = os.environ.get("TABLE_NAME")
STEP_FUNCTION_ARN = os.environ.get("STEP_FUNCTION_ARN")
QUEUE_URL = os.environ.get("QUEUE_URL")
def _decode_payload(event: dict) -> dict:
# get insert data from apigw
if "body" in event:
payload = json.loads(event['body'])
elif "data" in event:
payload = event['data']
else:
raise ValueError("'body' or 'data' is required.")
return payload
def consumer(event, context):
table = dynamodb.Table(TABLE_NAME)
scan_data = []
# Scan items in table
try:
response = table.scan()
except ClientError as e:
print(e.response['Error']['Message'])
else:
scan_data = []
# print item of the table - see CloudWatch logs
for i in response['Items']:
scan_data.append(i)
print(i)
return {
'statusCode': 200,
"body": json.dumps({"response": scan_data}, cls=DecimalEncoder)
}
def producer(event, context):
table = dynamodb.Table(TABLE_NAME)
# get data from payload
payload = _decode_payload(event=event)
id_ = str(uuid.uuid4())
payload.update({"id": id_})
# en-queue
sqs.send_message(
QueueUrl=QUEUE_URL,
MessageBody=id_
)
# put item in table
response = table.put_item(
Item=payload
)
print(f"item to insert: {payload}")
print("PutItem succeeded:")
print(json.dumps(response, indent=4, cls=DecimalEncoder))
return {
'statusCode': 200,
"body": json.dumps({"insert": payload})
}
def update_status(event, context):
table = dynamodb.Table(TABLE_NAME)
# get data from payload
payload = _decode_payload(event=event)
response = table.update_item(
Key={
"id": payload['id']
},
UpdateExpression="set #status = :status",
ExpressionAttributeNames={
'#status': 'status'
},
ExpressionAttributeValues={
':status': payload['status']
},
ReturnValues="UPDATED_NEW"
)
return {
"statusCode": 200,
"body": json.dumps({"update": response})
}
def invoke_step_function(event, _):
"""
queue message is received as
{
"Messages": [
{
"MessageId": "...",
"ReceiptHandle": "...",
"MD5OfBody": "...",
"Body": "..."
}
],
"ResponseMetadata": {
"RequestId": "...",
"HttpStatusCode": 200,
"HTTPHeaders": {
"x-amzn-requestid": "...",
"data": "Sun, 22 Nov 2020 02:15:28 GMT",
"content-type": "text/xml",
"content-length": 123
},
"RetryAttempts": 0
}
}
"""
# get data from queue
message = sqs.receive_message(
QueueUrl=QUEUE_URL,
MaxNumberOfMessages=1,
VisibilityTimeout=30
)
print(message)
if "Messages" in message:
queue_message = message['Messages'][0]
id_ = queue_message['Body']
step_functions.start_execution(
stateMachineArn=STEP_FUNCTION_ARN,
name=f"process_for_{id_}_{datetime.now().strftime('%Y%m%dT%H%M%S')}",
input=json.dumps({
"id": id_,
# to choice `success` or `failure` in SFn
"job_status": "success" if random.randint(1, 10) < 5 else "fail"
})
)
# delete message
_ = sqs.delete_message(
QueueUrl=QUEUE_URL,
ReceiptHandle=queue_message['ReceiptHandle']
)
else:
pass
| [
"json.loads",
"boto3.client",
"json.dumps",
"os.environ.get",
"uuid.uuid4",
"datetime.datetime.now",
"boto3.resource",
"random.randint"
] | [((514, 540), 'boto3.resource', 'boto3.resource', (['"""dynamodb"""'], {}), "('dynamodb')\n", (528, 540), False, 'import boto3\n'), ((558, 587), 'boto3.client', 'boto3.client', (['"""stepfunctions"""'], {}), "('stepfunctions')\n", (570, 587), False, 'import boto3\n'), ((594, 613), 'boto3.client', 'boto3.client', (['"""sqs"""'], {}), "('sqs')\n", (606, 613), False, 'import boto3\n'), ((655, 683), 'os.environ.get', 'os.environ.get', (['"""TABLE_NAME"""'], {}), "('TABLE_NAME')\n", (669, 683), False, 'import os\n'), ((704, 739), 'os.environ.get', 'os.environ.get', (['"""STEP_FUNCTION_ARN"""'], {}), "('STEP_FUNCTION_ARN')\n", (718, 739), False, 'import os\n'), ((752, 779), 'os.environ.get', 'os.environ.get', (['"""QUEUE_URL"""'], {}), "('QUEUE_URL')\n", (766, 779), False, 'import os\n'), ((899, 924), 'json.loads', 'json.loads', (["event['body']"], {}), "(event['body'])\n", (909, 924), False, 'import json\n'), ((1538, 1593), 'json.dumps', 'json.dumps', (["{'response': scan_data}"], {'cls': 'DecimalEncoder'}), "({'response': scan_data}, cls=DecimalEncoder)\n", (1548, 1593), False, 'import json\n'), ((1756, 1768), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (1766, 1768), False, 'import uuid\n'), ((2065, 2115), 'json.dumps', 'json.dumps', (['response'], {'indent': '(4)', 'cls': 'DecimalEncoder'}), '(response, indent=4, cls=DecimalEncoder)\n', (2075, 2115), False, 'import json\n'), ((2174, 2205), 'json.dumps', 'json.dumps', (["{'insert': payload}"], {}), "({'insert': payload})\n", (2184, 2205), False, 'import json\n'), ((2764, 2796), 'json.dumps', 'json.dumps', (["{'update': response}"], {}), "({'update': response})\n", (2774, 2796), False, 'import json\n'), ((3881, 3895), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (3893, 3895), False, 'from datetime import datetime\n'), ((4084, 4105), 'random.randint', 'random.randint', (['(1)', '(10)'], {}), '(1, 10)\n', (4098, 4105), False, 'import random\n')] |
from .socket import Socket
from socket import timeout as sockTimeout
from ... import Logger, DummyLog
import threading
import sys
import warnings
_QUEUEDSOCKET_IDENTIFIER_ = '<agutil.io.queuedsocket:1.0.0>'
class QueuedSocket(Socket):
def __init__(
self,
address,
port,
logmethod=DummyLog,
_socket=None
):
warnings.warn(
"QueuedSocket is now deprecated and will be"
" removed in a future release",
DeprecationWarning
)
super().__init__(address, port, _socket)
self.incoming = {'__orphan__': []}
self.outgoing = {}
self.outgoing_index = 0
self._shutdown = False
self.datalock = threading.Condition()
self.new_messages = threading.Event()
self.message_sent = threading.Event()
self._qs_log = logmethod
if isinstance(self._qs_log, Logger):
self._qs_log = self._qs_log.bindToSender("QueuedSocket")
self._qs_log(
"The underlying Socket has been initialized. "
"Starting background thread..."
)
self._thread = threading.Thread(
target=QueuedSocket._worker,
args=(self,),
name="QueuedSocket background thread",
daemon=True
)
self._thread.start()
QueuedSocket.send(self, _QUEUEDSOCKET_IDENTIFIER_, '__protocol__')
remoteID = QueuedSocket.recv(self, '__protocol__', True)
if remoteID != _QUEUEDSOCKET_IDENTIFIER_:
self._qs_log(
"The remote socket provided an invalid QueuedSocket "
"protocol identifier. (Theirs: %s) (Ours: %s)" % (
remoteID,
_QUEUEDSOCKET_IDENTIFIER_
),
"WARN"
)
self.close()
raise ValueError(
"The remote socket provided an invalid identifier "
"at the QueuedSocket level"
)
def close(self, timeout=1):
if self._shutdown:
return
self._qs_log(
"Shutdown initiated. Waiting for background thread to "
"send remaining messages (%d channels queued)" % len(self.outgoing)
)
with self.datalock:
self._shutdown = True
self._thread.join(timeout)
super().close()
self._qs_log.close()
def send(self, msg, channel='__orphan__'):
if self._shutdown:
self._qs_log(
"Attempt to use the QueuedSocket after shutdown",
"WARN"
)
raise IOError("This QueuedSocket has already been closed")
if '^' in channel:
self._qs_log(
"Attempt to send message over illegal channel name",
"WARN"
)
raise ValueError(
"Channel names cannot contain '^' characters (ascii 94)"
)
if type(msg) == str:
msg = msg.encode()
elif type(msg) != bytes:
raise TypeError("msg argument must be str or bytes")
if not self._thread.is_alive():
self._qs_log(
"The background thread has crashed or stopped before the "
"QueuedSocket shut down. Restarting thread...",
"WARN"
)
self._thread = threading.Thread(
target=QueuedSocket._worker,
args=(self,),
name="QueuedSocket background thread",
daemon=True
)
self._thread.start()
self._qs_log("The background thread has been restarted", "INFO")
with self.datalock:
if channel not in self.outgoing:
self.outgoing[channel] = []
self.outgoing[channel].append(msg)
self._qs_log("Message Queued on channel '%s'" % channel, "DEBUG")
def recv(
self,
channel='__orphan__',
decode=False,
timeout=None,
_logInit=True
):
if self._shutdown:
self._qs_log(
"Attempt to use the QueuedSocket after shutdown",
"WARN"
)
raise IOError("This QueuedSocket has already been closed")
if not self._thread.is_alive():
self._qs_log(
"The background thread has crashed or stopped before the "
"QueuedSocket shut down. Restarting thread...",
"WARN"
)
self._thread = threading.Thread(
target=QueuedSocket._worker,
args=(self,),
name="QueuedSocket background thread",
daemon=True
)
self._thread.start()
self._qs_log("The background thread has been restarted", "INFO")
with self.datalock:
if channel not in self.incoming:
self.incoming[channel] = []
if _logInit:
self._qs_log(
"Waiting for input on channel '%s'" % channel,
"DEBUG"
)
while not self._check_channel(channel):
result = self.new_messages.wait(timeout)
if not result:
raise sockTimeout()
self.new_messages.clear()
self._qs_log("Input dequeued from channel '%s'" % channel, "DETAIL")
msg = self.incoming[channel].pop(0)
if decode:
msg = msg.decode()
return msg
def flush(self):
while len(self.outgoing):
self.message_sent.wait()
self.message_sent.clear()
def _sends(self, msg, channel):
channel = ":ch#"+channel+"^"
if type(msg) == bytes:
channel = channel.encode()
msg = channel + msg
# print("Sends:", msg)
super().send(msg)
def _recvs(self):
msg = super().recv()
# print("Recvs:", msg)
if msg[:4] == b':ch#':
channel = b""
i = 4
while msg[i:i+1] != b'^':
channel += msg[i:i+1]
i += 1
return (channel.decode(), msg[i+1:])
return ("__orphan__", msg)
def _check_channel(self, channel):
return len(self.incoming[channel])
def _worker(self):
self._qs_log("QueuedSocket background thread initialized")
outqueue = len(self.outgoing)
while outqueue or not self._shutdown:
if outqueue:
with self.datalock:
self.outgoing_index = (self.outgoing_index + 1) % outqueue
target = list(self.outgoing)[self.outgoing_index]
payload = self.outgoing[target].pop(0)
self.outgoing = {
k: v for k, v in self.outgoing.items() if len(v)
}
self._qs_log(
"Outgoing payload on channel '%s'" % target,
"DEBUG"
)
try:
self._sends(payload, target)
self.message_sent.set()
except (OSError, BrokenPipeError) as e:
if self._shutdown:
self._qs_log(
"QueuedSocket background thread halted "
"(attempted to send after shutdown)"
)
return
else:
self._qs_log(
"QueuedSocket encountered an error: "+str(e),
"ERROR"
)
raise e
if not self._shutdown:
super().settimeout(.025)
try:
(channel, payload) = self._recvs()
self._qs_log(
"Incoming payload on channel '%s'" % channel,
"DEBUG"
)
with self.datalock:
if channel not in self.incoming:
self.incoming[channel] = []
self.incoming[channel].append(payload)
self.new_messages.set()
self._qs_log(
"Threads waiting on '%s' have been notified" % channel,
"DETAIL"
)
except sockTimeout:
pass
except (OSError, BrokenPipeError) as e:
if self._shutdown:
self._qs_log("QueuedSocket background thread halted")
return
else:
self._qs_log(
"QueuedSocket encountered an error: "+str(e),
"ERROR"
)
raise e
outqueue = len(self.outgoing)
| [
"threading.Event",
"socket.timeout",
"warnings.warn",
"threading.Thread",
"threading.Condition"
] | [((365, 481), 'warnings.warn', 'warnings.warn', (['"""QueuedSocket is now deprecated and will be removed in a future release"""', 'DeprecationWarning'], {}), "(\n 'QueuedSocket is now deprecated and will be removed in a future release',\n DeprecationWarning)\n", (378, 481), False, 'import warnings\n'), ((728, 749), 'threading.Condition', 'threading.Condition', ([], {}), '()\n', (747, 749), False, 'import threading\n'), ((778, 795), 'threading.Event', 'threading.Event', ([], {}), '()\n', (793, 795), False, 'import threading\n'), ((824, 841), 'threading.Event', 'threading.Event', ([], {}), '()\n', (839, 841), False, 'import threading\n'), ((1148, 1264), 'threading.Thread', 'threading.Thread', ([], {'target': 'QueuedSocket._worker', 'args': '(self,)', 'name': '"""QueuedSocket background thread"""', 'daemon': '(True)'}), "(target=QueuedSocket._worker, args=(self,), name=\n 'QueuedSocket background thread', daemon=True)\n", (1164, 1264), False, 'import threading\n'), ((3402, 3518), 'threading.Thread', 'threading.Thread', ([], {'target': 'QueuedSocket._worker', 'args': '(self,)', 'name': '"""QueuedSocket background thread"""', 'daemon': '(True)'}), "(target=QueuedSocket._worker, args=(self,), name=\n 'QueuedSocket background thread', daemon=True)\n", (3418, 3518), False, 'import threading\n'), ((4569, 4685), 'threading.Thread', 'threading.Thread', ([], {'target': 'QueuedSocket._worker', 'args': '(self,)', 'name': '"""QueuedSocket background thread"""', 'daemon': '(True)'}), "(target=QueuedSocket._worker, args=(self,), name=\n 'QueuedSocket background thread', daemon=True)\n", (4585, 4685), False, 'import threading\n'), ((5284, 5297), 'socket.timeout', 'sockTimeout', ([], {}), '()\n', (5295, 5297), True, 'from socket import timeout as sockTimeout\n')] |
#!/usr/bin/env python3
from astropy.modeling.models import Const1D, Const2D, Gaussian1D, Gaussian2D
from astropy.modeling.fitting import LevMarLSQFitter
from astropy.modeling import Fittable2DModel, Parameter
import sys
import logging
import argparse
import warnings
from datetime import datetime
from glob import glob
import numpy as np
import scipy.ndimage as nd
from matplotlib.patches import Ellipse
import matplotlib.pyplot as plt
from astropy.io import fits
from astropy.stats import sigma_clipped_stats
from astropy.wcs import WCS
from astropy.table import Table
from astropy.wcs import FITSFixedWarning
import photutils as pu
import sep
parser = argparse.ArgumentParser()
parser.add_argument('files', nargs='*', help='files to process')
parser.add_argument('--reprocess', action='store_true')
parser.add_argument('--verbose', '-v', action='store_true',
help='verbose logging')
args = parser.parse_args()
######################################################################
class GaussianConst2D(Fittable2DModel):
"""A model for a 2D Gaussian plus a constant.
Code from photutils (Copyright (c) 2011, Photutils developers).
Parameters
----------
constant : float
Value of the constant.
amplitude : float
Amplitude of the Gaussian.
x_mean : float
Mean of the Gaussian in x.
y_mean : float
Mean of the Gaussian in y.
x_stddev : float
Standard deviation of the Gaussian in x. ``x_stddev`` and
``y_stddev`` must be specified unless a covariance matrix
(``cov_matrix``) is input.
y_stddev : float
Standard deviation of the Gaussian in y. ``x_stddev`` and
``y_stddev`` must be specified unless a covariance matrix
(``cov_matrix``) is input.
theta : float, optional
Rotation angle in radians. The rotation angle increases
counterclockwise.
"""
constant = Parameter(default=1)
amplitude = Parameter(default=1)
x_mean = Parameter(default=0)
y_mean = Parameter(default=0)
x_stddev = Parameter(default=1)
y_stddev = Parameter(default=1)
theta = Parameter(default=0)
@staticmethod
def evaluate(x, y, constant, amplitude, x_mean, y_mean, x_stddev,
y_stddev, theta):
"""Two dimensional Gaussian plus constant function."""
model = Const2D(constant)(x, y) + Gaussian2D(amplitude, x_mean,
y_mean, x_stddev,
y_stddev, theta)(x, y)
return model
def fit_2dgaussian(data):
"""Fit a 2D Gaussian plus a constant to a 2D image.
Based on code from photutils (Copyright (c) 2011, Photutils developers).
Parameters
----------
data : array_like
The 2D array of the image.
Returns
-------
result : A `GaussianConst2D` model instance.
The best-fitting Gaussian 2D model.
"""
if np.ma.count(data) < 7:
raise ValueError('Input data must have a least 7 unmasked values to '
'fit a 2D Gaussian plus a constant.')
data.fill_value = 0.
data = data.filled()
# Subtract the minimum of the data as a rough background estimate.
# This will also make the data values positive, preventing issues with
# the moment estimation in data_properties. Moments from negative data
# values can yield undefined Gaussian parameters, e.g., x/y_stddev.
data = data - np.min(data)
guess_y, guess_x = np.array(data.shape) / 2
init_amplitude = np.ptp(data)
g_init = GaussianConst2D(constant=0, amplitude=init_amplitude,
x_mean=guess_x,
y_mean=guess_y,
x_stddev=3,
y_stddev=3,
theta=0)
fitter = LevMarLSQFitter()
y, x = np.indices(data.shape)
gfit = fitter(g_init, x, y, data)
return gfit
######################################################################
# setup logging
logger = logging.Logger('LMI Add Catalog')
logger.setLevel(logging.DEBUG)
# this allows logging to work when lmi-add-cat is run multiple times from
# ipython
if len(logger.handlers) == 0:
formatter = logging.Formatter('%(levelname)s: %(message)s')
level = logging.DEBUG if args.verbose else logging.INFO
console = logging.StreamHandler(sys.stdout)
console.setLevel(level)
console.setFormatter(formatter)
logger.addHandler(console)
logfile = logging.FileHandler('lmi-add-cat.log')
logfile.setLevel(level)
logfile.setFormatter(formatter)
logger.addHandler(logfile)
logger.info('#' * 70)
logger.info(datetime.now().isoformat())
logger.info('Command line: ' + ' '.join(sys.argv[1:]))
######################################################################
# suppress unnecessary warnings
warnings.simplefilter('ignore', FITSFixedWarning)
######################################################################
def show_objects(im, objects):
# plot background-subtracted image
fig, ax = plt.subplots()
m, s = np.mean(im), np.std(im)
im = ax.imshow(im, interpolation='nearest', cmap='gray',
vmin=m-s, vmax=m+s, origin='lower')
# plot an ellipse for each object
for i in range(len(objects)):
e = Ellipse(xy=(objects['x'][i], objects['y'][i]),
width=6*objects['a'][i],
height=6*objects['b'][i],
angle=objects['theta'][i] * 180. / np.pi)
e.set_facecolor('none')
e.set_edgecolor('red')
ax.add_artist(e)
for f in args.files:
if fits.getheader(f)['IMAGETYP'] != 'OBJECT':
continue
logger.debug(f)
with fits.open(f, mode='update') as hdu:
im = hdu[0].data + 0
h = hdu[0].header
if h['IMAGETYP'].upper() != 'OBJECT':
logger.warning(
f'Refusing to measure {f} with image type {h["imagetyp"]}.')
continue
if 'MASK' in hdu:
mask = hdu['MASK'].data.astype(bool)
else:
mask = np.zeros_like(im, bool)
if 'cat' in hdu:
if not args.reprocess:
continue
else:
del hdu['cat']
det = np.zeros_like(mask)
for iteration in range(3):
bkg = sep.Background(im, mask=det | mask, bw=64, bh=64, fw=3, fh=3)
# mask potential sources
det = ((im - bkg) / bkg.globalrms) > 3
# remove isolated pixels
det = nd.binary_closing(det)
bkg = sep.Background(im, mask=det | mask, bw=64, bh=64, fw=3, fh=3)
if 'bg' in hdu:
del hdu['bg']
hdu.append(fits.ImageHDU(bkg.back(), name='bg'))
hdu['bg'].header['bg'] = bkg.globalback
hdu['bg'].header['rms'] = bkg.globalrms
data = im - bkg
data[mask] = 0
try:
objects, labels = sep.extract(data, 3, err=bkg.globalrms,
segmentation_map=True)
except Exception as e:
logger.error(f'{f}: Object detection failed - {str(e)}')
continue
hdu[0].header['ncat'] = len(objects), 'number of objects in catalog'
if len(objects) == 0:
continue
#show_objects(data, objects)
# estimate seeing
fwhms = []
segmap = pu.SegmentationImage(labels)
for i in np.random.choice(len(segmap.segments), 50):
obj = segmap.segments[i].make_cutout(data, masked_array=True)
try:
g = fit_2dgaussian(obj)
except:
continue
fwhm = np.mean((g.x_stddev.value, g.y_stddev.value)) * 2.35
if fwhm < 1:
continue
fwhms.append(fwhm)
fwhm = sigma_clipped_stats(fwhms)[1]
rap = fwhm * 2 if np.isfinite(fwhm) else 10
flux, fluxerr, flag = sep.sum_circle(
data, objects['x'], objects['y'], rap, err=bkg.globalrms,
gain=h['gain'])
kronrad, krflag = sep.kron_radius(data, objects['x'], objects['y'],
objects['a'], objects['b'],
objects['theta'], 6.0)
krflux, krfluxerr, _flag = sep.sum_ellipse(
data, objects['x'], objects['y'], objects['a'], objects['b'],
np.minimum(objects['theta'], np.pi / 2.00001),
2.5 * kronrad, subpix=1, err=bkg.globalrms,
gain=h['gain'])
krflag |= _flag # combine flags
wcs = WCS(h)
ra, dec = wcs.all_pix2world(objects['x'], objects['y'], 0)
tab = Table((objects['x'], objects['y'], ra, dec, flux, fluxerr,
flag, objects['a'], objects['b'], objects['theta'],
kronrad, krflux, krfluxerr, krflag),
names=('x', 'y', 'ra', 'dec', 'flux', 'fluxerr', 'flag',
'a', 'b', 'theta', 'kronrad', 'krflux',
'krfluxerr', 'krflag'))
if 'cat' in hdu:
del hdu['cat']
hdu.append(fits.BinTableHDU(tab, name='cat'))
hdu['cat'].header['FWHM'] = fwhm, 'estimated median FWHM'
hdu['cat'].header['RADIUS'] = 2 * fwhm, 'aperture photometry radius'
logger.info(f"{f}: {len(tab)} objects, seeing = {fwhm:.1f}, background mean/rms = "
f"{hdu['bg'].header['bg']:.1f}/{hdu['bg'].header['rms']:.1f}")
| [
"numpy.ptp",
"sep.kron_radius",
"logging.StreamHandler",
"astropy.table.Table",
"numpy.array",
"sep.Background",
"numpy.isfinite",
"astropy.io.fits.open",
"astropy.modeling.models.Const2D",
"numpy.mean",
"argparse.ArgumentParser",
"numpy.ma.count",
"astropy.modeling.Parameter",
"astropy.wc... | [((658, 683), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (681, 683), False, 'import argparse\n'), ((4104, 4137), 'logging.Logger', 'logging.Logger', (['"""LMI Add Catalog"""'], {}), "('LMI Add Catalog')\n", (4118, 4137), False, 'import logging\n'), ((4923, 4972), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""', 'FITSFixedWarning'], {}), "('ignore', FITSFixedWarning)\n", (4944, 4972), False, 'import warnings\n'), ((1942, 1962), 'astropy.modeling.Parameter', 'Parameter', ([], {'default': '(1)'}), '(default=1)\n', (1951, 1962), False, 'from astropy.modeling import Fittable2DModel, Parameter\n'), ((1979, 1999), 'astropy.modeling.Parameter', 'Parameter', ([], {'default': '(1)'}), '(default=1)\n', (1988, 1999), False, 'from astropy.modeling import Fittable2DModel, Parameter\n'), ((2013, 2033), 'astropy.modeling.Parameter', 'Parameter', ([], {'default': '(0)'}), '(default=0)\n', (2022, 2033), False, 'from astropy.modeling import Fittable2DModel, Parameter\n'), ((2047, 2067), 'astropy.modeling.Parameter', 'Parameter', ([], {'default': '(0)'}), '(default=0)\n', (2056, 2067), False, 'from astropy.modeling import Fittable2DModel, Parameter\n'), ((2083, 2103), 'astropy.modeling.Parameter', 'Parameter', ([], {'default': '(1)'}), '(default=1)\n', (2092, 2103), False, 'from astropy.modeling import Fittable2DModel, Parameter\n'), ((2119, 2139), 'astropy.modeling.Parameter', 'Parameter', ([], {'default': '(1)'}), '(default=1)\n', (2128, 2139), False, 'from astropy.modeling import Fittable2DModel, Parameter\n'), ((2152, 2172), 'astropy.modeling.Parameter', 'Parameter', ([], {'default': '(0)'}), '(default=0)\n', (2161, 2172), False, 'from astropy.modeling import Fittable2DModel, Parameter\n'), ((3596, 3608), 'numpy.ptp', 'np.ptp', (['data'], {}), '(data)\n', (3602, 3608), True, 'import numpy as np\n'), ((3899, 3916), 'astropy.modeling.fitting.LevMarLSQFitter', 'LevMarLSQFitter', ([], {}), '()\n', (3914, 3916), False, 'from astropy.modeling.fitting import LevMarLSQFitter\n'), ((3928, 3950), 'numpy.indices', 'np.indices', (['data.shape'], {}), '(data.shape)\n', (3938, 3950), True, 'import numpy as np\n'), ((4300, 4347), 'logging.Formatter', 'logging.Formatter', (['"""%(levelname)s: %(message)s"""'], {}), "('%(levelname)s: %(message)s')\n", (4317, 4347), False, 'import logging\n'), ((4423, 4456), 'logging.StreamHandler', 'logging.StreamHandler', (['sys.stdout'], {}), '(sys.stdout)\n', (4444, 4456), False, 'import logging\n'), ((4567, 4605), 'logging.FileHandler', 'logging.FileHandler', (['"""lmi-add-cat.log"""'], {}), "('lmi-add-cat.log')\n", (4586, 4605), False, 'import logging\n'), ((5131, 5145), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (5143, 5145), True, 'import matplotlib.pyplot as plt\n'), ((2986, 3003), 'numpy.ma.count', 'np.ma.count', (['data'], {}), '(data)\n', (2997, 3003), True, 'import numpy as np\n'), ((3513, 3525), 'numpy.min', 'np.min', (['data'], {}), '(data)\n', (3519, 3525), True, 'import numpy as np\n'), ((3549, 3569), 'numpy.array', 'np.array', (['data.shape'], {}), '(data.shape)\n', (3557, 3569), True, 'import numpy as np\n'), ((5157, 5168), 'numpy.mean', 'np.mean', (['im'], {}), '(im)\n', (5164, 5168), True, 'import numpy as np\n'), ((5170, 5180), 'numpy.std', 'np.std', (['im'], {}), '(im)\n', (5176, 5180), True, 'import numpy as np\n'), ((5382, 5530), 'matplotlib.patches.Ellipse', 'Ellipse', ([], {'xy': "(objects['x'][i], objects['y'][i])", 'width': "(6 * objects['a'][i])", 'height': "(6 * objects['b'][i])", 'angle': "(objects['theta'][i] * 180.0 / np.pi)"}), "(xy=(objects['x'][i], objects['y'][i]), width=6 * objects['a'][i],\n height=6 * objects['b'][i], angle=objects['theta'][i] * 180.0 / np.pi)\n", (5389, 5530), False, 'from matplotlib.patches import Ellipse\n'), ((5791, 5818), 'astropy.io.fits.open', 'fits.open', (['f'], {'mode': '"""update"""'}), "(f, mode='update')\n", (5800, 5818), False, 'from astropy.io import fits\n'), ((6338, 6357), 'numpy.zeros_like', 'np.zeros_like', (['mask'], {}), '(mask)\n', (6351, 6357), True, 'import numpy as np\n'), ((6657, 6718), 'sep.Background', 'sep.Background', (['im'], {'mask': '(det | mask)', 'bw': '(64)', 'bh': '(64)', 'fw': '(3)', 'fh': '(3)'}), '(im, mask=det | mask, bw=64, bh=64, fw=3, fh=3)\n', (6671, 6718), False, 'import sep\n'), ((7470, 7498), 'photutils.SegmentationImage', 'pu.SegmentationImage', (['labels'], {}), '(labels)\n', (7490, 7498), True, 'import photutils as pu\n'), ((8019, 8111), 'sep.sum_circle', 'sep.sum_circle', (['data', "objects['x']", "objects['y']", 'rap'], {'err': 'bkg.globalrms', 'gain': "h['gain']"}), "(data, objects['x'], objects['y'], rap, err=bkg.globalrms,\n gain=h['gain'])\n", (8033, 8111), False, 'import sep\n'), ((8160, 8265), 'sep.kron_radius', 'sep.kron_radius', (['data', "objects['x']", "objects['y']", "objects['a']", "objects['b']", "objects['theta']", '(6.0)'], {}), "(data, objects['x'], objects['y'], objects['a'], objects['b'\n ], objects['theta'], 6.0)\n", (8175, 8265), False, 'import sep\n'), ((8670, 8676), 'astropy.wcs.WCS', 'WCS', (['h'], {}), '(h)\n', (8673, 8676), False, 'from astropy.wcs import WCS\n'), ((8759, 9040), 'astropy.table.Table', 'Table', (["(objects['x'], objects['y'], ra, dec, flux, fluxerr, flag, objects['a'],\n objects['b'], objects['theta'], kronrad, krflux, krfluxerr, krflag)"], {'names': "('x', 'y', 'ra', 'dec', 'flux', 'fluxerr', 'flag', 'a', 'b', 'theta',\n 'kronrad', 'krflux', 'krfluxerr', 'krflag')"}), "((objects['x'], objects['y'], ra, dec, flux, fluxerr, flag, objects[\n 'a'], objects['b'], objects['theta'], kronrad, krflux, krfluxerr,\n krflag), names=('x', 'y', 'ra', 'dec', 'flux', 'fluxerr', 'flag', 'a',\n 'b', 'theta', 'kronrad', 'krflux', 'krfluxerr', 'krflag'))\n", (8764, 9040), False, 'from astropy.table import Table\n'), ((4736, 4750), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (4748, 4750), False, 'from datetime import datetime\n'), ((5700, 5717), 'astropy.io.fits.getheader', 'fits.getheader', (['f'], {}), '(f)\n', (5714, 5717), False, 'from astropy.io import fits\n'), ((6164, 6187), 'numpy.zeros_like', 'np.zeros_like', (['im', 'bool'], {}), '(im, bool)\n', (6177, 6187), True, 'import numpy as np\n'), ((6411, 6472), 'sep.Background', 'sep.Background', (['im'], {'mask': '(det | mask)', 'bw': '(64)', 'bh': '(64)', 'fw': '(3)', 'fh': '(3)'}), '(im, mask=det | mask, bw=64, bh=64, fw=3, fh=3)\n', (6425, 6472), False, 'import sep\n'), ((6619, 6641), 'scipy.ndimage.binary_closing', 'nd.binary_closing', (['det'], {}), '(det)\n', (6636, 6641), True, 'import scipy.ndimage as nd\n'), ((7014, 7076), 'sep.extract', 'sep.extract', (['data', '(3)'], {'err': 'bkg.globalrms', 'segmentation_map': '(True)'}), '(data, 3, err=bkg.globalrms, segmentation_map=True)\n', (7025, 7076), False, 'import sep\n'), ((7906, 7932), 'astropy.stats.sigma_clipped_stats', 'sigma_clipped_stats', (['fwhms'], {}), '(fwhms)\n', (7925, 7932), False, 'from astropy.stats import sigma_clipped_stats\n'), ((7962, 7979), 'numpy.isfinite', 'np.isfinite', (['fwhm'], {}), '(fwhm)\n', (7973, 7979), True, 'import numpy as np\n'), ((8483, 8528), 'numpy.minimum', 'np.minimum', (["objects['theta']", '(np.pi / 2.00001)'], {}), "(objects['theta'], np.pi / 2.00001)\n", (8493, 8528), True, 'import numpy as np\n'), ((9215, 9248), 'astropy.io.fits.BinTableHDU', 'fits.BinTableHDU', (['tab'], {'name': '"""cat"""'}), "(tab, name='cat')\n", (9231, 9248), False, 'from astropy.io import fits\n'), ((2377, 2394), 'astropy.modeling.models.Const2D', 'Const2D', (['constant'], {}), '(constant)\n', (2384, 2394), False, 'from astropy.modeling.models import Const1D, Const2D, Gaussian1D, Gaussian2D\n'), ((2403, 2467), 'astropy.modeling.models.Gaussian2D', 'Gaussian2D', (['amplitude', 'x_mean', 'y_mean', 'x_stddev', 'y_stddev', 'theta'], {}), '(amplitude, x_mean, y_mean, x_stddev, y_stddev, theta)\n', (2413, 2467), False, 'from astropy.modeling.models import Const1D, Const2D, Gaussian1D, Gaussian2D\n'), ((7756, 7801), 'numpy.mean', 'np.mean', (['(g.x_stddev.value, g.y_stddev.value)'], {}), '((g.x_stddev.value, g.y_stddev.value))\n', (7763, 7801), True, 'import numpy as np\n')] |
from __future__ import absolute_import, unicode_literals
from django.urls import include, re_path
from wagtail.admin import urls as wagtailadmin_urls
from wagtail.core import urls as wagtail_urls
from wagtail_transfer import urls as wagtailtransfer_urls
urlpatterns = [
re_path(r'^admin/', include(wagtailadmin_urls)),
re_path(r'^wagtail-transfer/', include(wagtailtransfer_urls)),
# For anything not caught by a more specific rule above, hand over to
# Wagtail's serving mechanism
re_path(r'', include(wagtail_urls)),
]
| [
"django.urls.include"
] | [((298, 324), 'django.urls.include', 'include', (['wagtailadmin_urls'], {}), '(wagtailadmin_urls)\n', (305, 324), False, 'from django.urls import include, re_path\n'), ((362, 391), 'django.urls.include', 'include', (['wagtailtransfer_urls'], {}), '(wagtailtransfer_urls)\n', (369, 391), False, 'from django.urls import include, re_path\n'), ((520, 541), 'django.urls.include', 'include', (['wagtail_urls'], {}), '(wagtail_urls)\n', (527, 541), False, 'from django.urls import include, re_path\n')] |
# Generated by Django 3.2.5 on 2021-07-30 15:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0011_auto_20210729_2147'),
]
operations = [
migrations.AddField(
model_name='curation',
name='needs_verification',
field=models.BooleanField(default=True, verbose_name='Needs Verification'),
),
migrations.AddField(
model_name='historicalcuration',
name='needs_verification',
field=models.BooleanField(default=True, verbose_name='Needs Verification'),
),
]
| [
"django.db.models.BooleanField"
] | [((345, 413), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(True)', 'verbose_name': '"""Needs Verification"""'}), "(default=True, verbose_name='Needs Verification')\n", (364, 413), False, 'from django.db import migrations, models\n'), ((557, 625), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(True)', 'verbose_name': '"""Needs Verification"""'}), "(default=True, verbose_name='Needs Verification')\n", (576, 625), False, 'from django.db import migrations, models\n')] |
import tensorflow as tf
def touch(fname: str, times=None, create_dirs: bool = False):
import os
if create_dirs:
base_dir = os.path.dirname(fname)
if not os.path.exists(base_dir):
os.makedirs(base_dir)
with open(fname, 'a'):
os.utime(fname, times)
def touch_dir(base_dir: str) -> None:
import os
if not os.path.exists(base_dir):
os.makedirs(base_dir)
def now_int():
from datetime import datetime
epoch = datetime.utcfromtimestamp(0)
return (datetime.now() - epoch).total_seconds()
def bias_variable(shape, name=None):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial, name=name)
def entry_stop_gradients(target, mask):
mask_h = tf.logical_not(mask)
mask = tf.cast(mask, dtype=target.dtype)
mask_h = tf.cast(mask_h, dtype=target.dtype)
return tf.stop_gradient(mask_h * target) + mask * target
# Adapeted from
# https://gist.github.com/kukuruza/03731dc494603ceab0c5#gistcomment-1879326
def on_grid(kernel, grid_side, pad=1):
"""Visualize conv. features as an image (mostly for the 1st layer).
Place kernel into a grid, with some paddings between adjacent filters.
Args:
kernel: tensor of shape [Y, X, NumChannels, NumKernels]
grid_side: side of the grid. Require: NumKernels == grid_side**2
pad: number of black pixels around each filter (between them)
Returns:
An image Tensor with shape [(Y+2*pad)*grid_side, (X+2*pad)*grid_side, NumChannels, 1].
"""
x_min = tf.reduce_min(kernel)
x_max = tf.reduce_max(kernel)
kernel1 = (kernel - x_min) / (x_max - x_min)
# pad X and Y
x1 = tf.pad(
kernel1,
tf.constant([[pad, pad], [pad, pad], [0, 0], [0, 0]]),
mode='CONSTANT')
# X and Y dimensions, w.r.t. padding
Y = kernel1.get_shape()[0] + 2 * pad
X = kernel1.get_shape()[1] + 2 * pad
channels = kernel1.get_shape()[2]
# put NumKernels to the 1st dimension
x2 = tf.transpose(x1, (3, 0, 1, 2))
# organize grid on Y axis
x3 = tf.reshape(x2,
tf.stack(
values=[grid_side, Y * grid_side, X, channels],
axis=0)) # 3
# switch X and Y axes
x4 = tf.transpose(x3, (0, 2, 1, 3))
# organize grid on X axis
x5 = tf.reshape(x4,
tf.stack(
values=[1, X * grid_side, Y * grid_side, channels],
axis=0)) # 3
# back to normal order (not combining with the next step for clarity)
x6 = tf.transpose(x5, (2, 1, 3, 0))
# to tf.image_summary order [batch_size, height, width, channels],
# where in this case batch_size == 1
x7 = tf.transpose(x6, (3, 0, 1, 2))
# scale to [0, 255] and convert to uint8
return tf.image.convert_image_dtype(x7, dtype=tf.uint8)
def get_last_output(output, sequence_length, name):
"""Get the last value of the returned output of an RNN.
http://disq.us/p/1gjkgdr
output: [batch x number of steps x ... ] Output of the dynamic lstm.
sequence_length: [batch] Length of each of the sequence.
"""
rng = tf.range(0, tf.shape(sequence_length)[0])
indexes = tf.stack([rng, sequence_length - 1], 1)
return tf.gather_nd(output, indexes, name)
| [
"datetime.datetime.utcfromtimestamp",
"tensorflow.reduce_min",
"os.path.exists",
"tensorflow.image.convert_image_dtype",
"tensorflow.shape",
"tensorflow.transpose",
"tensorflow.Variable",
"os.makedirs",
"tensorflow.logical_not",
"os.utime",
"tensorflow.reduce_max",
"os.path.dirname",
"tensor... | [((481, 509), 'datetime.datetime.utcfromtimestamp', 'datetime.utcfromtimestamp', (['(0)'], {}), '(0)\n', (506, 509), False, 'from datetime import datetime\n'), ((615, 644), 'tensorflow.constant', 'tf.constant', (['(0.1)'], {'shape': 'shape'}), '(0.1, shape=shape)\n', (626, 644), True, 'import tensorflow as tf\n'), ((656, 687), 'tensorflow.Variable', 'tf.Variable', (['initial'], {'name': 'name'}), '(initial, name=name)\n', (667, 687), True, 'import tensorflow as tf\n'), ((743, 763), 'tensorflow.logical_not', 'tf.logical_not', (['mask'], {}), '(mask)\n', (757, 763), True, 'import tensorflow as tf\n'), ((776, 809), 'tensorflow.cast', 'tf.cast', (['mask'], {'dtype': 'target.dtype'}), '(mask, dtype=target.dtype)\n', (783, 809), True, 'import tensorflow as tf\n'), ((823, 858), 'tensorflow.cast', 'tf.cast', (['mask_h'], {'dtype': 'target.dtype'}), '(mask_h, dtype=target.dtype)\n', (830, 858), True, 'import tensorflow as tf\n'), ((1556, 1577), 'tensorflow.reduce_min', 'tf.reduce_min', (['kernel'], {}), '(kernel)\n', (1569, 1577), True, 'import tensorflow as tf\n'), ((1590, 1611), 'tensorflow.reduce_max', 'tf.reduce_max', (['kernel'], {}), '(kernel)\n', (1603, 1611), True, 'import tensorflow as tf\n'), ((2018, 2048), 'tensorflow.transpose', 'tf.transpose', (['x1', '(3, 0, 1, 2)'], {}), '(x1, (3, 0, 1, 2))\n', (2030, 2048), True, 'import tensorflow as tf\n'), ((2279, 2309), 'tensorflow.transpose', 'tf.transpose', (['x3', '(0, 2, 1, 3)'], {}), '(x3, (0, 2, 1, 3))\n', (2291, 2309), True, 'import tensorflow as tf\n'), ((2592, 2622), 'tensorflow.transpose', 'tf.transpose', (['x5', '(2, 1, 3, 0)'], {}), '(x5, (2, 1, 3, 0))\n', (2604, 2622), True, 'import tensorflow as tf\n'), ((2747, 2777), 'tensorflow.transpose', 'tf.transpose', (['x6', '(3, 0, 1, 2)'], {}), '(x6, (3, 0, 1, 2))\n', (2759, 2777), True, 'import tensorflow as tf\n'), ((2835, 2883), 'tensorflow.image.convert_image_dtype', 'tf.image.convert_image_dtype', (['x7'], {'dtype': 'tf.uint8'}), '(x7, dtype=tf.uint8)\n', (2863, 2883), True, 'import tensorflow as tf\n'), ((3235, 3274), 'tensorflow.stack', 'tf.stack', (['[rng, sequence_length - 1]', '(1)'], {}), '([rng, sequence_length - 1], 1)\n', (3243, 3274), True, 'import tensorflow as tf\n'), ((3286, 3321), 'tensorflow.gather_nd', 'tf.gather_nd', (['output', 'indexes', 'name'], {}), '(output, indexes, name)\n', (3298, 3321), True, 'import tensorflow as tf\n'), ((141, 163), 'os.path.dirname', 'os.path.dirname', (['fname'], {}), '(fname)\n', (156, 163), False, 'import os\n'), ((274, 296), 'os.utime', 'os.utime', (['fname', 'times'], {}), '(fname, times)\n', (282, 296), False, 'import os\n'), ((362, 386), 'os.path.exists', 'os.path.exists', (['base_dir'], {}), '(base_dir)\n', (376, 386), False, 'import os\n'), ((396, 417), 'os.makedirs', 'os.makedirs', (['base_dir'], {}), '(base_dir)\n', (407, 417), False, 'import os\n'), ((871, 904), 'tensorflow.stop_gradient', 'tf.stop_gradient', (['(mask_h * target)'], {}), '(mask_h * target)\n', (887, 904), True, 'import tensorflow as tf\n'), ((1723, 1776), 'tensorflow.constant', 'tf.constant', (['[[pad, pad], [pad, pad], [0, 0], [0, 0]]'], {}), '([[pad, pad], [pad, pad], [0, 0], [0, 0]])\n', (1734, 1776), True, 'import tensorflow as tf\n'), ((2123, 2187), 'tensorflow.stack', 'tf.stack', ([], {'values': '[grid_side, Y * grid_side, X, channels]', 'axis': '(0)'}), '(values=[grid_side, Y * grid_side, X, channels], axis=0)\n', (2131, 2187), True, 'import tensorflow as tf\n'), ((2384, 2452), 'tensorflow.stack', 'tf.stack', ([], {'values': '[1, X * grid_side, Y * grid_side, channels]', 'axis': '(0)'}), '(values=[1, X * grid_side, Y * grid_side, channels], axis=0)\n', (2392, 2452), True, 'import tensorflow as tf\n'), ((179, 203), 'os.path.exists', 'os.path.exists', (['base_dir'], {}), '(base_dir)\n', (193, 203), False, 'import os\n'), ((217, 238), 'os.makedirs', 'os.makedirs', (['base_dir'], {}), '(base_dir)\n', (228, 238), False, 'import os\n'), ((3191, 3216), 'tensorflow.shape', 'tf.shape', (['sequence_length'], {}), '(sequence_length)\n', (3199, 3216), True, 'import tensorflow as tf\n'), ((522, 536), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (534, 536), False, 'from datetime import datetime\n')] |
# Some of the implementation inspired by:
# REF: https://github.com/fchen365/epca
import time
from abc import abstractmethod
import numpy as np
from factor_analyzer import Rotator
from sklearn.base import BaseEstimator
from sklearn.preprocessing import StandardScaler
from sklearn.utils import check_array
from graspologic.embed import selectSVD
from ..utils import calculate_explained_variance_ratio, soft_threshold
from scipy.linalg import orthogonal_procrustes
def _varimax(X):
return Rotator(normalize=False).fit_transform(X)
def _polar(X):
# REF: https://en.wikipedia.org/wiki/Polar_decomposition#Relation_to_the_SVD
U, D, Vt = selectSVD(X, n_components=X.shape[1], algorithm="full")
return U @ Vt
def _polar_rotate_shrink(X, gamma=0.1):
# Algorithm 1 from the paper
U, _, _ = selectSVD(X, n_components=X.shape[1], algorithm="full")
# U = _polar(X)
# R, _ = orthogonal_procrustes(U_old, U)
# print(np.linalg.norm(U_old @ R - U))
U_rot = _varimax(U)
U_thresh = soft_threshold(U_rot, gamma)
return U_thresh
def _reorder_components(X, Z_hat, Y_hat):
score_norms = np.linalg.norm(X @ Y_hat, axis=0)
sort_inds = np.argsort(-score_norms)
return Z_hat[:, sort_inds], Y_hat[:, sort_inds]
# import abc
# class SuperclassMeta(type):
# def __new__(mcls, classname, bases, cls_dict):
# cls = super().__new__(mcls, classname, bases, cls_dict)
# for name, member in cls_dict.items():
# if not getattr(member, "__doc__"):
# member.__doc__ = getattr(bases[-1], name).__doc__
# return cls
class BaseSparseDecomposition(BaseEstimator):
def __init__(
self,
n_components=2,
gamma=None,
max_iter=10,
scale=False,
center=False,
tol=1e-4,
verbose=0,
):
"""Sparse matrix decomposition model.
Parameters
----------
n_components : int, optional (default=2)
Number of components or embedding dimensions.
gamma : float, int or None, optional (default=None)
Sparsity parameter, must be nonnegative. Lower values lead to more sparsity
in the estimated components. If ``None``, will be set to
``sqrt(n_components * X.shape[1])`` where ``X`` is the matrix passed to
``fit``.
max_iter : int, optional (default=10)
Maximum number of iterations allowed, must be nonnegative.
scale : bool, optional
[description], by default False
center : bool, optional
[description], by default False
tol : float or int, optional (default=1e-4)
Tolerance for stopping iterative optimization. If the relative difference in
score is less than this amount the algorithm will terminate.
verbose : int, optional (default=0)
Verbosity level. Higher values will result in more messages.
"""
self.n_components = n_components
self.gamma = gamma
self.max_iter = max_iter
self.scale = scale
self.center = center
self.tol = tol
self.verbose = verbose
# TODO add random state
def _initialize(self, X):
"""[summary]
Parameters
----------
X : [type]
[description]
Returns
-------
[type]
[description]
"""
U, D, Vt = selectSVD(X, n_components=self.n_components)
score = np.linalg.norm(D)
return U, Vt.T, score
def _validate_parameters(self, X):
"""[summary]
Parameters
----------
X : [type]
[description]
"""
if not self.gamma:
gamma = np.sqrt(self.n_components * X.shape[1])
else:
gamma = self.gamma
self.gamma_ = gamma
def _preprocess_data(self, X):
"""[summary]
Parameters
----------
X : [type]
[description]
Returns
-------
[type]
[description]
"""
if self.scale or self.center:
X = StandardScaler(
with_mean=self.center, with_std=self.scale
).fit_transform(X)
return X
# def _compute_matrix_difference(X, metric='max'):
# TODO better convergence criteria
def fit_transform(self, X, y=None):
"""[summary]
Parameters
----------
X : [type]
[description]
y : [type], optional
[description], by default None
Returns
-------
[type]
[description]
"""
self._validate_parameters(X)
self._validate_data(X, copy=True, ensure_2d=True) # from sklearn BaseEstimator
Z_hat, Y_hat, score = self._initialize(X)
if self.gamma == np.inf:
max_iter = 0
else:
max_iter = self.max_iter
# for keeping track of progress over iteration
Z_diff = np.inf
Y_diff = np.inf
norm_score_diff = np.inf
last_score = 0
# main loop
i = 0
while (i < max_iter) and (norm_score_diff > self.tol):
if self.verbose > 0:
print(f"Iteration: {i}")
iter_time = time.time()
Z_hat_new, Y_hat_new = self._update_estimates(X, Z_hat, Y_hat)
# Z_hat_new, Y_hat_new = _reorder_components(X, Z_hat_new, Y_hat_new)
Z_diff = np.linalg.norm(Z_hat_new - Z_hat)
Y_diff = np.linalg.norm(Y_hat_new - Y_hat)
norm_Z_diff = Z_diff / np.linalg.norm(Z_hat_new)
norm_Y_diff = Y_diff / np.linalg.norm(Y_hat_new)
Z_hat = Z_hat_new
Y_hat = Y_hat_new
B_hat = Z_hat.T @ X @ Y_hat
score = np.linalg.norm(B_hat)
norm_score_diff = np.abs(score - last_score) / score
last_score = score
if self.verbose > 1:
print(f"{time.time() - iter_time:.3f} seconds elapsed for iteration.")
if self.verbose > 0:
print(f"Difference in Z_hat: {Z_diff}")
print(f"Difference in Y_hat: {Z_diff}")
print(f"Normalized difference in Z_hat: {norm_Z_diff}")
print(f"Normalized difference in Y_hat: {norm_Y_diff}")
print(f"Total score: {score}")
print(f"Normalized difference in score: {norm_score_diff}")
print()
i += 1
Z_hat, Y_hat = _reorder_components(X, Z_hat, Y_hat)
# save attributes
self.n_iter_ = i
self.components_ = Y_hat.T
# TODO this should not be cumulative by the sklearn definition
self.explained_variance_ratio_ = calculate_explained_variance_ratio(X, Y_hat)
self.score_ = score
return Z_hat
def fit(self, X):
"""[summary]
Parameters
----------
X : [type]
[description]
Returns
-------
[type]
[description]
"""
self.fit_transform(X)
return self
def transform(self, X):
"""[summary]
Parameters
----------
X : [type]
[description]
Returns
-------
[type]
[description]
"""
# TODO input checking
return X @ self.components_.T
@abstractmethod
def _update_estimates(self, X, Z_hat, Y_hat):
"""[summary]
Parameters
----------
X : [type]
[description]
Z_hat : [type]
[description]
Y_hat : [type]
[description]
"""
pass
class SparseComponentAnalysis(BaseSparseDecomposition):
def _update_estimates(self, X, Z_hat, Y_hat):
"""[summary]
Parameters
----------
X : [type]
[description]
Z_hat : [type]
[description]
Y_hat : [type]
[description]
Returns
-------
[type]
[description]
"""
Y_hat = _polar_rotate_shrink(X.T @ Z_hat, gamma=self.gamma)
Z_hat = _polar(X @ Y_hat)
return Z_hat, Y_hat
def _save_attributes(self, X, Z_hat, Y_hat):
"""[summary]
Parameters
----------
X : [type]
[description]
Z_hat : [type]
[description]
Y_hat : [type]
[description]
"""
pass
class SparseMatrixApproximation(BaseSparseDecomposition):
def _update_estimates(self, X, Z_hat, Y_hat):
"""[summary]
Parameters
----------
X : [type]
[description]
Z_hat : [type]
[description]
Y_hat : [type]
[description]
Returns
-------
[type]
[description]
"""
Z_hat = _polar_rotate_shrink(X @ Y_hat)
Y_hat = _polar_rotate_shrink(X.T @ Z_hat)
return Z_hat, Y_hat
def _save_attributes(self, X, Z_hat, Y_hat):
"""[summary]
Parameters
----------
X : [type]
[description]
Z_hat : [type]
[description]
Y_hat : [type]
[description]
"""
B = Z_hat.T @ X @ Y_hat
self.score_ = B
self.right_latent_ = Y_hat
self.left_latent_ = Z_hat
| [
"factor_analyzer.Rotator",
"numpy.abs",
"numpy.sqrt",
"graspologic.embed.selectSVD",
"numpy.argsort",
"sklearn.preprocessing.StandardScaler",
"numpy.linalg.norm",
"time.time"
] | [((654, 709), 'graspologic.embed.selectSVD', 'selectSVD', (['X'], {'n_components': 'X.shape[1]', 'algorithm': '"""full"""'}), "(X, n_components=X.shape[1], algorithm='full')\n", (663, 709), False, 'from graspologic.embed import selectSVD\n'), ((817, 872), 'graspologic.embed.selectSVD', 'selectSVD', (['X'], {'n_components': 'X.shape[1]', 'algorithm': '"""full"""'}), "(X, n_components=X.shape[1], algorithm='full')\n", (826, 872), False, 'from graspologic.embed import selectSVD\n'), ((1131, 1164), 'numpy.linalg.norm', 'np.linalg.norm', (['(X @ Y_hat)'], {'axis': '(0)'}), '(X @ Y_hat, axis=0)\n', (1145, 1164), True, 'import numpy as np\n'), ((1181, 1205), 'numpy.argsort', 'np.argsort', (['(-score_norms)'], {}), '(-score_norms)\n', (1191, 1205), True, 'import numpy as np\n'), ((3454, 3498), 'graspologic.embed.selectSVD', 'selectSVD', (['X'], {'n_components': 'self.n_components'}), '(X, n_components=self.n_components)\n', (3463, 3498), False, 'from graspologic.embed import selectSVD\n'), ((3515, 3532), 'numpy.linalg.norm', 'np.linalg.norm', (['D'], {}), '(D)\n', (3529, 3532), True, 'import numpy as np\n'), ((499, 523), 'factor_analyzer.Rotator', 'Rotator', ([], {'normalize': '(False)'}), '(normalize=False)\n', (506, 523), False, 'from factor_analyzer import Rotator\n'), ((3767, 3806), 'numpy.sqrt', 'np.sqrt', (['(self.n_components * X.shape[1])'], {}), '(self.n_components * X.shape[1])\n', (3774, 3806), True, 'import numpy as np\n'), ((5327, 5338), 'time.time', 'time.time', ([], {}), '()\n', (5336, 5338), False, 'import time\n'), ((5519, 5552), 'numpy.linalg.norm', 'np.linalg.norm', (['(Z_hat_new - Z_hat)'], {}), '(Z_hat_new - Z_hat)\n', (5533, 5552), True, 'import numpy as np\n'), ((5574, 5607), 'numpy.linalg.norm', 'np.linalg.norm', (['(Y_hat_new - Y_hat)'], {}), '(Y_hat_new - Y_hat)\n', (5588, 5607), True, 'import numpy as np\n'), ((5852, 5873), 'numpy.linalg.norm', 'np.linalg.norm', (['B_hat'], {}), '(B_hat)\n', (5866, 5873), True, 'import numpy as np\n'), ((5643, 5668), 'numpy.linalg.norm', 'np.linalg.norm', (['Z_hat_new'], {}), '(Z_hat_new)\n', (5657, 5668), True, 'import numpy as np\n'), ((5704, 5729), 'numpy.linalg.norm', 'np.linalg.norm', (['Y_hat_new'], {}), '(Y_hat_new)\n', (5718, 5729), True, 'import numpy as np\n'), ((5904, 5930), 'numpy.abs', 'np.abs', (['(score - last_score)'], {}), '(score - last_score)\n', (5910, 5930), True, 'import numpy as np\n'), ((4161, 4219), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {'with_mean': 'self.center', 'with_std': 'self.scale'}), '(with_mean=self.center, with_std=self.scale)\n', (4175, 4219), False, 'from sklearn.preprocessing import StandardScaler\n'), ((6029, 6040), 'time.time', 'time.time', ([], {}), '()\n', (6038, 6040), False, 'import time\n')] |